Search in sources :

Example 51 with Inet4Address

use of java.net.Inet4Address in project NetGuard by M66B.

the class ServiceSinkhole method getDns.

public static List<InetAddress> getDns(Context context) {
    List<InetAddress> listDns = new ArrayList<>();
    List<String> sysDns = Util.getDefaultDNS(context);
    // Get custom DNS servers
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean ip6 = prefs.getBoolean("ip6", true);
    String vpnDns1 = prefs.getString("dns", null);
    String vpnDns2 = prefs.getString("dns2", null);
    Log.i(TAG, "DNS system=" + TextUtils.join(",", sysDns) + " VPN1=" + vpnDns1 + " VPN2=" + vpnDns2);
    if (vpnDns1 != null)
        try {
            InetAddress dns = InetAddress.getByName(vpnDns1);
            if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()) && (ip6 || dns instanceof Inet4Address))
                listDns.add(dns);
        } catch (Throwable ignored) {
        }
    if (vpnDns2 != null)
        try {
            InetAddress dns = InetAddress.getByName(vpnDns2);
            if (!(dns.isLoopbackAddress() || dns.isAnyLocalAddress()) && (ip6 || dns instanceof Inet4Address))
                listDns.add(dns);
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
    // Use system DNS servers only when no two custom DNS servers specified
    if (listDns.size() <= 1)
        for (String def_dns : sysDns) try {
            InetAddress ddns = InetAddress.getByName(def_dns);
            if (!listDns.contains(ddns) && !(ddns.isLoopbackAddress() || ddns.isAnyLocalAddress()) && (ip6 || ddns instanceof Inet4Address))
                listDns.add(ddns);
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
    // Remove local DNS servers when not routing LAN
    boolean lan = prefs.getBoolean("lan", false);
    boolean use_hosts = prefs.getBoolean("filter", false) && prefs.getBoolean("use_hosts", false);
    if (lan && use_hosts) {
        List<InetAddress> listLocal = new ArrayList<>();
        try {
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
            if (nis != null)
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback()) {
                        List<InterfaceAddress> ias = ni.getInterfaceAddresses();
                        if (ias != null)
                            for (InterfaceAddress ia : ias) {
                                InetAddress hostAddress = ia.getAddress();
                                BigInteger host = new BigInteger(1, hostAddress.getAddress());
                                int prefix = ia.getNetworkPrefixLength();
                                BigInteger mask = BigInteger.valueOf(-1).shiftLeft(hostAddress.getAddress().length * 8 - prefix);
                                for (InetAddress dns : listDns) if (hostAddress.getAddress().length == dns.getAddress().length) {
                                    BigInteger ip = new BigInteger(1, dns.getAddress());
                                    if (host.and(mask).equals(ip.and(mask))) {
                                        Log.i(TAG, "Local DNS server host=" + hostAddress + "/" + prefix + " dns=" + dns);
                                        listLocal.add(dns);
                                    }
                                }
                            }
                    }
                }
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
        List<InetAddress> listDns4 = new ArrayList<>();
        List<InetAddress> listDns6 = new ArrayList<>();
        try {
            listDns4.add(InetAddress.getByName("8.8.8.8"));
            listDns4.add(InetAddress.getByName("8.8.4.4"));
            if (ip6) {
                listDns6.add(InetAddress.getByName("2001:4860:4860::8888"));
                listDns6.add(InetAddress.getByName("2001:4860:4860::8844"));
            }
        } catch (Throwable ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
        for (InetAddress dns : listLocal) {
            listDns.remove(dns);
            if (dns instanceof Inet4Address) {
                if (listDns4.size() > 0) {
                    listDns.add(listDns4.get(0));
                    listDns4.remove(0);
                }
            } else {
                if (listDns6.size() > 0) {
                    listDns.add(listDns6.get(0));
                    listDns6.remove(0);
                }
            }
        }
    }
    return listDns;
}
Also used : Inet4Address(java.net.Inet4Address) SharedPreferences(android.content.SharedPreferences) InterfaceAddress(java.net.InterfaceAddress) ArrayList(java.util.ArrayList) NetworkInterface(java.net.NetworkInterface) SpannableString(android.text.SpannableString) Paint(android.graphics.Paint) BigInteger(java.math.BigInteger) List(java.util.List) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress)

Example 52 with Inet4Address

use of java.net.Inet4Address in project NetGuard by M66B.

the class ServiceSinkhole method getBuilder.

