1 /*
2 * Copyright 2020, 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 "NetworkUtils"
18
19 #include <android/file_descriptor_jni.h>
20 #include <android/multinetwork.h>
21 #include <linux/filter.h>
22 #include <linux/tcp.h>
23 #include <netinet/in.h>
24 #include <string.h>
25
26 #include <bpf/BpfClassic.h>
27 #include <bpf/KernelUtils.h>
28 #include <DnsProxydProtocol.h> // NETID_USE_LOCAL_NAMESERVERS
29 #include <nativehelper/JNIPlatformHelp.h>
30 #include <nativehelper/ScopedPrimitiveArray.h>
31 #include <utils/Log.h>
32
33 #include "jni.h"
34
35 #define NETUTILS_PKG_NAME "android/net/NetworkUtils"
36
37 namespace android {
38
39 constexpr int MAXPACKETSIZE = 8 * 1024;
40 // FrameworkListener limits the size of commands to 4096 bytes.
41 constexpr int MAXCMDSIZE = 4096;
42
43 static volatile jclass class_Network = 0;
44 static volatile jmethodID method_fromNetworkHandle = 0;
45
FindClassOrDie(JNIEnv * env,const char * class_name)46 static inline jclass FindClassOrDie(JNIEnv* env, const char* class_name) {
47 jclass clazz = env->FindClass(class_name);
48 LOG_ALWAYS_FATAL_IF(clazz == NULL, "Unable to find class %s", class_name);
49 return clazz;
50 }
51
52 template <typename T>
MakeGlobalRefOrDie(JNIEnv * env,T in)53 static inline T MakeGlobalRefOrDie(JNIEnv* env, T in) {
54 jobject res = env->NewGlobalRef(in);
55 LOG_ALWAYS_FATAL_IF(res == NULL, "Unable to create global reference.");
56 return static_cast<T>(res);
57 }
58
android_net_utils_attachDropAllBPFFilter(JNIEnv * env,jclass clazz,jobject javaFd)59 static void android_net_utils_attachDropAllBPFFilter(JNIEnv *env, jclass clazz, jobject javaFd)
60 {
61 static struct sock_filter filter_code[] = {
62 BPF_REJECT,
63 };
64 static const struct sock_fprog filter = {
65 sizeof(filter_code) / sizeof(filter_code[0]),
66 filter_code,
67 };
68
69 int fd = AFileDescriptor_getFd(env, javaFd);
70 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
71 jniThrowExceptionFmt(env, "java/net/SocketException",
72 "setsockopt(SO_ATTACH_FILTER): %s", strerror(errno));
73 }
74 }
75
android_net_utils_detachBPFFilter(JNIEnv * env,jclass clazz,jobject javaFd)76 static void android_net_utils_detachBPFFilter(JNIEnv *env, jclass clazz, jobject javaFd)
77 {
78 int optval_ignored = 0;
79 int fd = AFileDescriptor_getFd(env, javaFd);
80 if (setsockopt(fd, SOL_SOCKET, SO_DETACH_FILTER, &optval_ignored, sizeof(optval_ignored)) !=
81 0) {
82 jniThrowExceptionFmt(env, "java/net/SocketException",
83 "setsockopt(SO_DETACH_FILTER): %s", strerror(errno));
84 }
85 }
86
android_net_utils_bindProcessToNetworkHandle(JNIEnv * env,jclass clazz,jlong netHandle)87 static jboolean android_net_utils_bindProcessToNetworkHandle(JNIEnv *env, jclass clazz,
88 jlong netHandle)
89 {
90 return (jboolean) !android_setprocnetwork(netHandle);
91 }
92
android_net_utils_getBoundNetworkHandleForProcess(JNIEnv * env,jclass clazz)93 static jlong android_net_utils_getBoundNetworkHandleForProcess(JNIEnv *env, jclass clazz)
94 {
95 net_handle_t network;
96 if (android_getprocnetwork(&network) != 0) {
97 jniThrowExceptionFmt(env, "java/lang/IllegalStateException",
98 "android_getprocnetwork(): %s", strerror(errno));
99 return NETWORK_UNSPECIFIED;
100 }
101 return (jlong) network;
102 }
103
android_net_utils_bindProcessToNetworkForHostResolution(JNIEnv * env,jclass clazz,jint netId,jlong netHandle)104 static jboolean android_net_utils_bindProcessToNetworkForHostResolution(JNIEnv *env, jclass clazz,
105 jint netId, jlong netHandle)
106 {
107 return (jboolean) !android_setprocdns(netHandle);
108 }
109
android_net_utils_bindSocketToNetworkHandle(JNIEnv * env,jclass clazz,jobject javaFd,jlong netHandle)110 static jint android_net_utils_bindSocketToNetworkHandle(JNIEnv *env, jclass clazz, jobject javaFd,
111 jlong netHandle) {
112 return android_setsocknetwork(netHandle, AFileDescriptor_getFd(env, javaFd));
113 }
114
checkLenAndCopy(JNIEnv * env,const jbyteArray & addr,int len,void * dst)115 static bool checkLenAndCopy(JNIEnv* env, const jbyteArray& addr, int len, void* dst)
116 {
117 if (env->GetArrayLength(addr) != len) {
118 return false;
119 }
120 env->GetByteArrayRegion(addr, 0, len, reinterpret_cast<jbyte*>(dst));
121 return true;
122 }
123
android_net_utils_resNetworkQuery(JNIEnv * env,jclass clazz,jlong netHandle,jstring dname,jint ns_class,jint ns_type,jint flags)124 static jobject android_net_utils_resNetworkQuery(JNIEnv *env, jclass clazz, jlong netHandle,
125 jstring dname, jint ns_class, jint ns_type, jint flags) {
126 const jsize javaCharsCount = env->GetStringLength(dname);
127 const jsize byteCountUTF8 = env->GetStringUTFLength(dname);
128
129 // Only allow dname which could be simply formatted to UTF8.
130 // In native layer, res_mkquery would re-format the input char array to packet.
131 char queryname[byteCountUTF8 + 1];
132 memset(queryname, 0, (byteCountUTF8 + 1) * sizeof(char));
133
134 env->GetStringUTFRegion(dname, 0, javaCharsCount, queryname);
135 int fd = android_res_nquery(netHandle, queryname, ns_class, ns_type, flags);
136
137 if (fd < 0) {
138 jniThrowErrnoException(env, "resNetworkQuery", -fd);
139 return nullptr;
140 }
141
142 return jniCreateFileDescriptor(env, fd);
143 }
144
android_net_utils_resNetworkSend(JNIEnv * env,jclass clazz,jlong netHandle,jbyteArray msg,jint msgLen,jint flags)145 static jobject android_net_utils_resNetworkSend(JNIEnv *env, jclass clazz, jlong netHandle,
146 jbyteArray msg, jint msgLen, jint flags) {
147 uint8_t data[MAXCMDSIZE];
148
149 checkLenAndCopy(env, msg, msgLen, data);
150 int fd = android_res_nsend(netHandle, data, msgLen, flags);
151
152 if (fd < 0) {
153 jniThrowErrnoException(env, "resNetworkSend", -fd);
154 return nullptr;
155 }
156
157 return jniCreateFileDescriptor(env, fd);
158 }
159
android_net_utils_resNetworkResult(JNIEnv * env,jclass clazz,jobject javaFd)160 static jobject android_net_utils_resNetworkResult(JNIEnv *env, jclass clazz, jobject javaFd) {
161 int fd = AFileDescriptor_getFd(env, javaFd);
162 int rcode;
163 uint8_t buf[MAXPACKETSIZE] = {0};
164
165 int res = android_res_nresult(fd, &rcode, buf, MAXPACKETSIZE);
166 jniSetFileDescriptorOfFD(env, javaFd, -1);
167 if (res < 0) {
168 jniThrowErrnoException(env, "resNetworkResult", -res);
169 return nullptr;
170 }
171
172 jbyteArray answer = env->NewByteArray(res);
173 if (answer == nullptr) {
174 jniThrowErrnoException(env, "resNetworkResult", ENOMEM);
175 return nullptr;
176 } else {
177 env->SetByteArrayRegion(answer, 0, res, reinterpret_cast<jbyte*>(buf));
178 }
179
180 jclass class_DnsResponse = env->FindClass("android/net/DnsResolver$DnsResponse");
181 jmethodID ctor = env->GetMethodID(class_DnsResponse, "<init>", "([BI)V");
182
183 return env->NewObject(class_DnsResponse, ctor, answer, rcode);
184 }
185
android_net_utils_resNetworkCancel(JNIEnv * env,jclass clazz,jobject javaFd)186 static void android_net_utils_resNetworkCancel(JNIEnv *env, jclass clazz, jobject javaFd) {
187 int fd = AFileDescriptor_getFd(env, javaFd);
188 android_res_cancel(fd);
189 jniSetFileDescriptorOfFD(env, javaFd, -1);
190 }
191
android_net_utils_getDnsNetwork(JNIEnv * env,jclass clazz)192 static jobject android_net_utils_getDnsNetwork(JNIEnv *env, jclass clazz) {
193 net_handle_t dnsNetHandle = NETWORK_UNSPECIFIED;
194 if (int res = android_getprocdns(&dnsNetHandle) < 0) {
195 jniThrowErrnoException(env, "getDnsNetwork", -res);
196 return nullptr;
197 }
198
199 if (method_fromNetworkHandle == 0) {
200 // This may be called multiple times concurrently but that is fine
201 class_Network = MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/net/Network"));
202 method_fromNetworkHandle = env->GetStaticMethodID(class_Network, "fromNetworkHandle",
203 "(J)Landroid/net/Network;");
204 }
205 return env->CallStaticObjectMethod(class_Network, method_fromNetworkHandle,
206 static_cast<jlong>(dnsNetHandle));
207 }
208
android_net_utils_getTcpRepairWindow(JNIEnv * env,jclass clazz,jobject javaFd)209 static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jclass clazz, jobject javaFd) {
210 if (javaFd == NULL) {
211 jniThrowNullPointerException(env, NULL);
212 return NULL;
213 }
214
215 int fd = AFileDescriptor_getFd(env, javaFd);
216 struct tcp_repair_window trw = {};
217 socklen_t size = sizeof(trw);
218
219 // Obtain the parameters of the TCP repair window.
220 int rc = getsockopt(fd, IPPROTO_TCP, TCP_REPAIR_WINDOW, &trw, &size);
221 if (rc == -1) {
222 jniThrowErrnoException(env, "getsockopt : TCP_REPAIR_WINDOW", errno);
223 return NULL;
224 }
225
226 struct tcp_info tcpinfo = {};
227 socklen_t tcpinfo_size = sizeof(tcp_info);
228
229 // Obtain the window scale from the tcp info structure. This contains a scale factor that
230 // should be applied to the window size.
231 rc = getsockopt(fd, IPPROTO_TCP, TCP_INFO, &tcpinfo, &tcpinfo_size);
232 if (rc == -1) {
233 jniThrowErrnoException(env, "getsockopt : TCP_INFO", errno);
234 return NULL;
235 }
236
237 jclass class_TcpRepairWindow = env->FindClass(
238 "android/net/connectivity/android/net/TcpRepairWindow");
239 jmethodID ctor = env->GetMethodID(class_TcpRepairWindow, "<init>", "(IIIIII)V");
240
241 return env->NewObject(class_TcpRepairWindow, ctor, trw.snd_wl1, trw.snd_wnd, trw.max_window,
242 trw.rcv_wnd, trw.rcv_wup, tcpinfo.tcpi_rcv_wscale);
243 }
244
android_net_utils_setsockoptBytes(JNIEnv * env,jclass clazz,jobject javaFd,jint level,jint option,jbyteArray javaBytes)245 static void android_net_utils_setsockoptBytes(JNIEnv *env, jclass clazz, jobject javaFd,
246 jint level, jint option, jbyteArray javaBytes) {
247 int sock = AFileDescriptor_getFd(env, javaFd);
248 ScopedByteArrayRO value(env, javaBytes);
249 if (setsockopt(sock, level, option, value.get(), value.size()) != 0) {
250 jniThrowErrnoException(env, "setsockoptBytes", errno);
251 }
252 }
253
android_net_utils_isKernel64Bit(JNIEnv * env,jclass clazz)254 static jboolean android_net_utils_isKernel64Bit(JNIEnv *env, jclass clazz) {
255 return bpf::isKernel64Bit();
256 }
257
android_net_utils_isKernelX86(JNIEnv * env,jclass clazz)258 static jboolean android_net_utils_isKernelX86(JNIEnv *env, jclass clazz) {
259 return bpf::isX86();
260 }
261
262 // ----------------------------------------------------------------------------
263
264 /*
265 * JNI registration.
266 */
267 // clang-format off
268 static const JNINativeMethod gNetworkUtilMethods[] = {
269 /* name, signature, funcPtr */
270 { "bindProcessToNetworkHandle", "(J)Z", (void*) android_net_utils_bindProcessToNetworkHandle },
271 { "getBoundNetworkHandleForProcess", "()J", (void*) android_net_utils_getBoundNetworkHandleForProcess },
272 { "bindProcessToNetworkForHostResolution", "(I)Z", (void*) android_net_utils_bindProcessToNetworkForHostResolution },
273 { "bindSocketToNetworkHandle", "(Ljava/io/FileDescriptor;J)I", (void*) android_net_utils_bindSocketToNetworkHandle },
274 { "attachDropAllBPFFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_attachDropAllBPFFilter },
275 { "detachBPFFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_detachBPFFilter },
276 { "getTcpRepairWindow", "(Ljava/io/FileDescriptor;)Landroid/net/connectivity/android/net/TcpRepairWindow;", (void*) android_net_utils_getTcpRepairWindow },
277 { "resNetworkSend", "(J[BII)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkSend },
278 { "resNetworkQuery", "(JLjava/lang/String;III)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkQuery },
279 { "resNetworkResult", "(Ljava/io/FileDescriptor;)Landroid/net/DnsResolver$DnsResponse;", (void*) android_net_utils_resNetworkResult },
280 { "resNetworkCancel", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_resNetworkCancel },
281 { "getDnsNetwork", "()Landroid/net/Network;", (void*) android_net_utils_getDnsNetwork },
282 { "setsockoptBytes", "(Ljava/io/FileDescriptor;II[B)V",
283 (void*) android_net_utils_setsockoptBytes},
284 { "isKernel64Bit", "()Z", (void*) android_net_utils_isKernel64Bit },
285 { "isKernelX86", "()Z", (void*) android_net_utils_isKernelX86 },
286 };
287 // clang-format on
288
register_android_net_NetworkUtils(JNIEnv * env)289 int register_android_net_NetworkUtils(JNIEnv* env)
290 {
291 return jniRegisterNativeMethods(env, NETUTILS_PKG_NAME, gNetworkUtilMethods,
292 NELEM(gNetworkUtilMethods));
293 }
294
295 }; // namespace android
296