xposed框架的Android网络监测模块

简介: 试图监控一个app所有的网络通信。前提 :手机root过已成功安装xposed框架XposedInstaller:https://github.

试图监控一个app所有的网络通信。

前提 :

  1. 手机root过
  2. 已成功安装xposed框架

XposedInstaller:

https://github.com/rovo89/XposedInstaller

操作步骤

  1. 添加xposed框架XposedBridgeApi-54.jar包到android项目build path

  2. assets目录下添加xposed_init文件内容为com.example.xposeddiy.Test,指示入口

  3. AndroidManifest.xml文件application标签下添加

    [[meta-data
    android:name="xposedmodule"
    android:value="true" />
    [[meta-data
    android:name="xposedminversion"
    android:value="40" />
    [[meta-data
    android:name="xposeddescription"
    android:value="network monitor" />

  4. hook android所有通信调用函数,代码如下

package com.example.xposeddiy;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;


import android.app.Activity;
import android.app.Application;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.util.Log;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodHook.MethodHookParam;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import static de.robv.android.xposed.XposedHelpers.findAndHookMethod;
import static de.robv.android.xposed.XposedHelpers.findAndHookConstructor;

//web.loadUrl("http://1.1.1.0", param);web.loadUrl("http://1.1.1.1/");web.postUrl("","");

//DatagramSocket.send(packet) 发送
//DatagramSocket DatagramSocket.bind DatagramSocket.createSocket 监听

//startupSocket对应多个socket构造函数  sock.connect  
//ServerSocket ServerSocket.bind

//SocketChannel.open(addr)  ?SocketChannel.connect?

//outputstream.write(byte[],int,int)

//httpclient.execute(post);
//urls.openConnection(); urls.openConnection(proxy);  ?urls.setRequestProperty?


//辅助记录,避免出现调用其他包进行监听 logcat | grep xuhu >>/sdcard/a.txt

public class Test implements IXposedHookLoadPackage{
private String TARGET_APP = "com.baidu.BaiduMap";
private String[] TARGET_APPS = new String[]{"com.yek.lafaso","com.vipshop.vswxk","com.baidu.BaiduMap","com.example.t1","com.baidu.fb","com.tencent.mm","com.tencent.mtt","com.nq.mdm"};
private SharedPreferences msp = null;
private Application mApp = null;
private String LOG_FILENAME = "_test_network";
private boolean NETWORK = true;
private boolean HTTP_DATA = true;
private boolean SOCKET_DATA = true;
private boolean HTTP_RESPONSE = false;
    @Override
    public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
    
    if(!Arrays.asList(TARGET_APPS).contains(lpparam.packageName))return;
   
TARGET_APP = lpparam.packageName;
if(lpparam.appInfo == null || 
           (lpparam.appInfo.flags & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) !=0){
       return;
   }else if(true){//lpparam.isFirstApplication
   
    hookOncreate(lpparam);//
    if(mApp != null){
    msp = mApp.getSharedPreferences(LOG_FILENAME, Activity.MODE_PRIVATE);
    }
    mLog("target", lpparam.packageName);

    //网络监控开始
    if(NETWORK){
    findAndHookConstructor(InetSocketAddress.class, String.class, int.class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            mLog("网络地址", param.args[0]+":"+param.args[1]);
               super.beforeHookedMethod(param);
           }
       });
   
    //
    findAndHookMethod("java.net.DatagramSocket", lpparam.classLoader, "send", DatagramPacket.class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            DatagramPacket d = (DatagramPacket)param.args[0];
            if(SOCKET_DATA){
            mLog("udp发送", d.getAddress()+":"+d.getPort()+":"+new String(d.getData()));
            }else{
            mLog("udp发送", d.getAddress()+":"+d.getPort());
            }
               super.beforeHookedMethod(param);
           }
       });
    findAndHookMethod("java.net.DatagramSocket", lpparam.classLoader, "createSocket", int.class, InetAddress.class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            mLog("udp监听", ((InetAddress)param.args[1]).toString()+":"+(Integer)param.args[0]);
               super.beforeHookedMethod(param);
           }
       });
    findAndHookMethod("java.net.DatagramSocket", lpparam.classLoader, "bind", SocketAddress.class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            mLog("udp监听", ((SocketAddress)param.args[0]).toString());
               super.beforeHookedMethod(param);
           }
       });
    findAndHookConstructor(DatagramSocket.class, SocketAddress.class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            mLog("udp监听", ((SocketAddress)param.args[0]).toString());
               super.beforeHookedMethod(param);
           }
       });
   
    //
    findAndHookMethod("android.webkit.WebView", lpparam.classLoader, "loadUrl", String.class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            String d = (String)param.args[0];
               mLog("webview", d);
               super.beforeHookedMethod(param);
           }
       });
    findAndHookMethod("android.webkit.WebView", lpparam.classLoader, "loadUrl", String.class, Map.class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            String d = (String)param.args[0];
            if(HTTP_DATA){
            Map d1 = (Map)param.args[1];
               mLog("webview", d+":"+d1.toString());
            }else{
            mLog("webview", d);
            }
           
               super.beforeHookedMethod(param);
           }
       });
    findAndHookMethod("android.webkit.WebView", lpparam.classLoader, "postUrl", String.class, byte[].class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            String d = (String)param.args[0];
            if(HTTP_DATA){
            String d1 = new String((byte[])param.args[1]);
               mLog("webview", d+":"+d1);
            }else{
            mLog("webview", d);
            }
           
               super.beforeHookedMethod(param);
           }
       });
   
    //
    if(SOCKET_DATA){
       findAndHookMethod("java.io.OutputStream", lpparam.classLoader, "write", byte[].class, int.class, int.class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            byte[] d = (byte[])param.args[0];
            mLog("socketdata", new String(d));
               super.beforeHookedMethod(param);
           }
       });
       findAndHookMethod("java.io.OutputStream", lpparam.classLoader, "write", byte[].class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            byte[] d = (byte[])param.args[0];
            mLog("socketdata1", new String(d));
               super.beforeHookedMethod(param);
           }
       });
    }
    findAndHookMethod("java.nio.channels.SocketChannel", lpparam.classLoader, "open", SocketAddress.class, new XC_MethodHook() {
      @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
            mLog("tcp连接", ((SocketAddress)param.args[0]).toString());
               super.beforeHookedMethod(param);
           }
       });
   
    findAndHookMethod("java.net.Socket", lpparam.classLoader, "startupSocket", InetAddress.class, int.class, InetAddress.class, int.class, boolean.class, new XC_MethodHook() { 
           @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
               mLog("tcp连接", ((InetAddress)param.args[0]).toString()+":"+(Integer)param.args[1]);
               super.beforeHookedMethod(param);
           }
       });
    findAndHookMethod("java.net.Socket", lpparam.classLoader, "connect", SocketAddress.class, int.class, new XC_MethodHook() { 
           @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
               mLog("tcp连接", ((SocketAddress)param.args[0]).toString());
               super.beforeHookedMethod(param);
           }
       });
    findAndHookConstructor(ServerSocket.class, int.class, int.class, InetAddress.class, new XC_MethodHook() { 
           @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
               mLog("tcp监听", ((InetAddress)param.args[0]).toString());
               super.beforeHookedMethod(param);
           }
       });
       findAndHookMethod("java.net.ServerSocket", lpparam.classLoader, "bind", SocketAddress.class, int.class, new XC_MethodHook() {
    @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
               mLog("tcp监听", ((SocketAddress)param.args[0]).toString());
               super.beforeHookedMethod(param);
           }
       });
       
       //
       findAndHookMethod("java.net.URL", lpparam.classLoader, "openConnection", java.net.Proxy.class, new XC_MethodHook() {
    @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
               URL url = (URL) param.thisObject;
               mLog("urlconnp", url.toString()+":"+((Proxy)param.args[0]).toString());
               super.beforeHookedMethod(param);
           }
       });
       if(HTTP_DATA){
    findAndHookMethod("java.net.URLConnection", lpparam.classLoader, "setRequestProperty", String.class, String.class, new XC_MethodHook() {
    @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
               mLog("urlconnheader", (String)param.args[0]+":"+(String)param.args[1]);
               super.beforeHookedMethod(param);
           }

       });
    findAndHookMethod("java.net.URLConnection", lpparam.classLoader, "addRequestProperty", String.class, String.class, new XC_MethodHook() {
    @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
               mLog("urlconnheader", (String)param.args[0]+":"+(String)param.args[1]);
               super.beforeHookedMethod(param);
           }
   
       });
       }
    findAndHookMethod("java.net.URL", lpparam.classLoader, "openConnection", new XC_MethodHook() {
    @Override
           protected void beforeHookedMethod(MethodHookParam param)
                   throws Throwable {
               URL url = (URL) param.thisObject;
               mLog("urlconn", url.toString());
               super.beforeHookedMethod(param);
           }
       });
    //
    hookHttpClient(lpparam);

    }//网络监控结束
        }
    }
    
    public void mLog(String tag, String text){
    Log.i(TARGET_APP, "xuhu"+tag+":"+text);
    if(msp != null){
    if(HTTP_DATA){
    mSharePrefer(text,tag);
    }else{
    int i = text.indexOf("?");
    if(i > 0)
    mSharePrefer(text.substring(0, i), tag);
    else
    mSharePrefer(text, tag);
    }
    }
    }
    public void mSharePrefer(String key, String value){
SharedPreferences.Editor editor = msp.edit();
editor.putString(key, value);
editor.commit();
}
    
    public void hookHttpClient(LoadPackageParam lpparam){
    findAndHookMethod("org.apache.http.impl.client.AbstractHttpClient", lpparam.classLoader,
"execute", HttpHost.class, HttpRequest.class, HttpContext.class, new XC_MethodHook() {
     
            @Override
            protected void beforeHookedMethod(MethodHookParam param)
                    throws Throwable {
            //HttpHost host = (HttpHost) param.args[0];
HttpRequest request = (HttpRequest) param.args[1];
if (request instanceof HttpGet) {
HttpGet httpGet = (HttpGet) request;
mLog("httpclientGet", httpGet.getURI().toString());
if(HTTP_DATA){
Header[] headers = request.getAllHeaders();
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
mLog("getHeader", headers[i].getName() + ": " + headers[i].getValue());
}
}}
} else if (request instanceof HttpPost) {
HttpPost httpPost = (HttpPost) request;
mLog("httpclientPost", httpPost.getURI().toString());
if(HTTP_DATA){// until get header
Header[] headers = request.getAllHeaders();
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
mLog("postHeader", headers[i].getName() + ":" + headers[i].getValue());
}
}
HttpEntity entity = httpPost.getEntity();
String contentType = null;
if (entity.getContentType() != null) {
contentType = entity.getContentType().getValue();
if (URLEncodedUtils.CONTENT_TYPE.equals(contentType)) {
try {
byte[] data = new byte[(int) entity.getContentLength()];
entity.getContent().read(data);
String content = new String(data, HTTP.DEFAULT_CONTENT_CHARSET);
mLog("postcontent",content);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (contentType.startsWith(HTTP.DEFAULT_CONTENT_TYPE)) {
try {
byte[] data = new byte[(int) entity.getContentLength()];
entity.getContent().read(data);
String content = new String(data, contentType.substring(contentType.lastIndexOf("=") + 1));
mLog("postcontent",content);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
byte[] data = new byte[(int) entity.getContentLength()];
try {
entity.getContent().read(data);
String content = new String(data, HTTP.DEFAULT_CONTENT_CHARSET);
mLog("postcontent",content);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}//get header
}else{
HttpEntityEnclosingRequestBase get = (HttpEntityEnclosingRequestBase)request;
HttpEntity entity = get.getEntity();
mLog("Android-async-http", get.getURI().toString());
if(HTTP_DATA){
Header[] headers = request.getAllHeaders();
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
mLog("Android-async-httpHeader", headers[i].getName() + ":" + headers[i].getValue());
}
}
if(entity!= null){
String content = EntityUtils.toString(entity);
                       mLog("Android-async-httpcontent", content);
}
}
}
                super.beforeHookedMethod(param);
            }

            @Override
            protected void afterHookedMethod(MethodHookParam param)
                    throws Throwable { 
            HttpResponse resp = (HttpResponse) param.getResult();
if (resp != null && HTTP_RESPONSE) {
mLog("Status Code", ""+resp.getStatusLine().getStatusCode());
Header[] headers = resp.getAllHeaders();
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
mLog("response", headers[i].getName() + ":" + headers[i].getValue());
}
}

}
                super.afterHookedMethod(param);
            }
        });
    }
    
    public void hookOncreate(LoadPackageParam lpparam){
    String appClassName = lpparam.appInfo.className;
    if (appClassName == null) {
    Method hookOncreateMethod = null;
try {
hookOncreateMethod = Application.class.getDeclaredMethod("onCreate", new Class[] {});
} catch (NoSuchMethodException e) {
e.printStackTrace();
mLog("target0", "target");
}
    XposedBridge.hookMethod(hookOncreateMethod, new ApplicationOnCreateHook("target0",lpparam));
    }else{
    Class[[?> hook_application_class = null;
try {
hook_application_class = lpparam.classLoader.loadClass(appClassName);
if (hook_application_class != null) {
Method hookOncreateMethod = hook_application_class.getDeclaredMethod("onCreate", new Class[] {});
if (hookOncreateMethod != null) {
XposedBridge.hookMethod(hookOncreateMethod, new ApplicationOnCreateHook("target1",lpparam));
}
}
mLog("target11", "target");
} catch (Exception e) {
// TODO Auto-generated catch block
Method hookOncreateMethod;
try {
hookOncreateMethod = Application.class.getDeclaredMethod("onCreate", new Class[] {});
if (hookOncreateMethod != null) {
XposedBridge.hookMethod(hookOncreateMethod, new ApplicationOnCreateHook("target2",lpparam));
}
mLog("target21", "target");
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
mLog("target3", "target");
e1.printStackTrace();
}

}
    }
    }
    private class ApplicationOnCreateHook extends XC_MethodHook {
    public String which;
    public LoadPackageParam lpparam;
public ApplicationOnCreateHook(String which, LoadPackageParam lpparam){
this.which = which;
this.lpparam = lpparam;
}
@Override
public void afterHookedMethod(MethodHookParam param) throws FileNotFoundException {
mLog("", which);
if (!HAS_REGISTER_LISENER) {
mApp = (lpparam.isFirstApplication)?(Application) param.thisObject:mApp;
IntentFilter filter = new IntentFilter("xuhuafeng");
mApp.registerReceiver(new CommandBroadcastReceiver(), filter);
msp = mApp.getSharedPreferences(LOG_FILENAME, Activity.MODE_PRIVATE);
HAS_REGISTER_LISENER = true;
}
}

}
    private boolean HAS_REGISTER_LISENER = false;
}


相关文章
|
2月前
|
开发框架 前端开发 Android开发
Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势
本文深入探讨了 Flutter 与原生模块(Android 和 iOS)之间的通信机制,包括方法调用、事件传递等,分析了通信的必要性、主要方式、数据传递、性能优化及错误处理,并通过实际案例展示了其应用效果,展望了未来的发展趋势。这对于实现高效的跨平台移动应用开发具有重要指导意义。
192 4
|
2月前
|
数据采集 存储 JSON
Python网络爬虫:Scrapy框架的实战应用与技巧分享
【10月更文挑战第27天】本文介绍了Python网络爬虫Scrapy框架的实战应用与技巧。首先讲解了如何创建Scrapy项目、定义爬虫、处理JSON响应、设置User-Agent和代理,以及存储爬取的数据。通过具体示例,帮助读者掌握Scrapy的核心功能和使用方法,提升数据采集效率。
116 6
|
9天前
|
存储 安全 物联网
浅析Kismet:无线网络监测与分析工具
Kismet是一款开源的无线网络监测和入侵检测系统(IDS),支持Wi-Fi、Bluetooth、ZigBee等协议,具备被动监听、实时数据分析、地理定位等功能。广泛应用于安全审计、网络优化和频谱管理。本文介绍其安装配置、基本操作及高级应用技巧,帮助用户掌握这一强大的无线网络安全工具。
39 9
浅析Kismet:无线网络监测与分析工具
|
18天前
|
机器学习/深度学习 算法 PyTorch
基于图神经网络的大语言模型检索增强生成框架研究:面向知识图谱推理的优化与扩展
本文探讨了图神经网络(GNN)与大型语言模型(LLM)结合在知识图谱问答中的应用。研究首先基于G-Retriever构建了探索性模型,然后深入分析了GNN-RAG架构,通过敏感性研究和架构改进,显著提升了模型的推理能力和答案质量。实验结果表明,改进后的模型在多个评估指标上取得了显著提升,特别是在精确率和召回率方面。最后,文章提出了反思机制和教师网络的概念,进一步增强了模型的推理能力。
45 4
基于图神经网络的大语言模型检索增强生成框架研究:面向知识图谱推理的优化与扩展
|
2月前
|
Linux iOS开发 网络架构
如何使用 Ping 命令监测网络丢包情况?
如何使用 Ping 命令监测网络丢包情况?
446 48
|
2月前
|
人工智能 自然语言处理
WebDreamer:基于大语言模型模拟网页交互增强网络规划能力的框架
WebDreamer是一个基于大型语言模型(LLMs)的网络智能体框架,通过模拟网页交互来增强网络规划能力。它利用GPT-4o作为世界模型,预测用户行为及其结果,优化决策过程,提高性能和安全性。WebDreamer的核心在于“做梦”概念,即在实际采取行动前,用LLM预测每个可能步骤的结果,并选择最有可能实现目标的行动。
64 1
WebDreamer:基于大语言模型模拟网页交互增强网络规划能力的框架
|
2月前
|
JSON 数据处理 Swift
Swift 中的网络编程,主要介绍了 URLSession 和 Alamofire 两大框架的特点、用法及实际应用
本文深入探讨了 Swift 中的网络编程,主要介绍了 URLSession 和 Alamofire 两大框架的特点、用法及实际应用。URLSession 由苹果提供,支持底层网络控制;Alamofire 则是在 URLSession 基础上增加了更简洁的接口和功能扩展。文章通过具体案例对比了两者的使用方法,帮助开发者根据需求选择合适的网络编程工具。
35 3
|
2月前
|
存储 安全 网络安全
网络安全法律框架:全球视角下的合规性分析
网络安全法律框架:全球视角下的合规性分析
56 1
|
2月前
|
算法 JavaScript Android开发
|
2月前
|
数据采集 前端开发 中间件
Python网络爬虫:Scrapy框架的实战应用与技巧分享
【10月更文挑战第26天】Python是一种强大的编程语言,在数据抓取和网络爬虫领域应用广泛。Scrapy作为高效灵活的爬虫框架,为开发者提供了强大的工具集。本文通过实战案例,详细解析Scrapy框架的应用与技巧,并附上示例代码。文章介绍了Scrapy的基本概念、创建项目、编写简单爬虫、高级特性和技巧等内容。
97 4

热门文章

最新文章