private Builder getBuilder(List<Rule> listAllowed, List<Rule> listRule) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean subnet = prefs.getBoolean("subnet", false);
    boolean tethering = prefs.getBoolean("tethering", false);
    boolean lan = prefs.getBoolean("lan", false);
    boolean ip6 = prefs.getBoolean("ip6", true);
    boolean filter = prefs.getBoolean("filter", false);
    boolean system = prefs.getBoolean("manage_system", false);
    // Build VPN service
    Builder builder = new Builder();
    builder.setSession(getString(R.string.app_name));
    // VPN address
    String vpn4 = prefs.getString("vpn4", "10.1.10.1");
    Log.i(TAG, "vpn4=" + vpn4);
    builder.addAddress(vpn4, 32);
    if (ip6) {
        String vpn6 = prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1");
        Log.i(TAG, "vpn6=" + vpn6);
        builder.addAddress(vpn6, 128);
    }
    // DNS address
    if (filter)
        for (InetAddress dns : getDns(ServiceSinkhole.this)) {
            if (ip6 || dns instanceof Inet4Address) {
                Log.i(TAG, "dns=" + dns);
                builder.addDnsServer(dns);
            }
        }
    // Subnet routing
    if (subnet) {
        // Exclude IP ranges
        List<IPUtil.CIDR> listExclude = new ArrayList<>();
        // localhost
        listExclude.add(new IPUtil.CIDR("127.0.0.0", 8));
        if (tethering) {
            // USB tethering 192.168.42.x
            // Wi-Fi tethering 192.168.43.x
            listExclude.add(new IPUtil.CIDR("192.168.42.0", 23));
            // Wi-Fi direct 192.168.49.x
            listExclude.add(new IPUtil.CIDR("192.168.49.0", 24));
        }
        if (lan) {
            try {
                Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback() && ni.getName() != null && !ni.getName().startsWith("tun"))
                        for (InterfaceAddress ia : ni.getInterfaceAddresses()) if (ia.getAddress() instanceof Inet4Address) {
                            IPUtil.CIDR local = new IPUtil.CIDR(ia.getAddress(), ia.getNetworkPrefixLength());
                            Log.i(TAG, "Excluding " + ni.getName() + " " + local);
                            listExclude.add(local);
                        }
                }
            } catch (SocketException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }
        // https://en.wikipedia.org/wiki/Mobile_country_code
        Configuration config = getResources().getConfiguration();
        // T-Mobile Wi-Fi calling
        if (config.mcc == 310 && (config.mnc == 160 || config.mnc == 200 || config.mnc == 210 || config.mnc == 220 || config.mnc == 230 || config.mnc == 240 || config.mnc == 250 || config.mnc == 260 || config.mnc == 270 || config.mnc == 310 || config.mnc == 490 || config.mnc == 660 || config.mnc == 800)) {
            listExclude.add(new IPUtil.CIDR("66.94.2.0", 24));
            listExclude.add(new IPUtil.CIDR("66.94.6.0", 23));
            listExclude.add(new IPUtil.CIDR("66.94.8.0", 22));
            listExclude.add(new IPUtil.CIDR("208.54.0.0", 16));
        }
        // Verizon wireless calling
        if ((config.mcc == 310 && (config.mnc == 4 || config.mnc == 5 || config.mnc == 6 || config.mnc == 10 || config.mnc == 12 || config.mnc == 13 || config.mnc == 350 || config.mnc == 590 || config.mnc == 820 || config.mnc == 890 || config.mnc == 910)) || (config.mcc == 311 && (config.mnc == 12 || config.mnc == 110 || (config.mnc >= 270 && config.mnc <= 289) || config.mnc == 390 || (config.mnc >= 480 && config.mnc <= 489) || config.mnc == 590)) || (config.mcc == 312 && (config.mnc == 770))) {
            // 66.174.0.0 - 66.174.255.255
            listExclude.add(new IPUtil.CIDR("66.174.0.0", 16));
            // 69.82.0.0 - 69.83.255.255
            listExclude.add(new IPUtil.CIDR("66.82.0.0", 15));
            // 69.96.0.0 - 69.103.255.255
            listExclude.add(new IPUtil.CIDR("69.96.0.0", 13));
            // 70.192.0.0 - 70.223.255.255
            listExclude.add(new IPUtil.CIDR("70.192.0.0", 11));
            // 97.128.0.0 - 97.255.255.255
            listExclude.add(new IPUtil.CIDR("97.128.0.0", 9));
            // 174.192.0.0 - 174.255.255.255
            listExclude.add(new IPUtil.CIDR("174.192.0.0", 9));
            // 72.96.0.0 - 72.127.255.255
            listExclude.add(new IPUtil.CIDR("72.96.0.0", 9));
            // 75.192.0.0 - 75.255.255.255
            listExclude.add(new IPUtil.CIDR("75.192.0.0", 9));
            // 97.0.0.0 - 97.63.255.255
            listExclude.add(new IPUtil.CIDR("97.0.0.0", 10));
        }
        // Broadcast
        listExclude.add(new IPUtil.CIDR("224.0.0.0", 3));
        Collections.sort(listExclude);
        try {
            InetAddress start = InetAddress.getByName("0.0.0.0");
            for (IPUtil.CIDR exclude : listExclude) {
                Log.i(TAG, "Exclude " + exclude.getStart().getHostAddress() + "..." + exclude.getEnd().getHostAddress());
                for (IPUtil.CIDR include : IPUtil.toCIDR(start, IPUtil.minus1(exclude.getStart()))) try {
                    builder.addRoute(include.address, include.prefix);
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
                start = IPUtil.plus1(exclude.getEnd());
            }
            for (IPUtil.CIDR include : IPUtil.toCIDR("224.0.0.0", "255.255.255.255")) try {
                builder.addRoute(include.address, include.prefix);
            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        } catch (UnknownHostException ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
    } else
        builder.addRoute("0.0.0.0", 0);
    Log.i(TAG, "IPv6=" + ip6);
    if (ip6)
        builder.addRoute("0:0:0:0:0:0:0:0", 0);
    // MTU
    int mtu = jni_get_mtu();
    Log.i(TAG, "MTU=" + mtu);
    builder.setMtu(mtu);
    // Add list of allowed applications
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        if (last_connected && !filter)
            for (Rule rule : listAllowed) try {
                builder.addDisallowedApplication(rule.info.packageName);
            } catch (PackageManager.NameNotFoundException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        else if (filter)
            for (Rule rule : listRule) if (!rule.apply || (!system && rule.system))
                try {
                    Log.i(TAG, "Not routing " + rule.info.packageName);
                    builder.addDisallowedApplication(rule.info.packageName);
                } catch (PackageManager.NameNotFoundException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
    // Build configure intent
    Intent configure = new Intent(this, ActivityMain.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, configure, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setConfigureIntent(pi);
    return builder;
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) Configuration(android.content.res.Configuration) UnknownHostException(java.net.UnknownHostException) SharedPreferences(android.content.SharedPreferences) InterfaceAddress(java.net.InterfaceAddress) ArrayList(java.util.ArrayList) NetworkInterface(java.net.NetworkInterface) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) SpannableString(android.text.SpannableString) Paint(android.graphics.Paint) PendingIntent(android.app.PendingIntent) InetAddress(java.net.InetAddress)

Example 53 with Inet4Address

use of java.net.Inet4Address in project android_frameworks_base by AOSPA.

the class KeepalivePacketData method nattKeepalivePacket.

/**
     * Creates an IPsec NAT-T keepalive packet with the specified parameters.
     */
public static KeepalivePacketData nattKeepalivePacket(InetAddress srcAddress, int srcPort, InetAddress dstAddress, int dstPort) throws InvalidPacketException {
    if (!(srcAddress instanceof Inet4Address) || !(dstAddress instanceof Inet4Address)) {
        throw new InvalidPacketException(ERROR_INVALID_IP_ADDRESS);
    }
    if (dstPort != NATT_PORT) {
        throw new InvalidPacketException(ERROR_INVALID_PORT);
    }
    int length = IPV4_HEADER_LENGTH + UDP_HEADER_LENGTH + 1;
    ByteBuffer buf = ByteBuffer.allocate(length);
    buf.order(ByteOrder.BIG_ENDIAN);
    // IP version and TOS
    buf.putShort((short) 0x4500);
    buf.putShort((short) length);
    // ID, flags, offset
    buf.putInt(0);
    // TTL
    buf.put((byte) 64);
    buf.put((byte) OsConstants.IPPROTO_UDP);
    int ipChecksumOffset = buf.position();
    // IP checksum
    buf.putShort((short) 0);
    buf.put(srcAddress.getAddress());
    buf.put(dstAddress.getAddress());
    buf.putShort((short) srcPort);
    buf.putShort((short) dstPort);
    // UDP length
    buf.putShort((short) (length - 20));
    int udpChecksumOffset = buf.position();
    // UDP checksum
    buf.putShort((short) 0);
    // NAT-T keepalive
    buf.put((byte) 0xff);
    buf.putShort(ipChecksumOffset, IpUtils.ipChecksum(buf, 0));
    buf.putShort(udpChecksumOffset, IpUtils.udpChecksum(buf, 0, IPV4_HEADER_LENGTH));
    return new KeepalivePacketData(srcAddress, srcPort, dstAddress, dstPort, buf.array());
}
Also used : Inet4Address(java.net.Inet4Address) ByteBuffer(java.nio.ByteBuffer)

Example 54 with Inet4Address

use of java.net.Inet4Address in project android_frameworks_base by AOSPA.

the class WifiDisplayController method getInterfaceAddress.

private static Inet4Address getInterfaceAddress(WifiP2pGroup info) {
    NetworkInterface iface;
    try {
        iface = NetworkInterface.getByName(info.getInterface());
    } catch (SocketException ex) {
        Slog.w(TAG, "Could not obtain address of network interface " + info.getInterface(), ex);
        return null;
    }
    Enumeration<InetAddress> addrs = iface.getInetAddresses();
    while (addrs.hasMoreElements()) {
        InetAddress addr = addrs.nextElement();
        if (addr instanceof Inet4Address) {
            return (Inet4Address) addr;
        }
    }
    Slog.w(TAG, "Could not obtain address of network interface " + info.getInterface() + " because it had no IPv4 addresses.");
    return null;
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 55 with Inet4Address

use of java.net.Inet4Address in project android_frameworks_base by AOSPA.

the class IpConfigStore method readIpAndProxyConfigurations.

public SparseArray<IpConfiguration> readIpAndProxyConfigurations(String filePath) {
    SparseArray<IpConfiguration> networks = new SparseArray<IpConfiguration>();
    DataInputStream in = null;
    try {
        in = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
        int version = in.readInt();
        if (version != 2 && version != 1) {
            loge("Bad version on IP configuration file, ignore read");
            return null;
        }
        while (true) {
            int id = -1;
            // Default is DHCP with no proxy
            IpAssignment ipAssignment = IpAssignment.DHCP;
            ProxySettings proxySettings = ProxySettings.NONE;
            StaticIpConfiguration staticIpConfiguration = new StaticIpConfiguration();
            String proxyHost = null;
            String pacFileUrl = null;
            int proxyPort = -1;
            String exclusionList = null;
            String key;
            do {
                key = in.readUTF();
                try {
                    if (key.equals(ID_KEY)) {
                        id = in.readInt();
                    } else if (key.equals(IP_ASSIGNMENT_KEY)) {
                        ipAssignment = IpAssignment.valueOf(in.readUTF());
                    } else if (key.equals(LINK_ADDRESS_KEY)) {
                        LinkAddress linkAddr = new LinkAddress(NetworkUtils.numericToInetAddress(in.readUTF()), in.readInt());
                        if (linkAddr.getAddress() instanceof Inet4Address && staticIpConfiguration.ipAddress == null) {
                            staticIpConfiguration.ipAddress = linkAddr;
                        } else {
                            loge("Non-IPv4 or duplicate address: " + linkAddr);
                        }
                    } else if (key.equals(GATEWAY_KEY)) {
                        LinkAddress dest = null;
                        InetAddress gateway = null;
                        if (version == 1) {
                            // only supported default gateways - leave the dest/prefix empty
                            gateway = NetworkUtils.numericToInetAddress(in.readUTF());
                            if (staticIpConfiguration.gateway == null) {
                                staticIpConfiguration.gateway = gateway;
                            } else {
                                loge("Duplicate gateway: " + gateway.getHostAddress());
                            }
                        } else {
                            if (in.readInt() == 1) {
                                dest = new LinkAddress(NetworkUtils.numericToInetAddress(in.readUTF()), in.readInt());
                            }
                            if (in.readInt() == 1) {
                                gateway = NetworkUtils.numericToInetAddress(in.readUTF());
                            }
                            RouteInfo route = new RouteInfo(dest, gateway);
                            if (route.isIPv4Default() && staticIpConfiguration.gateway == null) {
                                staticIpConfiguration.gateway = gateway;
                            } else {
                                loge("Non-IPv4 default or duplicate route: " + route);
                            }
                        }
                    } else if (key.equals(DNS_KEY)) {
                        staticIpConfiguration.dnsServers.add(NetworkUtils.numericToInetAddress(in.readUTF()));
                    } else if (key.equals(PROXY_SETTINGS_KEY)) {
                        proxySettings = ProxySettings.valueOf(in.readUTF());
                    } else if (key.equals(PROXY_HOST_KEY)) {
                        proxyHost = in.readUTF();
                    } else if (key.equals(PROXY_PORT_KEY)) {
                        proxyPort = in.readInt();
                    } else if (key.equals(PROXY_PAC_FILE)) {
                        pacFileUrl = in.readUTF();
                    } else if (key.equals(EXCLUSION_LIST_KEY)) {
                        exclusionList = in.readUTF();
                    } else if (key.equals(EOS)) {
                        break;
                    } else {
                        loge("Ignore unknown key " + key + "while reading");
                    }
                } catch (IllegalArgumentException e) {
                    loge("Ignore invalid address while reading" + e);
                }
            } while (true);
            if (id != -1) {
                IpConfiguration config = new IpConfiguration();
                networks.put(id, config);
                switch(ipAssignment) {
                    case STATIC:
                        config.staticIpConfiguration = staticIpConfiguration;
                        config.ipAssignment = ipAssignment;
                        break;
                    case DHCP:
                        config.ipAssignment = ipAssignment;
                        break;
                    case UNASSIGNED:
                        loge("BUG: Found UNASSIGNED IP on file, use DHCP");
                        config.ipAssignment = IpAssignment.DHCP;
                        break;
                    default:
                        loge("Ignore invalid ip assignment while reading.");
                        config.ipAssignment = IpAssignment.UNASSIGNED;
                        break;
                }
                switch(proxySettings) {
                    case STATIC:
                        ProxyInfo proxyInfo = new ProxyInfo(proxyHost, proxyPort, exclusionList);
                        config.proxySettings = proxySettings;
                        config.httpProxy = proxyInfo;
                        break;
                    case PAC:
                        ProxyInfo proxyPacProperties = new ProxyInfo(pacFileUrl);
                        config.proxySettings = proxySettings;
                        config.httpProxy = proxyPacProperties;
                        break;
                    case NONE:
                        config.proxySettings = proxySettings;
                        break;
                    case UNASSIGNED:
                        loge("BUG: Found UNASSIGNED proxy on file, use NONE");
                        config.proxySettings = ProxySettings.NONE;
                        break;
                    default:
                        loge("Ignore invalid proxy settings while reading");
                        config.proxySettings = ProxySettings.UNASSIGNED;
                        break;
                }
            } else {
                if (DBG)
                    log("Missing id while parsing configuration");
            }
        }
    } catch (EOFException ignore) {
    } catch (IOException e) {
        loge("Error parsing configuration: " + e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
    return networks;
}
Also used : LinkAddress(android.net.LinkAddress) Inet4Address(java.net.Inet4Address) IpConfiguration(android.net.IpConfiguration) StaticIpConfiguration(android.net.StaticIpConfiguration) IpAssignment(android.net.IpConfiguration.IpAssignment) ProxySettings(android.net.IpConfiguration.ProxySettings) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) EOFException(java.io.EOFException) ProxyInfo(android.net.ProxyInfo) SparseArray(android.util.SparseArray) BufferedInputStream(java.io.BufferedInputStream) StaticIpConfiguration(android.net.StaticIpConfiguration) EOFException(java.io.EOFException) RouteInfo(android.net.RouteInfo) InetAddress(java.net.InetAddress)

Aggregations

Inet4Address (java.net.Inet4Address)184 InetAddress (java.net.InetAddress)85 Inet6Address (java.net.Inet6Address)45 NetworkInterface (java.net.NetworkInterface)39 UnknownHostException (java.net.UnknownHostException)28 LinkAddress (android.net.LinkAddress)24 SocketException (java.net.SocketException)23 IOException (java.io.IOException)22 ArrayList (java.util.ArrayList)19 InterfaceAddress (java.net.InterfaceAddress)17 ByteBuffer (java.nio.ByteBuffer)17 RouteInfo (android.net.RouteInfo)12 LinkProperties (android.net.LinkProperties)7 InetSocketAddress (java.net.InetSocketAddress)6 Test (org.junit.Test)6 WifiDisplay (android.hardware.display.WifiDisplay)5 WifiDisplaySessionInfo (android.hardware.display.WifiDisplaySessionInfo)5 DhcpResults (android.net.DhcpResults)5 IpConfiguration (android.net.IpConfiguration)5 IpAssignment (android.net.IpConfiguration.IpAssignment)5