1/*
2 * Copyright 2008, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "NetUtils"
18
19#include "jni.h"
20#include <nativehelper/JNIHelp.h>
21#include "NetdClient.h"
22#include <utils/misc.h>
23#include <android_runtime/AndroidRuntime.h>
24#include <utils/Log.h>
25#include <arpa/inet.h>
26#include <net/if.h>
27#include <linux/filter.h>
28#include <linux/if_arp.h>
29#include <netinet/ether.h>
30#include <netinet/icmp6.h>
31#include <netinet/ip.h>
32#include <netinet/ip6.h>
33#include <netinet/udp.h>
34#include <cutils/properties.h>
35
36#include "core_jni_helpers.h"
37
38extern "C" {
39int ifc_enable(const char *ifname);
40int ifc_disable(const char *ifname);
41}
42
43#define NETUTILS_PKG_NAME "android/net/NetworkUtils"
44
45namespace android {
46
47static const uint32_t kEtherTypeOffset = offsetof(ether_header, ether_type);
48static const uint32_t kEtherHeaderLen = sizeof(ether_header);
49static const uint32_t kIPv4Protocol = kEtherHeaderLen + offsetof(iphdr, protocol);
50static const uint32_t kIPv4FlagsOffset = kEtherHeaderLen + offsetof(iphdr, frag_off);
51static const uint32_t kIPv6NextHeader = kEtherHeaderLen + offsetof(ip6_hdr, ip6_nxt);
52static const uint32_t kIPv6PayloadStart = kEtherHeaderLen + sizeof(ip6_hdr);
53static const uint32_t kICMPv6TypeOffset = kIPv6PayloadStart + offsetof(icmp6_hdr, icmp6_type);
54static const uint32_t kUDPSrcPortIndirectOffset = kEtherHeaderLen + offsetof(udphdr, source);
55static const uint32_t kUDPDstPortIndirectOffset = kEtherHeaderLen + offsetof(udphdr, dest);
56static const uint16_t kDhcpClientPort = 68;
57
58static void android_net_utils_attachDhcpFilter(JNIEnv *env, jobject clazz, jobject javaFd)
59{
60    struct sock_filter filter_code[] = {
61        // Check the protocol is UDP.
62        BPF_STMT(BPF_LD  | BPF_B   | BPF_ABS,  kIPv4Protocol),
63        BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    IPPROTO_UDP, 0, 6),
64
65        // Check this is not a fragment.
66        BPF_STMT(BPF_LD  | BPF_H    | BPF_ABS, kIPv4FlagsOffset),
67        BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K,   IP_OFFMASK, 4, 0),
68
69        // Get the IP header length.
70        BPF_STMT(BPF_LDX | BPF_B    | BPF_MSH, kEtherHeaderLen),
71
72        // Check the destination port.
73        BPF_STMT(BPF_LD  | BPF_H    | BPF_IND, kUDPDstPortIndirectOffset),
74        BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   kDhcpClientPort, 0, 1),
75
76        // Accept or reject.
77        BPF_STMT(BPF_RET | BPF_K,              0xffff),
78        BPF_STMT(BPF_RET | BPF_K,              0)
79    };
80    struct sock_fprog filter = {
81        sizeof(filter_code) / sizeof(filter_code[0]),
82        filter_code,
83    };
84
85    int fd = jniGetFDFromFileDescriptor(env, javaFd);
86    if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
87        jniThrowExceptionFmt(env, "java/net/SocketException",
88                "setsockopt(SO_ATTACH_FILTER): %s", strerror(errno));
89    }
90}
91
92static void android_net_utils_attachRaFilter(JNIEnv *env, jobject clazz, jobject javaFd,
93        jint hardwareAddressType)
94{
95    if (hardwareAddressType != ARPHRD_ETHER) {
96        jniThrowExceptionFmt(env, "java/net/SocketException",
97                "attachRaFilter only supports ARPHRD_ETHER");
98        return;
99    }
100
101    struct sock_filter filter_code[] = {
102        // Check IPv6 Next Header is ICMPv6.
103        BPF_STMT(BPF_LD  | BPF_B   | BPF_ABS,  kIPv6NextHeader),
104        BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    IPPROTO_ICMPV6, 0, 3),
105
106        // Check ICMPv6 type is Router Advertisement.
107        BPF_STMT(BPF_LD  | BPF_B   | BPF_ABS,  kICMPv6TypeOffset),
108        BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    ND_ROUTER_ADVERT, 0, 1),
109
110        // Accept or reject.
111        BPF_STMT(BPF_RET | BPF_K,              0xffff),
112        BPF_STMT(BPF_RET | BPF_K,              0)
113    };
114    struct sock_fprog filter = {
115        sizeof(filter_code) / sizeof(filter_code[0]),
116        filter_code,
117    };
118
119    int fd = jniGetFDFromFileDescriptor(env, javaFd);
120    if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
121        jniThrowExceptionFmt(env, "java/net/SocketException",
122                "setsockopt(SO_ATTACH_FILTER): %s", strerror(errno));
123    }
124}
125
126// TODO: Move all this filter code into libnetutils.
127static void android_net_utils_attachControlPacketFilter(
128        JNIEnv *env, jobject clazz, jobject javaFd, jint hardwareAddressType) {
129    if (hardwareAddressType != ARPHRD_ETHER) {
130        jniThrowExceptionFmt(env, "java/net/SocketException",
131                "attachControlPacketFilter only supports ARPHRD_ETHER");
132        return;
133    }
134
135    // Capture all:
136    //     - ARPs
137    //     - DHCPv4 packets
138    //     - Router Advertisements & Solicitations
139    //     - Neighbor Advertisements & Solicitations
140    //
141    // tcpdump:
142    //     arp or
143    //     '(ip and udp port 68)' or
144    //     '(icmp6 and ip6[40] >= 133 and ip6[40] <= 136)'
145    struct sock_filter filter_code[] = {
146        // Load the link layer next payload field.
147        BPF_STMT(BPF_LD  | BPF_H   | BPF_ABS,  kEtherTypeOffset),
148
149        // Accept all ARP.
150        // TODO: Figure out how to better filter ARPs on noisy networks.
151        BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ETHERTYPE_ARP, 16, 0),
152
153        // If IPv4:
154        BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ETHERTYPE_IP, 0, 9),
155
156        // Check the protocol is UDP.
157        BPF_STMT(BPF_LD  | BPF_B   | BPF_ABS,  kIPv4Protocol),
158        BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    IPPROTO_UDP, 0, 14),
159
160        // Check this is not a fragment.
161        BPF_STMT(BPF_LD  | BPF_H    | BPF_ABS, kIPv4FlagsOffset),
162        BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K,   IP_OFFMASK, 12, 0),
163
164        // Get the IP header length.
165        BPF_STMT(BPF_LDX | BPF_B    | BPF_MSH, kEtherHeaderLen),
166
167        // Check the source port.
168        BPF_STMT(BPF_LD  | BPF_H    | BPF_IND, kUDPSrcPortIndirectOffset),
169        BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   kDhcpClientPort, 8, 0),
170
171        // Check the destination port.
172        BPF_STMT(BPF_LD  | BPF_H    | BPF_IND, kUDPDstPortIndirectOffset),
173        BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   kDhcpClientPort, 6, 7),
174
175        // IPv6 ...
176        BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ETHERTYPE_IPV6, 0, 6),
177        // ... check IPv6 Next Header is ICMPv6 (ignore fragments), ...
178        BPF_STMT(BPF_LD  | BPF_B   | BPF_ABS,  kIPv6NextHeader),
179        BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    IPPROTO_ICMPV6, 0, 4),
180        // ... and check the ICMPv6 type is one of RS/RA/NS/NA.
181        BPF_STMT(BPF_LD  | BPF_B   | BPF_ABS,  kICMPv6TypeOffset),
182        BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K,    ND_ROUTER_SOLICIT, 0, 2),
183        BPF_JUMP(BPF_JMP | BPF_JGT | BPF_K,    ND_NEIGHBOR_ADVERT, 1, 0),
184
185        // Accept or reject.
186        BPF_STMT(BPF_RET | BPF_K,              0xffff),
187        BPF_STMT(BPF_RET | BPF_K,              0)
188    };
189    struct sock_fprog filter = {
190        sizeof(filter_code) / sizeof(filter_code[0]),
191        filter_code,
192    };
193
194    int fd = jniGetFDFromFileDescriptor(env, javaFd);
195    if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
196        jniThrowExceptionFmt(env, "java/net/SocketException",
197                "setsockopt(SO_ATTACH_FILTER): %s", strerror(errno));
198    }
199}
200
201static void android_net_utils_setupRaSocket(JNIEnv *env, jobject clazz, jobject javaFd,
202        jint ifIndex)
203{
204    static const int kLinkLocalHopLimit = 255;
205
206    int fd = jniGetFDFromFileDescriptor(env, javaFd);
207
208    // Set an ICMPv6 filter that only passes Router Solicitations.
209    struct icmp6_filter rs_only;
210    ICMP6_FILTER_SETBLOCKALL(&rs_only);
211    ICMP6_FILTER_SETPASS(ND_ROUTER_SOLICIT, &rs_only);
212    socklen_t len = sizeof(rs_only);
213    if (setsockopt(fd, IPPROTO_ICMPV6, ICMP6_FILTER, &rs_only, len) != 0) {
214        jniThrowExceptionFmt(env, "java/net/SocketException",
215                "setsockopt(ICMP6_FILTER): %s", strerror(errno));
216        return;
217    }
218
219    // Most/all of the rest of these options can be set via Java code, but
220    // because we're here on account of setting an icmp6_filter go ahead
221    // and do it all natively for now.
222    //
223    // TODO: Consider moving these out to Java.
224
225    // Set the multicast hoplimit to 255 (link-local only).
226    int hops = kLinkLocalHopLimit;
227    len = sizeof(hops);
228    if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &hops, len) != 0) {
229        jniThrowExceptionFmt(env, "java/net/SocketException",
230                "setsockopt(IPV6_MULTICAST_HOPS): %s", strerror(errno));
231        return;
232    }
233
234    // Set the unicast hoplimit to 255 (link-local only).
235    hops = kLinkLocalHopLimit;
236    len = sizeof(hops);
237    if (setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &hops, len) != 0) {
238        jniThrowExceptionFmt(env, "java/net/SocketException",
239                "setsockopt(IPV6_UNICAST_HOPS): %s", strerror(errno));
240        return;
241    }
242
243    // Explicitly disable multicast loopback.
244    int off = 0;
245    len = sizeof(off);
246    if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &off, len) != 0) {
247        jniThrowExceptionFmt(env, "java/net/SocketException",
248                "setsockopt(IPV6_MULTICAST_LOOP): %s", strerror(errno));
249        return;
250    }
251
252    // Specify the IPv6 interface to use for outbound multicast.
253    len = sizeof(ifIndex);
254    if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &ifIndex, len) != 0) {
255        jniThrowExceptionFmt(env, "java/net/SocketException",
256                "setsockopt(IPV6_MULTICAST_IF): %s", strerror(errno));
257        return;
258    }
259
260    // Additional options to be considered:
261    //     - IPV6_TCLASS
262    //     - IPV6_RECVPKTINFO
263    //     - IPV6_RECVHOPLIMIT
264
265    // Bind to [::].
266    const struct sockaddr_in6 sin6 = {
267            .sin6_family = AF_INET6,
268            .sin6_port = 0,
269            .sin6_flowinfo = 0,
270            .sin6_addr = IN6ADDR_ANY_INIT,
271            .sin6_scope_id = 0,
272    };
273    auto sa = reinterpret_cast<const struct sockaddr *>(&sin6);
274    len = sizeof(sin6);
275    if (bind(fd, sa, len) != 0) {
276        jniThrowExceptionFmt(env, "java/net/SocketException",
277                "bind(IN6ADDR_ANY): %s", strerror(errno));
278        return;
279    }
280
281    // Join the all-routers multicast group, ff02::2%index.
282    struct ipv6_mreq all_rtrs = {
283        .ipv6mr_multiaddr = {{{0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2}}},
284        .ipv6mr_interface = ifIndex,
285    };
286    len = sizeof(all_rtrs);
287    if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &all_rtrs, len) != 0) {
288        jniThrowExceptionFmt(env, "java/net/SocketException",
289                "setsockopt(IPV6_JOIN_GROUP): %s", strerror(errno));
290        return;
291    }
292}
293
294static jboolean android_net_utils_bindProcessToNetwork(JNIEnv *env, jobject thiz, jint netId)
295{
296    return (jboolean) !setNetworkForProcess(netId);
297}
298
299static jint android_net_utils_getBoundNetworkForProcess(JNIEnv *env, jobject thiz)
300{
301    return getNetworkForProcess();
302}
303
304static jboolean android_net_utils_bindProcessToNetworkForHostResolution(JNIEnv *env, jobject thiz,
305        jint netId)
306{
307    return (jboolean) !setNetworkForResolv(netId);
308}
309
310static jint android_net_utils_bindSocketToNetwork(JNIEnv *env, jobject thiz, jint socket,
311        jint netId)
312{
313    return setNetworkForSocket(netId, socket);
314}
315
316static jboolean android_net_utils_protectFromVpn(JNIEnv *env, jobject thiz, jint socket)
317{
318    return (jboolean) !protectFromVpn(socket);
319}
320
321static jboolean android_net_utils_queryUserAccess(JNIEnv *env, jobject thiz, jint uid, jint netId)
322{
323    return (jboolean) !queryUserAccess(uid, netId);
324}
325
326
327// ----------------------------------------------------------------------------
328
329/*
330 * JNI registration.
331 */
332static const JNINativeMethod gNetworkUtilMethods[] = {
333    /* name, signature, funcPtr */
334    { "bindProcessToNetwork", "(I)Z", (void*) android_net_utils_bindProcessToNetwork },
335    { "getBoundNetworkForProcess", "()I", (void*) android_net_utils_getBoundNetworkForProcess },
336    { "bindProcessToNetworkForHostResolution", "(I)Z", (void*) android_net_utils_bindProcessToNetworkForHostResolution },
337    { "bindSocketToNetwork", "(II)I", (void*) android_net_utils_bindSocketToNetwork },
338    { "protectFromVpn", "(I)Z", (void*)android_net_utils_protectFromVpn },
339    { "queryUserAccess", "(II)Z", (void*)android_net_utils_queryUserAccess },
340    { "attachDhcpFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_attachDhcpFilter },
341    { "attachRaFilter", "(Ljava/io/FileDescriptor;I)V", (void*) android_net_utils_attachRaFilter },
342    { "attachControlPacketFilter", "(Ljava/io/FileDescriptor;I)V", (void*) android_net_utils_attachControlPacketFilter },
343    { "setupRaSocket", "(Ljava/io/FileDescriptor;I)V", (void*) android_net_utils_setupRaSocket },
344};
345
346int register_android_net_NetworkUtils(JNIEnv* env)
347{
348    return RegisterMethodsOrDie(env, NETUTILS_PKG_NAME, gNetworkUtilMethods,
349                                NELEM(gNetworkUtilMethods));
350}
351
352}; // namespace android
353