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 <vector>
20
21 #include <arpa/inet.h>
22 #include <linux/filter.h>
23 #include <linux/if_arp.h>
24 #include <linux/tcp.h>
25 #include <net/if.h>
26 #include <netinet/ether.h>
27 #include <netinet/icmp6.h>
28 #include <netinet/ip.h>
29 #include <netinet/ip6.h>
30 #include <netinet/udp.h>
31
32 #include <android_runtime/AndroidRuntime.h>
33 #include <cutils/properties.h>
34 #include <utils/misc.h>
35 #include <utils/Log.h>
36 #include <nativehelper/JNIHelp.h>
37 #include <nativehelper/ScopedLocalRef.h>
38
39 #include "NetdClient.h"
40 #include "core_jni_helpers.h"
41 #include "jni.h"
42
43 extern "C" {
44 int ifc_enable(const char *ifname);
45 int ifc_disable(const char *ifname);
46 }
47
48 #define NETUTILS_PKG_NAME "android/net/NetworkUtils"
49
50 namespace android {
51
52 constexpr int MAXPACKETSIZE = 8 * 1024;
53 // FrameworkListener limits the size of commands to 4096 bytes.
54 constexpr int MAXCMDSIZE = 4096;
55
throwErrnoException(JNIEnv * env,const char * functionName,int error)56 static void throwErrnoException(JNIEnv* env, const char* functionName, int error) {
57 ScopedLocalRef<jstring> detailMessage(env, env->NewStringUTF(functionName));
58 if (detailMessage.get() == NULL) {
59 // Not really much we can do here. We're probably dead in the water,
60 // but let's try to stumble on...
61 env->ExceptionClear();
62 }
63 static jclass errnoExceptionClass =
64 MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/system/ErrnoException"));
65
66 static jmethodID errnoExceptionCtor =
67 GetMethodIDOrDie(env, errnoExceptionClass,
68 "<init>", "(Ljava/lang/String;I)V");
69
70 jobject exception = env->NewObject(errnoExceptionClass,
71 errnoExceptionCtor,
72 detailMessage.get(),
73 error);
74 env->Throw(reinterpret_cast<jthrowable>(exception));
75 }
76
android_net_utils_attachDropAllBPFFilter(JNIEnv * env,jobject clazz,jobject javaFd)77 static void android_net_utils_attachDropAllBPFFilter(JNIEnv *env, jobject clazz, jobject javaFd)
78 {
79 struct sock_filter filter_code[] = {
80 // Reject all.
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
android_net_utils_detachBPFFilter(JNIEnv * env,jobject clazz,jobject javaFd)95 static void android_net_utils_detachBPFFilter(JNIEnv *env, jobject clazz, jobject javaFd)
96 {
97 int dummy = 0;
98 int fd = jniGetFDFromFileDescriptor(env, javaFd);
99 if (setsockopt(fd, SOL_SOCKET, SO_DETACH_FILTER, &dummy, sizeof(dummy)) != 0) {
100 jniThrowExceptionFmt(env, "java/net/SocketException",
101 "setsockopt(SO_DETACH_FILTER): %s", strerror(errno));
102 }
103
104 }
android_net_utils_setupRaSocket(JNIEnv * env,jobject clazz,jobject javaFd,jint ifIndex)105 static void android_net_utils_setupRaSocket(JNIEnv *env, jobject clazz, jobject javaFd,
106 jint ifIndex)
107 {
108 static const int kLinkLocalHopLimit = 255;
109
110 int fd = jniGetFDFromFileDescriptor(env, javaFd);
111
112 // Set an ICMPv6 filter that only passes Router Solicitations.
113 struct icmp6_filter rs_only;
114 ICMP6_FILTER_SETBLOCKALL(&rs_only);
115 ICMP6_FILTER_SETPASS(ND_ROUTER_SOLICIT, &rs_only);
116 socklen_t len = sizeof(rs_only);
117 if (setsockopt(fd, IPPROTO_ICMPV6, ICMP6_FILTER, &rs_only, len) != 0) {
118 jniThrowExceptionFmt(env, "java/net/SocketException",
119 "setsockopt(ICMP6_FILTER): %s", strerror(errno));
120 return;
121 }
122
123 // Most/all of the rest of these options can be set via Java code, but
124 // because we're here on account of setting an icmp6_filter go ahead
125 // and do it all natively for now.
126 //
127 // TODO: Consider moving these out to Java.
128
129 // Set the multicast hoplimit to 255 (link-local only).
130 int hops = kLinkLocalHopLimit;
131 len = sizeof(hops);
132 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &hops, len) != 0) {
133 jniThrowExceptionFmt(env, "java/net/SocketException",
134 "setsockopt(IPV6_MULTICAST_HOPS): %s", strerror(errno));
135 return;
136 }
137
138 // Set the unicast hoplimit to 255 (link-local only).
139 hops = kLinkLocalHopLimit;
140 len = sizeof(hops);
141 if (setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &hops, len) != 0) {
142 jniThrowExceptionFmt(env, "java/net/SocketException",
143 "setsockopt(IPV6_UNICAST_HOPS): %s", strerror(errno));
144 return;
145 }
146
147 // Explicitly disable multicast loopback.
148 int off = 0;
149 len = sizeof(off);
150 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &off, len) != 0) {
151 jniThrowExceptionFmt(env, "java/net/SocketException",
152 "setsockopt(IPV6_MULTICAST_LOOP): %s", strerror(errno));
153 return;
154 }
155
156 // Specify the IPv6 interface to use for outbound multicast.
157 len = sizeof(ifIndex);
158 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &ifIndex, len) != 0) {
159 jniThrowExceptionFmt(env, "java/net/SocketException",
160 "setsockopt(IPV6_MULTICAST_IF): %s", strerror(errno));
161 return;
162 }
163
164 // Additional options to be considered:
165 // - IPV6_TCLASS
166 // - IPV6_RECVPKTINFO
167 // - IPV6_RECVHOPLIMIT
168
169 // Bind to [::].
170 const struct sockaddr_in6 sin6 = {
171 .sin6_family = AF_INET6,
172 .sin6_port = 0,
173 .sin6_flowinfo = 0,
174 .sin6_addr = IN6ADDR_ANY_INIT,
175 .sin6_scope_id = 0,
176 };
177 auto sa = reinterpret_cast<const struct sockaddr *>(&sin6);
178 len = sizeof(sin6);
179 if (bind(fd, sa, len) != 0) {
180 jniThrowExceptionFmt(env, "java/net/SocketException",
181 "bind(IN6ADDR_ANY): %s", strerror(errno));
182 return;
183 }
184
185 // Join the all-routers multicast group, ff02::2%index.
186 struct ipv6_mreq all_rtrs = {
187 .ipv6mr_multiaddr = {{{0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2}}},
188 .ipv6mr_interface = ifIndex,
189 };
190 len = sizeof(all_rtrs);
191 if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &all_rtrs, len) != 0) {
192 jniThrowExceptionFmt(env, "java/net/SocketException",
193 "setsockopt(IPV6_JOIN_GROUP): %s", strerror(errno));
194 return;
195 }
196 }
197
android_net_utils_bindProcessToNetwork(JNIEnv * env,jobject thiz,jint netId)198 static jboolean android_net_utils_bindProcessToNetwork(JNIEnv *env, jobject thiz, jint netId)
199 {
200 return (jboolean) !setNetworkForProcess(netId);
201 }
202
android_net_utils_getBoundNetworkForProcess(JNIEnv * env,jobject thiz)203 static jint android_net_utils_getBoundNetworkForProcess(JNIEnv *env, jobject thiz)
204 {
205 return getNetworkForProcess();
206 }
207
android_net_utils_bindProcessToNetworkForHostResolution(JNIEnv * env,jobject thiz,jint netId)208 static jboolean android_net_utils_bindProcessToNetworkForHostResolution(JNIEnv *env, jobject thiz,
209 jint netId)
210 {
211 return (jboolean) !setNetworkForResolv(netId);
212 }
213
android_net_utils_bindSocketToNetwork(JNIEnv * env,jobject thiz,jint socket,jint netId)214 static jint android_net_utils_bindSocketToNetwork(JNIEnv *env, jobject thiz, jint socket,
215 jint netId)
216 {
217 return setNetworkForSocket(netId, socket);
218 }
219
android_net_utils_protectFromVpn(JNIEnv * env,jobject thiz,jint socket)220 static jboolean android_net_utils_protectFromVpn(JNIEnv *env, jobject thiz, jint socket)
221 {
222 return (jboolean) !protectFromVpn(socket);
223 }
224
android_net_utils_queryUserAccess(JNIEnv * env,jobject thiz,jint uid,jint netId)225 static jboolean android_net_utils_queryUserAccess(JNIEnv *env, jobject thiz, jint uid, jint netId)
226 {
227 return (jboolean) !queryUserAccess(uid, netId);
228 }
229
checkLenAndCopy(JNIEnv * env,const jbyteArray & addr,int len,void * dst)230 static bool checkLenAndCopy(JNIEnv* env, const jbyteArray& addr, int len, void* dst)
231 {
232 if (env->GetArrayLength(addr) != len) {
233 return false;
234 }
235 env->GetByteArrayRegion(addr, 0, len, reinterpret_cast<jbyte*>(dst));
236 return true;
237 }
238
android_net_utils_resNetworkQuery(JNIEnv * env,jobject thiz,jint netId,jstring dname,jint ns_class,jint ns_type,jint flags)239 static jobject android_net_utils_resNetworkQuery(JNIEnv *env, jobject thiz, jint netId,
240 jstring dname, jint ns_class, jint ns_type, jint flags) {
241 const jsize javaCharsCount = env->GetStringLength(dname);
242 const jsize byteCountUTF8 = env->GetStringUTFLength(dname);
243
244 // Only allow dname which could be simply formatted to UTF8.
245 // In native layer, res_mkquery would re-format the input char array to packet.
246 std::vector<char> queryname(byteCountUTF8 + 1, 0);
247
248 env->GetStringUTFRegion(dname, 0, javaCharsCount, queryname.data());
249 int fd = resNetworkQuery(netId, queryname.data(), ns_class, ns_type, flags);
250
251 if (fd < 0) {
252 throwErrnoException(env, "resNetworkQuery", -fd);
253 return nullptr;
254 }
255
256 return jniCreateFileDescriptor(env, fd);
257 }
258
android_net_utils_resNetworkSend(JNIEnv * env,jobject thiz,jint netId,jbyteArray msg,jint msgLen,jint flags)259 static jobject android_net_utils_resNetworkSend(JNIEnv *env, jobject thiz, jint netId,
260 jbyteArray msg, jint msgLen, jint flags) {
261 uint8_t data[MAXCMDSIZE];
262
263 checkLenAndCopy(env, msg, msgLen, data);
264 int fd = resNetworkSend(netId, data, msgLen, flags);
265
266 if (fd < 0) {
267 throwErrnoException(env, "resNetworkSend", -fd);
268 return nullptr;
269 }
270
271 return jniCreateFileDescriptor(env, fd);
272 }
273
android_net_utils_resNetworkResult(JNIEnv * env,jobject thiz,jobject javaFd)274 static jobject android_net_utils_resNetworkResult(JNIEnv *env, jobject thiz, jobject javaFd) {
275 int fd = jniGetFDFromFileDescriptor(env, javaFd);
276 int rcode;
277 std::vector<uint8_t> buf(MAXPACKETSIZE, 0);
278
279 int res = resNetworkResult(fd, &rcode, buf.data(), MAXPACKETSIZE);
280 jniSetFileDescriptorOfFD(env, javaFd, -1);
281 if (res < 0) {
282 throwErrnoException(env, "resNetworkResult", -res);
283 return nullptr;
284 }
285
286 jbyteArray answer = env->NewByteArray(res);
287 if (answer == nullptr) {
288 throwErrnoException(env, "resNetworkResult", ENOMEM);
289 return nullptr;
290 } else {
291 env->SetByteArrayRegion(answer, 0, res,
292 reinterpret_cast<jbyte*>(buf.data()));
293 }
294
295 jclass class_DnsResponse = env->FindClass("android/net/DnsResolver$DnsResponse");
296 jmethodID ctor = env->GetMethodID(class_DnsResponse, "<init>", "([BI)V");
297
298 return env->NewObject(class_DnsResponse, ctor, answer, rcode);
299 }
300
android_net_utils_resNetworkCancel(JNIEnv * env,jobject thiz,jobject javaFd)301 static void android_net_utils_resNetworkCancel(JNIEnv *env, jobject thiz, jobject javaFd) {
302 int fd = jniGetFDFromFileDescriptor(env, javaFd);
303 resNetworkCancel(fd);
304 jniSetFileDescriptorOfFD(env, javaFd, -1);
305 }
306
android_net_utils_getDnsNetwork(JNIEnv * env,jobject thiz)307 static jobject android_net_utils_getDnsNetwork(JNIEnv *env, jobject thiz) {
308 unsigned dnsNetId = 0;
309 if (int res = getNetworkForDns(&dnsNetId) < 0) {
310 throwErrnoException(env, "getDnsNetId", -res);
311 return nullptr;
312 }
313 bool privateDnsBypass = dnsNetId & NETID_USE_LOCAL_NAMESERVERS;
314
315 static jclass class_Network = MakeGlobalRefOrDie(
316 env, FindClassOrDie(env, "android/net/Network"));
317 static jmethodID ctor = env->GetMethodID(class_Network, "<init>", "(IZ)V");
318 return env->NewObject(
319 class_Network, ctor, dnsNetId & ~NETID_USE_LOCAL_NAMESERVERS, privateDnsBypass);
320 }
321
android_net_utils_getTcpRepairWindow(JNIEnv * env,jobject thiz,jobject javaFd)322 static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jobject thiz, jobject javaFd) {
323 if (javaFd == NULL) {
324 jniThrowNullPointerException(env, NULL);
325 return NULL;
326 }
327
328 int fd = jniGetFDFromFileDescriptor(env, javaFd);
329 struct tcp_repair_window trw = {};
330 socklen_t size = sizeof(trw);
331
332 // Obtain the parameters of the TCP repair window.
333 int rc = getsockopt(fd, IPPROTO_TCP, TCP_REPAIR_WINDOW, &trw, &size);
334 if (rc == -1) {
335 throwErrnoException(env, "getsockopt : TCP_REPAIR_WINDOW", errno);
336 return NULL;
337 }
338
339 struct tcp_info tcpinfo = {};
340 socklen_t tcpinfo_size = sizeof(tcp_info);
341
342 // Obtain the window scale from the tcp info structure. This contains a scale factor that
343 // should be applied to the window size.
344 rc = getsockopt(fd, IPPROTO_TCP, TCP_INFO, &tcpinfo, &tcpinfo_size);
345 if (rc == -1) {
346 throwErrnoException(env, "getsockopt : TCP_INFO", errno);
347 return NULL;
348 }
349
350 jclass class_TcpRepairWindow = env->FindClass("android/net/TcpRepairWindow");
351 jmethodID ctor = env->GetMethodID(class_TcpRepairWindow, "<init>", "(IIIIII)V");
352
353 return env->NewObject(class_TcpRepairWindow, ctor, trw.snd_wl1, trw.snd_wnd, trw.max_window,
354 trw.rcv_wnd, trw.rcv_wup, tcpinfo.tcpi_rcv_wscale);
355 }
356
357 // ----------------------------------------------------------------------------
358
359 /*
360 * JNI registration.
361 */
362 static const JNINativeMethod gNetworkUtilMethods[] = {
363 /* name, signature, funcPtr */
364 { "bindProcessToNetwork", "(I)Z", (void*) android_net_utils_bindProcessToNetwork },
365 { "getBoundNetworkForProcess", "()I", (void*) android_net_utils_getBoundNetworkForProcess },
366 { "bindProcessToNetworkForHostResolution", "(I)Z", (void*) android_net_utils_bindProcessToNetworkForHostResolution },
367 { "bindSocketToNetwork", "(II)I", (void*) android_net_utils_bindSocketToNetwork },
368 { "protectFromVpn", "(I)Z", (void*)android_net_utils_protectFromVpn },
369 { "queryUserAccess", "(II)Z", (void*)android_net_utils_queryUserAccess },
370 { "attachDropAllBPFFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_attachDropAllBPFFilter },
371 { "detachBPFFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_detachBPFFilter },
372 { "getTcpRepairWindow", "(Ljava/io/FileDescriptor;)Landroid/net/TcpRepairWindow;", (void*) android_net_utils_getTcpRepairWindow },
373 { "setupRaSocket", "(Ljava/io/FileDescriptor;I)V", (void*) android_net_utils_setupRaSocket },
374 { "resNetworkSend", "(I[BII)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkSend },
375 { "resNetworkQuery", "(ILjava/lang/String;III)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkQuery },
376 { "resNetworkResult", "(Ljava/io/FileDescriptor;)Landroid/net/DnsResolver$DnsResponse;", (void*) android_net_utils_resNetworkResult },
377 { "resNetworkCancel", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_resNetworkCancel },
378 { "getDnsNetwork", "()Landroid/net/Network;", (void*) android_net_utils_getDnsNetwork },
379 };
380
register_android_net_NetworkUtils(JNIEnv * env)381 int register_android_net_NetworkUtils(JNIEnv* env)
382 {
383 return RegisterMethodsOrDie(env, NETUTILS_PKG_NAME, gNetworkUtilMethods,
384 NELEM(gNetworkUtilMethods));
385 }
386
387 }; // namespace android
388