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/ip.h>
28 #include <netinet/udp.h>
29 
30 #include <DnsProxydProtocol.h> // NETID_USE_LOCAL_NAMESERVERS
31 #include <android_runtime/AndroidRuntime.h>
32 #include <cutils/properties.h>
33 #include <nativehelper/JNIHelp.h>
34 #include <nativehelper/ScopedLocalRef.h>
35 #include <utils/Log.h>
36 #include <utils/misc.h>
37 
38 #include "NetdClient.h"
39 #include "core_jni_helpers.h"
40 #include "jni.h"
41 
42 extern "C" {
43 int ifc_enable(const char *ifname);
44 int ifc_disable(const char *ifname);
45 }
46 
47 #define NETUTILS_PKG_NAME "android/net/NetworkUtils"
48 
49 namespace android {
50 
51 constexpr int MAXPACKETSIZE = 8 * 1024;
52 // FrameworkListener limits the size of commands to 4096 bytes.
53 constexpr int MAXCMDSIZE = 4096;
54 
throwErrnoException(JNIEnv * env,const char * functionName,int error)55 static void throwErrnoException(JNIEnv* env, const char* functionName, int error) {
56     ScopedLocalRef<jstring> detailMessage(env, env->NewStringUTF(functionName));
57     if (detailMessage.get() == NULL) {
58         // Not really much we can do here. We're probably dead in the water,
59         // but let's try to stumble on...
60         env->ExceptionClear();
61     }
62     static jclass errnoExceptionClass =
63             MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/system/ErrnoException"));
64 
65     static jmethodID errnoExceptionCtor =
66             GetMethodIDOrDie(env, errnoExceptionClass,
67             "<init>", "(Ljava/lang/String;I)V");
68 
69     jobject exception = env->NewObject(errnoExceptionClass,
70                                        errnoExceptionCtor,
71                                        detailMessage.get(),
72                                        error);
73     env->Throw(reinterpret_cast<jthrowable>(exception));
74 }
75 
android_net_utils_attachDropAllBPFFilter(JNIEnv * env,jobject clazz,jobject javaFd)76 static void android_net_utils_attachDropAllBPFFilter(JNIEnv *env, jobject clazz, jobject javaFd)
77 {
78     struct sock_filter filter_code[] = {
79         // Reject all.
80         BPF_STMT(BPF_RET | BPF_K, 0)
81     };
82     struct sock_fprog filter = {
83         sizeof(filter_code) / sizeof(filter_code[0]),
84         filter_code,
85     };
86 
87     int fd = jniGetFDFromFileDescriptor(env, javaFd);
88     if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
89         jniThrowExceptionFmt(env, "java/net/SocketException",
90                 "setsockopt(SO_ATTACH_FILTER): %s", strerror(errno));
91     }
92 }
93 
android_net_utils_detachBPFFilter(JNIEnv * env,jobject clazz,jobject javaFd)94 static void android_net_utils_detachBPFFilter(JNIEnv *env, jobject clazz, jobject javaFd)
95 {
96     int dummy = 0;
97     int fd = jniGetFDFromFileDescriptor(env, javaFd);
98     if (setsockopt(fd, SOL_SOCKET, SO_DETACH_FILTER, &dummy, sizeof(dummy)) != 0) {
99         jniThrowExceptionFmt(env, "java/net/SocketException",
100                 "setsockopt(SO_DETACH_FILTER): %s", strerror(errno));
101     }
102 
103 }
104 
android_net_utils_bindProcessToNetwork(JNIEnv * env,jobject thiz,jint netId)105 static jboolean android_net_utils_bindProcessToNetwork(JNIEnv *env, jobject thiz, jint netId)
106 {
107     return (jboolean) !setNetworkForProcess(netId);
108 }
109 
android_net_utils_getBoundNetworkForProcess(JNIEnv * env,jobject thiz)110 static jint android_net_utils_getBoundNetworkForProcess(JNIEnv *env, jobject thiz)
111 {
112     return getNetworkForProcess();
113 }
114 
android_net_utils_bindProcessToNetworkForHostResolution(JNIEnv * env,jobject thiz,jint netId)115 static jboolean android_net_utils_bindProcessToNetworkForHostResolution(JNIEnv *env, jobject thiz,
116         jint netId)
117 {
118     return (jboolean) !setNetworkForResolv(netId);
119 }
120 
android_net_utils_bindSocketToNetwork(JNIEnv * env,jobject thiz,jint socket,jint netId)121 static jint android_net_utils_bindSocketToNetwork(JNIEnv *env, jobject thiz, jint socket,
122         jint netId)
123 {
124     return setNetworkForSocket(netId, socket);
125 }
126 
android_net_utils_protectFromVpn(JNIEnv * env,jobject thiz,jint socket)127 static jboolean android_net_utils_protectFromVpn(JNIEnv *env, jobject thiz, jint socket)
128 {
129     return (jboolean) !protectFromVpn(socket);
130 }
131 
android_net_utils_queryUserAccess(JNIEnv * env,jobject thiz,jint uid,jint netId)132 static jboolean android_net_utils_queryUserAccess(JNIEnv *env, jobject thiz, jint uid, jint netId)
133 {
134     return (jboolean) !queryUserAccess(uid, netId);
135 }
136 
checkLenAndCopy(JNIEnv * env,const jbyteArray & addr,int len,void * dst)137 static bool checkLenAndCopy(JNIEnv* env, const jbyteArray& addr, int len, void* dst)
138 {
139     if (env->GetArrayLength(addr) != len) {
140         return false;
141     }
142     env->GetByteArrayRegion(addr, 0, len, reinterpret_cast<jbyte*>(dst));
143     return true;
144 }
145 
android_net_utils_resNetworkQuery(JNIEnv * env,jobject thiz,jint netId,jstring dname,jint ns_class,jint ns_type,jint flags)146 static jobject android_net_utils_resNetworkQuery(JNIEnv *env, jobject thiz, jint netId,
147         jstring dname, jint ns_class, jint ns_type, jint flags) {
148     const jsize javaCharsCount = env->GetStringLength(dname);
149     const jsize byteCountUTF8 = env->GetStringUTFLength(dname);
150 
151     // Only allow dname which could be simply formatted to UTF8.
152     // In native layer, res_mkquery would re-format the input char array to packet.
153     std::vector<char> queryname(byteCountUTF8 + 1, 0);
154 
155     env->GetStringUTFRegion(dname, 0, javaCharsCount, queryname.data());
156     int fd = resNetworkQuery(netId, queryname.data(), ns_class, ns_type, flags);
157 
158     if (fd < 0) {
159         throwErrnoException(env, "resNetworkQuery", -fd);
160         return nullptr;
161     }
162 
163     return jniCreateFileDescriptor(env, fd);
164 }
165 
android_net_utils_resNetworkSend(JNIEnv * env,jobject thiz,jint netId,jbyteArray msg,jint msgLen,jint flags)166 static jobject android_net_utils_resNetworkSend(JNIEnv *env, jobject thiz, jint netId,
167         jbyteArray msg, jint msgLen, jint flags) {
168     uint8_t data[MAXCMDSIZE];
169 
170     checkLenAndCopy(env, msg, msgLen, data);
171     int fd = resNetworkSend(netId, data, msgLen, flags);
172 
173     if (fd < 0) {
174         throwErrnoException(env, "resNetworkSend", -fd);
175         return nullptr;
176     }
177 
178     return jniCreateFileDescriptor(env, fd);
179 }
180 
android_net_utils_resNetworkResult(JNIEnv * env,jobject thiz,jobject javaFd)181 static jobject android_net_utils_resNetworkResult(JNIEnv *env, jobject thiz, jobject javaFd) {
182     int fd = jniGetFDFromFileDescriptor(env, javaFd);
183     int rcode;
184     std::vector<uint8_t> buf(MAXPACKETSIZE, 0);
185 
186     int res = resNetworkResult(fd, &rcode, buf.data(), MAXPACKETSIZE);
187     jniSetFileDescriptorOfFD(env, javaFd, -1);
188     if (res < 0) {
189         throwErrnoException(env, "resNetworkResult", -res);
190         return nullptr;
191     }
192 
193     jbyteArray answer = env->NewByteArray(res);
194     if (answer == nullptr) {
195         throwErrnoException(env, "resNetworkResult", ENOMEM);
196         return nullptr;
197     } else {
198         env->SetByteArrayRegion(answer, 0, res,
199                 reinterpret_cast<jbyte*>(buf.data()));
200     }
201 
202     jclass class_DnsResponse = env->FindClass("android/net/DnsResolver$DnsResponse");
203     jmethodID ctor = env->GetMethodID(class_DnsResponse, "<init>", "([BI)V");
204 
205     return env->NewObject(class_DnsResponse, ctor, answer, rcode);
206 }
207 
android_net_utils_resNetworkCancel(JNIEnv * env,jobject thiz,jobject javaFd)208 static void android_net_utils_resNetworkCancel(JNIEnv *env, jobject thiz, jobject javaFd) {
209     int fd = jniGetFDFromFileDescriptor(env, javaFd);
210     resNetworkCancel(fd);
211     jniSetFileDescriptorOfFD(env, javaFd, -1);
212 }
213 
android_net_utils_getDnsNetwork(JNIEnv * env,jobject thiz)214 static jobject android_net_utils_getDnsNetwork(JNIEnv *env, jobject thiz) {
215     unsigned dnsNetId = 0;
216     if (int res = getNetworkForDns(&dnsNetId) < 0) {
217         throwErrnoException(env, "getDnsNetId", -res);
218         return nullptr;
219     }
220     bool privateDnsBypass = dnsNetId & NETID_USE_LOCAL_NAMESERVERS;
221 
222     static jclass class_Network = MakeGlobalRefOrDie(
223             env, FindClassOrDie(env, "android/net/Network"));
224     static jmethodID ctor = env->GetMethodID(class_Network, "<init>", "(IZ)V");
225     return env->NewObject(
226             class_Network, ctor, dnsNetId & ~NETID_USE_LOCAL_NAMESERVERS, privateDnsBypass);
227 }
228 
android_net_utils_setAllowNetworkingForProcess(JNIEnv * env,jobject thiz,jboolean hasConnectivity)229 static void android_net_utils_setAllowNetworkingForProcess(JNIEnv *env, jobject thiz,
230                                                            jboolean hasConnectivity) {
231     setAllowNetworkingForProcess(hasConnectivity == JNI_TRUE);
232 }
233 
android_net_utils_getTcpRepairWindow(JNIEnv * env,jobject thiz,jobject javaFd)234 static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jobject thiz, jobject javaFd) {
235     if (javaFd == NULL) {
236         jniThrowNullPointerException(env, NULL);
237         return NULL;
238     }
239 
240     int fd = jniGetFDFromFileDescriptor(env, javaFd);
241     struct tcp_repair_window trw = {};
242     socklen_t size = sizeof(trw);
243 
244     // Obtain the parameters of the TCP repair window.
245     int rc = getsockopt(fd, IPPROTO_TCP, TCP_REPAIR_WINDOW, &trw, &size);
246     if (rc == -1) {
247       throwErrnoException(env, "getsockopt : TCP_REPAIR_WINDOW", errno);
248       return NULL;
249     }
250 
251     struct tcp_info tcpinfo = {};
252     socklen_t tcpinfo_size = sizeof(tcp_info);
253 
254     // Obtain the window scale from the tcp info structure. This contains a scale factor that
255     // should be applied to the window size.
256     rc = getsockopt(fd, IPPROTO_TCP, TCP_INFO, &tcpinfo, &tcpinfo_size);
257     if (rc == -1) {
258       throwErrnoException(env, "getsockopt : TCP_INFO", errno);
259       return NULL;
260     }
261 
262     jclass class_TcpRepairWindow = env->FindClass("android/net/TcpRepairWindow");
263     jmethodID ctor = env->GetMethodID(class_TcpRepairWindow, "<init>", "(IIIIII)V");
264 
265     return env->NewObject(class_TcpRepairWindow, ctor, trw.snd_wl1, trw.snd_wnd, trw.max_window,
266             trw.rcv_wnd, trw.rcv_wup, tcpinfo.tcpi_rcv_wscale);
267 }
268 
269 // ----------------------------------------------------------------------------
270 
271 /*
272  * JNI registration.
273  */
274 // clang-format off
275 static const JNINativeMethod gNetworkUtilMethods[] = {
276     /* name, signature, funcPtr */
277     { "bindProcessToNetwork", "(I)Z", (void*) android_net_utils_bindProcessToNetwork },
278     { "getBoundNetworkForProcess", "()I", (void*) android_net_utils_getBoundNetworkForProcess },
279     { "bindProcessToNetworkForHostResolution", "(I)Z", (void*) android_net_utils_bindProcessToNetworkForHostResolution },
280     { "bindSocketToNetwork", "(II)I", (void*) android_net_utils_bindSocketToNetwork },
281     { "protectFromVpn", "(I)Z", (void*)android_net_utils_protectFromVpn },
282     { "queryUserAccess", "(II)Z", (void*)android_net_utils_queryUserAccess },
283     { "attachDropAllBPFFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_attachDropAllBPFFilter },
284     { "detachBPFFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_detachBPFFilter },
285     { "getTcpRepairWindow", "(Ljava/io/FileDescriptor;)Landroid/net/TcpRepairWindow;", (void*) android_net_utils_getTcpRepairWindow },
286     { "resNetworkSend", "(I[BII)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkSend },
287     { "resNetworkQuery", "(ILjava/lang/String;III)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkQuery },
288     { "resNetworkResult", "(Ljava/io/FileDescriptor;)Landroid/net/DnsResolver$DnsResponse;", (void*) android_net_utils_resNetworkResult },
289     { "resNetworkCancel", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_resNetworkCancel },
290     { "getDnsNetwork", "()Landroid/net/Network;", (void*) android_net_utils_getDnsNetwork },
291     { "setAllowNetworkingForProcess", "(Z)V", (void *)android_net_utils_setAllowNetworkingForProcess },
292 };
293 // clang-format on
294 
register_android_net_NetworkUtils(JNIEnv * env)295 int register_android_net_NetworkUtils(JNIEnv* env)
296 {
297     return RegisterMethodsOrDie(env, NETUTILS_PKG_NAME, gNetworkUtilMethods,
298                                 NELEM(gNetworkUtilMethods));
299 }
300 
301 }; // namespace android
302