Android Dns全局Hosts映射方案

原创
07/07 07:20
阅读数 274

一、需求说明

开发中经常需要做一些网络请求,涉及到线上线下的灰度、正式环境切换,有时因为服务的不同,那么app内会存在多个域名的情况,甚至有些域名被添加到aar或者jar包中,修改起来也非常困难。一般的话利用fiddler或者charles去处理,然后修改电脑的域名映射,这种情况几乎处理了很多需求问题,也是非常可靠实用的方案。当然,这种操作一般很适合测试人员,对于开发来说,显的太繁重了。

那么有没有直接修改手机Hosts的方式呢?

早期的Android版本或者经过root的android系统都是可以实现的,但后期的版本经过大修,无论是解析还是权限,成本非常高,不过Android提供了另外一种方式是VpnService,其实可以通过VpnService可以去拦截,具体参考《PureHost开源项目》,这种要求具备协议编程的基础,当然实用性更高,另外一种是Hook InetAddress解析实现,实现起来也比较容易,但只支持Android 7.0 之后的版本,当然本篇主要是第二种,主要目的是应对基本的环境切换问题。

开源地址:https://gitee.com/smartian_git/DnsHosts

二、InetAddress DNS解析

在JDK中,无论走哪种带域名的网络连接,都会毫无例外的走InetAdress中的实现,去查询DNS,我们这里Hook InetAddress中的实现

public class DnsInetAddress implements InvocationHandler {

    private DnsHostsManager mDnsResoverManager;
    private RealInvocationHandler mInvocationHandler;

    public DnsInetAddress(DnsHostsManager dnsResoverManager) {
        this.mDnsResoverManager = dnsResoverManager;
        this.mInvocationHandler = newInvocationHandler();
    }

    private RealInvocationHandler newInvocationHandler() {
        try {
            return new RealInvocationHandler();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Object createProxyInstance(Object realImpl) {
        try {
            Class<?>[] interfaces = realImpl.getClass().getInterfaces();
            return Proxy.newProxyInstance(DnsInetAddress.class.getClassLoader(), interfaces, this);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void hook() {
        try {
            if (mInvocationHandler == null) {
                return;
            }
            Field addressImplField = mInvocationHandler.getAddressImplField();
            if (addressImplField == null) {
                return;
            }
            Object proxyInstance = createProxyInstance(mInvocationHandler.getAddressImpl());
            if (proxyInstance == null) {
                return;
            }
            addressImplField.set(InetAddress.class, proxyInstance);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        boolean shouldHookProxy = mDnsResoverManager.shouldHookProxy(method, args);
        if (shouldHookProxy) {
            Object result = mDnsResoverManager.lookup(method.getName(), method.getParameterTypes(), args);
            if (result != null) {
                return result;
            }
        }
        return mInvocationHandler.invoke(proxy, method, args);
    }

    static class RealInvocationHandler implements InvocationHandler {
        private Object mAddressImpl_instance;
        private Field addressImplField;

        public RealInvocationHandler() throws NoSuchFieldException, IllegalAccessException {
            this.addressImplField = getInetAddressImplField();
            if (addressImplField != null) {
                this.mAddressImpl_instance = addressImplField.get(null);
            }
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable  {
            try {
                Object result = method.invoke(mAddressImpl_instance, args);
                return result;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }catch (Exception e){
                throw  e;
            }
            return null;
        }
        public Object getAddressImpl() {
            return mAddressImpl_instance;
        }
        public Field getAddressImplField() {
            return addressImplField;
        }
    }
    public static Field getInetAddressImplField() throws NoSuchFieldException, IllegalAccessException {
        Field InetAddress_impl = InetAddress.class.getDeclaredField("impl");
        InetAddress_impl.setAccessible(true);
        return InetAddress_impl;
    }
}

拦截实现

public class DnsHookProxyImpl {
    private final DnsHostList dnsHostList;
    private static Method sHolderMethod = null;

    public DnsHookProxyImpl(DnsHostList dnsHostList) {
        this.dnsHostList = dnsHostList;
    }

    public InetAddress[] lookupAllHostAddr(String hostname, int netId) throws UnknownHostException {
        boolean hostNameIsIpAddress = InetAddressUtils.isMatcherIpV4OrIpV6(hostname);
        if(hostNameIsIpAddress){
            return null;
        }
        String lookupIp = dnsHostList.lookup(hostname, netId);
        if(TextUtils.isEmpty(lookupIp)){
            return null;
        }
        InetAddress address = createInetAddress(hostname,lookupIp);
        return new InetAddress[]{
                address
        };
    }

    private InetAddress createInetAddress(String hostname, String lookupIp) {
        InetAddress inetAddress = null;
        try {
            if(InetAddressUtils.isIPv4LiteralAddress(lookupIp)) {
                Constructor<Inet4Address> declaredConstructor = Inet4Address.class.getDeclaredConstructor(String.class, byte[].class);
                declaredConstructor.setAccessible(true);
                inetAddress = declaredConstructor.newInstance(hostname, InetAddressUtils.textToNumericFormatV4(lookupIp));
            }else if(InetAddressUtils.isIPv6LiteralAddress(lookupIp)){
                Constructor<Inet6Address> declaredConstructor = Inet6Address.class.getDeclaredConstructor(String.class, byte[].class);
                declaredConstructor.setAccessible(true);
                inetAddress = declaredConstructor.newInstance(hostname, InetAddressUtils.textToNumericFormatV6(lookupIp));
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return inetAddress;
    }



    public boolean canLookup() {
        if(dnsHostList!=null && !dnsHostList.isEmpty()){
            return true;
        }
        return false;
    }

    public final static String METHODS[] = {
            "lookupAllHostAddr"
    };

    public boolean isHookMethod(String methodName) {
        return Arrays.asList(METHODS).contains(methodName);
    }
}

三、用法和测试

用法

  Map<String,String> dnsMap = new HashMap<>();
  dnsMap.put("www.baidu.com","127.0.0.1");
  dnsMap.put("www.taobao.com", "2001:0db8:3c4d:0015:0000:0000:1a2f:1a2b");
  DnsHostsManager.registerDns(dnsMap);

测试:

    try {
            //被映射的域名
            InetAddress baidu = InetAddress.getByName("www.baidu.com");
            Log.d("DnsManager"," == " +baidu);
            InetAddress[] taobao = InetAddress.getAllByName("www.taobao.com");
            Log.d("DnsManager"," == " +taobao[0]);

            //未被映射的域名,走原有解析
            InetAddress tmall = InetAddress.getByName("www.tmall.com");
            Log.d("DnsManager"," == " +tmall);
            InetAddress qq = InetAddress.getByName("www.qq.com");
            Log.d("DnsManager"," == " +qq);
        } catch (Exception e) {
            e.printStackTrace();
        }

测试结果

D/DnsManager:  == www.baidu.com/127.0.0.1
D/DnsManager:  == www.taobao.com/2001:db8:3c4d:15::1a2f:1a2b
D/DnsManager:  == www.tmall.com/27.221.93.231
D/DnsManager:  == www.qq.com/220.194.120.49

 

 

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部