xposed框架的Android网络监测模块

试图监控一个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;
}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,392评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,580评论 18 139
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,394评论 2 45
  • 七律/葱 作者:心博、图片:网络 下身殷实上身空,一半掩埋黄土中。 绿叶朝天锥立起,轻风拂体笔弯弓。 佳肴调味焉能...
    心博1阅读 820评论 0 1
  • EOSDevHelper是一个跨平台PC端EOS钱包工具,由OracleChain团队研发。 EOS开发助手是一个...
    糖果果老师阅读 546评论 0 0