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