1 /*
2 * Copyright 2019, 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 "NetworkStackUtils-JNI"
18
19 #include <dlfcn.h>
20 #include <errno.h>
21 #include <jni.h>
22 #include <linux/filter.h>
23 #include <linux/if_arp.h>
24 #include <net/if.h>
25 #include <netinet/ether.h>
26 #include <netinet/icmp6.h>
27 #include <netinet/ip.h>
28 #include <netinet/ip6.h>
29 #include <netinet/udp.h>
30 #include <stdlib.h>
31 #include <sys/system_properties.h>
32
33 #include <string>
34
35 #include <nativehelper/JNIHelp.h>
36 #include <netjniutils/netjniutils.h>
37
38 #include <android/log.h>
39 #include <bpf/BpfClassic.h>
40
41 namespace android {
42 constexpr const char NETWORKSTACKUTILS_PKG_NAME[] =
43 "com/android/networkstack/util/NetworkStackUtils";
44
45 static const uint16_t kDhcpClientPort = 68;
46
checkLenAndCopy(JNIEnv * env,const jbyteArray & addr,int len,void * dst)47 static bool checkLenAndCopy(JNIEnv* env, const jbyteArray& addr, int len, void* dst) {
48 if (env->GetArrayLength(addr) != len) {
49 return false;
50 }
51 env->GetByteArrayRegion(addr, 0, len, reinterpret_cast<jbyte*>(dst));
52 return true;
53 }
54
network_stack_utils_addArpEntry(JNIEnv * env,jclass clazz,jbyteArray ethAddr,jbyteArray ipv4Addr,jstring ifname,jobject javaFd)55 static void network_stack_utils_addArpEntry(JNIEnv *env, jclass clazz, jbyteArray ethAddr,
56 jbyteArray ipv4Addr, jstring ifname, jobject javaFd) {
57 arpreq req = {};
58 sockaddr_in& netAddrStruct = *reinterpret_cast<sockaddr_in*>(&req.arp_pa);
59 sockaddr& ethAddrStruct = req.arp_ha;
60
61 ethAddrStruct.sa_family = ARPHRD_ETHER;
62 if (!checkLenAndCopy(env, ethAddr, ETH_ALEN, ethAddrStruct.sa_data)) {
63 jniThrowException(env, "java/io/IOException", "Invalid ethAddr length");
64 return;
65 }
66
67 netAddrStruct.sin_family = AF_INET;
68 if (!checkLenAndCopy(env, ipv4Addr, sizeof(in_addr), &netAddrStruct.sin_addr)) {
69 jniThrowException(env, "java/io/IOException", "Invalid ipv4Addr length");
70 return;
71 }
72
73 int ifLen = env->GetStringLength(ifname);
74 // IFNAMSIZ includes the terminating NULL character
75 if (ifLen >= IFNAMSIZ) {
76 jniThrowException(env, "java/io/IOException", "ifname too long");
77 return;
78 }
79 env->GetStringUTFRegion(ifname, 0, ifLen, req.arp_dev);
80
81 req.arp_flags = ATF_COM; // Completed entry (ha valid)
82 int fd = netjniutils::GetNativeFileDescriptor(env, javaFd);
83 if (fd < 0) {
84 jniThrowExceptionFmt(env, "java/io/IOException", "Invalid file descriptor");
85 return;
86 }
87 // See also: man 7 arp
88 if (ioctl(fd, SIOCSARP, &req)) {
89 jniThrowExceptionFmt(env, "java/io/IOException", "ioctl error: %s", strerror(errno));
90 return;
91 }
92 }
93
94 // fd is a "socket(AF_PACKET, SOCK_RAW, ETH_P_IP)"
95 // which guarantees packets already have skb->protocol == htons(ETH_P_IP)
network_stack_utils_attachDhcpFilter(JNIEnv * env,jclass clazz,jobject javaFd)96 static void network_stack_utils_attachDhcpFilter(JNIEnv *env, jclass clazz, jobject javaFd) {
97 static sock_filter filter_code[] = {
98 // Check the protocol is UDP.
99 BPF_LOAD_IPV4_U8(protocol),
100 BPF2_REJECT_IF_NOT_EQUAL(IPPROTO_UDP),
101
102 // Check this is not a fragment.
103 BPF_LOAD_IPV4_BE16(frag_off),
104 BPF2_REJECT_IF_ANY_MASKED_BITS_SET(IP_MF | IP_OFFMASK),
105
106 // Get the IP header length.
107 BPF_LOADX_NET_RELATIVE_IPV4_HLEN,
108
109 // Check the destination port.
110 BPF_LOAD_NETX_RELATIVE_DST_PORT,
111 BPF2_REJECT_IF_NOT_EQUAL(kDhcpClientPort),
112
113 BPF_ACCEPT,
114 };
115 const sock_fprog filter = {
116 sizeof(filter_code) / sizeof(filter_code[0]),
117 filter_code,
118 };
119
120 int fd = netjniutils::GetNativeFileDescriptor(env, javaFd);
121 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
122 jniThrowErrnoException(env, "setsockopt(SO_ATTACH_FILTER)", errno);
123 }
124 }
125
126 // fd is a "socket(AF_PACKET, SOCK_RAW, ETH_P_IPV6)"
127 // which guarantees packets already have skb->protocol == htons(ETH_P_IPV6)
network_stack_utils_attachRaFilter(JNIEnv * env,jclass clazz,jobject javaFd)128 static void network_stack_utils_attachRaFilter(JNIEnv *env, jclass clazz, jobject javaFd) {
129 static sock_filter filter_code[] = {
130 BPF_LOADX_CONSTANT_IPV6_HLEN,
131
132 // Check IPv6 Next Header is ICMPv6.
133 BPF_LOAD_IPV6_U8(nexthdr),
134 BPF2_REJECT_IF_NOT_EQUAL(IPPROTO_ICMPV6),
135
136 // Check ICMPv6 type is Router Advertisement.
137 BPF_LOAD_NETX_RELATIVE_ICMP_TYPE,
138 BPF2_REJECT_IF_NOT_EQUAL(ND_ROUTER_ADVERT),
139
140 BPF_ACCEPT,
141 };
142 static const sock_fprog filter = {
143 sizeof(filter_code) / sizeof(filter_code[0]),
144 filter_code,
145 };
146
147 int fd = netjniutils::GetNativeFileDescriptor(env, javaFd);
148 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
149 jniThrowErrnoException(env, "setsockopt(SO_ATTACH_FILTER)", errno);
150 }
151 }
152
153 // TODO: Move all this filter code into libnetutils.
154 // fd is a "socket(AF_PACKET, SOCK_RAW, ETH_P_ALL)"
network_stack_utils_attachControlPacketFilter(JNIEnv * env,jclass clazz,jobject javaFd)155 static void network_stack_utils_attachControlPacketFilter(
156 JNIEnv *env, jclass clazz, jobject javaFd) {
157 // Capture all:
158 // - ARPs
159 // - DHCPv4 packets
160 // - Router Advertisements & Solicitations
161 // - Neighbor Advertisements & Solicitations
162 //
163 // tcpdump:
164 // arp or
165 // '(ip and udp port 68)' or
166 // '(icmp6 and ip6[40] >= 133 and ip6[40] <= 136)'
167 static sock_filter filter_code[] = {
168 // Load the ethertype from skb->protocol
169 BPF_LOAD_SKB_PROTOCOL,
170
171 // Accept all ARP.
172 // TODO: Figure out how to better filter ARPs on noisy networks.
173 BPF2_ACCEPT_IF_EQUAL(ETHERTYPE_ARP),
174
175 // If IPv4: (otherwise jump to the 'IPv6 ...' below)
176 BPF_JUMP_IF_NOT_EQUAL(ETHERTYPE_IP, 14),
177
178 // Check the protocol is UDP.
179 BPF_LOAD_IPV4_U8(protocol),
180 BPF2_REJECT_IF_NOT_EQUAL(IPPROTO_UDP),
181
182 // Check this is not a fragment.
183 BPF_LOAD_IPV4_BE16(frag_off),
184 BPF2_REJECT_IF_ANY_MASKED_BITS_SET(IP_MF | IP_OFFMASK),
185
186 // Get the IP header length.
187 BPF_LOADX_NET_RELATIVE_IPV4_HLEN,
188
189 // Check the source port.
190 BPF_LOAD_NETX_RELATIVE_SRC_PORT,
191 BPF2_ACCEPT_IF_EQUAL(kDhcpClientPort),
192
193 // Check the destination port.
194 BPF_LOAD_NETX_RELATIVE_DST_PORT,
195 BPF2_ACCEPT_IF_EQUAL(kDhcpClientPort),
196
197 // Reject any other UDPv4
198 BPF_REJECT,
199
200 // IPv6 ...
201 BPF2_REJECT_IF_NOT_EQUAL(ETHERTYPE_IPV6),
202 // Assume standard, 40-byte, extension header-less ipv6 packet
203 BPF_LOADX_CONSTANT_IPV6_HLEN,
204 // ... check IPv6 Next Header is ICMPv6 (ignore fragments), ...
205 BPF_LOAD_IPV6_U8(nexthdr),
206 BPF2_REJECT_IF_NOT_EQUAL(IPPROTO_ICMPV6),
207 // ... and check the ICMPv6 type is one of RS/RA/NS/NA.
208 BPF_LOAD_NETX_RELATIVE_ICMP_TYPE,
209 BPF3_REJECT_IF_NOT_IN_RANGE(ND_ROUTER_SOLICIT, ND_NEIGHBOR_ADVERT),
210
211 BPF_ACCEPT,
212 };
213 static const sock_fprog filter = {
214 sizeof(filter_code) / sizeof(filter_code[0]),
215 filter_code,
216 };
217
218 int fd = netjniutils::GetNativeFileDescriptor(env, javaFd);
219 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
220 jniThrowErrnoException(env, "setsockopt(SO_ATTACH_FILTER)", errno);
221 }
222 }
223
224 /*
225 * JNI registration.
226 */
227 static const JNINativeMethod gNetworkStackUtilsMethods[] = {
228 /* name, signature, funcPtr */
229 { "addArpEntry", "([B[BLjava/lang/String;Ljava/io/FileDescriptor;)V", (void*) network_stack_utils_addArpEntry },
230 { "attachDhcpFilter", "(Ljava/io/FileDescriptor;)V", (void*) network_stack_utils_attachDhcpFilter },
231 { "attachRaFilter", "(Ljava/io/FileDescriptor;)V", (void*) network_stack_utils_attachRaFilter },
232 { "attachControlPacketFilter", "(Ljava/io/FileDescriptor;)V", (void*) network_stack_utils_attachControlPacketFilter },
233 };
234
JNI_OnLoad(JavaVM * vm,void *)235 extern "C" jint JNI_OnLoad(JavaVM* vm, void*) {
236 JNIEnv *env;
237 if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
238 __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "ERROR: GetEnv failed");
239 return JNI_ERR;
240 }
241
242 if (jniRegisterNativeMethods(env, NETWORKSTACKUTILS_PKG_NAME,
243 gNetworkStackUtilsMethods, NELEM(gNetworkStackUtilsMethods)) < 0) {
244 return JNI_ERR;
245 }
246
247 return JNI_VERSION_1_6;
248
249 }
250 }; // namespace android
251