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 <errno.h>
20 #include <jni.h>
21 #include <linux/filter.h>
22 #include <linux/if_arp.h>
23 #include <net/if.h>
24 #include <netinet/ether.h>
25 #include <netinet/icmp6.h>
26 #include <netinet/ip.h>
27 #include <netinet/ip6.h>
28 #include <netinet/udp.h>
29 #include <stdlib.h>
30 
31 #include <string>
32 
33 #include <nativehelper/JNIHelp.h>
34 #include <nativehelper/JNIHelpCompat.h>
35 
36 #include <android/log.h>
37 
38 namespace android {
39 constexpr const char NETWORKSTACKUTILS_PKG_NAME[] = "android/net/util/NetworkStackUtils";
40 
41 static const uint32_t kEtherTypeOffset = offsetof(ether_header, ether_type);
42 static const uint32_t kEtherHeaderLen = sizeof(ether_header);
43 static const uint32_t kIPv4Protocol = kEtherHeaderLen + offsetof(iphdr, protocol);
44 static const uint32_t kIPv4FlagsOffset = kEtherHeaderLen + offsetof(iphdr, frag_off);
45 static const uint32_t kIPv6NextHeader = kEtherHeaderLen + offsetof(ip6_hdr, ip6_nxt);
46 static const uint32_t kIPv6PayloadStart = kEtherHeaderLen + sizeof(ip6_hdr);
47 static const uint32_t kICMPv6TypeOffset = kIPv6PayloadStart + offsetof(icmp6_hdr, icmp6_type);
48 static const uint32_t kUDPSrcPortIndirectOffset = kEtherHeaderLen + offsetof(udphdr, source);
49 static const uint32_t kUDPDstPortIndirectOffset = kEtherHeaderLen + offsetof(udphdr, dest);
50 static const uint16_t kDhcpClientPort = 68;
51 
checkLenAndCopy(JNIEnv * env,const jbyteArray & addr,int len,void * dst)52 static bool checkLenAndCopy(JNIEnv* env, const jbyteArray& addr, int len, void* dst) {
53     if (env->GetArrayLength(addr) != len) {
54         return false;
55     }
56     env->GetByteArrayRegion(addr, 0, len, reinterpret_cast<jbyte*>(dst));
57     return true;
58 }
59 
network_stack_utils_addArpEntry(JNIEnv * env,jobject thiz,jbyteArray ethAddr,jbyteArray ipv4Addr,jstring ifname,jobject javaFd)60 static void network_stack_utils_addArpEntry(JNIEnv *env, jobject thiz, jbyteArray ethAddr,
61         jbyteArray ipv4Addr, jstring ifname, jobject javaFd) {
62     arpreq req = {};
63     sockaddr_in& netAddrStruct = *reinterpret_cast<sockaddr_in*>(&req.arp_pa);
64     sockaddr& ethAddrStruct = req.arp_ha;
65 
66     ethAddrStruct.sa_family = ARPHRD_ETHER;
67     if (!checkLenAndCopy(env, ethAddr, ETH_ALEN, ethAddrStruct.sa_data)) {
68         jniThrowException(env, "java/io/IOException", "Invalid ethAddr length");
69         return;
70     }
71 
72     netAddrStruct.sin_family = AF_INET;
73     if (!checkLenAndCopy(env, ipv4Addr, sizeof(in_addr), &netAddrStruct.sin_addr)) {
74         jniThrowException(env, "java/io/IOException", "Invalid ipv4Addr length");
75         return;
76     }
77 
78     int ifLen = env->GetStringLength(ifname);
79     // IFNAMSIZ includes the terminating NULL character
80     if (ifLen >= IFNAMSIZ) {
81         jniThrowException(env, "java/io/IOException", "ifname too long");
82         return;
83     }
84     env->GetStringUTFRegion(ifname, 0, ifLen, req.arp_dev);
85 
86     req.arp_flags = ATF_COM;  // Completed entry (ha valid)
87     int fd = jniGetFDFromFileDescriptor(env, javaFd);
88     if (fd < 0) {
89         jniThrowExceptionFmt(env, "java/io/IOException", "Invalid file descriptor");
90         return;
91     }
92     // See also: man 7 arp
93     if (ioctl(fd, SIOCSARP, &req)) {
94         jniThrowExceptionFmt(env, "java/io/IOException", "ioctl error: %s", strerror(errno));
95         return;
96     }
97 }
98 
network_stack_utils_attachDhcpFilter(JNIEnv * env,jobject clazz,jobject javaFd)99 static void network_stack_utils_attachDhcpFilter(JNIEnv *env, jobject clazz, jobject javaFd) {
100     static sock_filter filter_code[] = {
101         // Check the protocol is UDP.
102         BPF_STMT(BPF_LD  | BPF_B    | BPF_ABS, kIPv4Protocol),
103         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   IPPROTO_UDP, 0, 6),
104 
105         // Check this is not a fragment.
106         BPF_STMT(BPF_LD  | BPF_H    | BPF_ABS, kIPv4FlagsOffset),
107         BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K,   IP_OFFMASK, 4, 0),
108 
109         // Get the IP header length.
110         BPF_STMT(BPF_LDX | BPF_B    | BPF_MSH, kEtherHeaderLen),
111 
112         // Check the destination port.
113         BPF_STMT(BPF_LD  | BPF_H    | BPF_IND, kUDPDstPortIndirectOffset),
114         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   kDhcpClientPort, 0, 1),
115 
116         // Accept or reject.
117         BPF_STMT(BPF_RET | BPF_K,              0xffff),
118         BPF_STMT(BPF_RET | BPF_K,              0)
119     };
120     static const sock_fprog filter = {
121         sizeof(filter_code) / sizeof(filter_code[0]),
122         filter_code,
123     };
124 
125     int fd = jniGetFDFromFileDescriptor(env, javaFd);
126     if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
127         jniThrowExceptionFmt(env, "java/net/SocketException",
128                 "setsockopt(SO_ATTACH_FILTER): %s", strerror(errno));
129     }
130 }
131 
network_stack_utils_attachRaFilter(JNIEnv * env,jobject clazz,jobject javaFd,jint hardwareAddressType)132 static void network_stack_utils_attachRaFilter(JNIEnv *env, jobject clazz, jobject javaFd,
133         jint hardwareAddressType) {
134     if (hardwareAddressType != ARPHRD_ETHER) {
135         jniThrowExceptionFmt(env, "java/net/SocketException",
136                 "attachRaFilter only supports ARPHRD_ETHER");
137         return;
138     }
139 
140     static sock_filter filter_code[] = {
141         // Check IPv6 Next Header is ICMPv6.
142         BPF_STMT(BPF_LD  | BPF_B   | BPF_ABS,  kIPv6NextHeader),
143         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    IPPROTO_ICMPV6, 0, 3),
144 
145         // Check ICMPv6 type is Router Advertisement.
146         BPF_STMT(BPF_LD  | BPF_B   | BPF_ABS,  kICMPv6TypeOffset),
147         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K,    ND_ROUTER_ADVERT, 0, 1),
148 
149         // Accept or reject.
150         BPF_STMT(BPF_RET | BPF_K,              0xffff),
151         BPF_STMT(BPF_RET | BPF_K,              0)
152     };
153     static const sock_fprog filter = {
154         sizeof(filter_code) / sizeof(filter_code[0]),
155         filter_code,
156     };
157 
158     int fd = jniGetFDFromFileDescriptor(env, javaFd);
159     if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
160         jniThrowExceptionFmt(env, "java/net/SocketException",
161                 "setsockopt(SO_ATTACH_FILTER): %s", strerror(errno));
162     }
163 }
164 
165 // TODO: Move all this filter code into libnetutils.
network_stack_utils_attachControlPacketFilter(JNIEnv * env,jobject clazz,jobject javaFd,jint hardwareAddressType)166 static void network_stack_utils_attachControlPacketFilter(
167         JNIEnv *env, jobject clazz, jobject javaFd, jint hardwareAddressType) {
168     if (hardwareAddressType != ARPHRD_ETHER) {
169         jniThrowExceptionFmt(env, "java/net/SocketException",
170                 "attachControlPacketFilter only supports ARPHRD_ETHER");
171         return;
172     }
173 
174     // Capture all:
175     //     - ARPs
176     //     - DHCPv4 packets
177     //     - Router Advertisements & Solicitations
178     //     - Neighbor Advertisements & Solicitations
179     //
180     // tcpdump:
181     //     arp or
182     //     '(ip and udp port 68)' or
183     //     '(icmp6 and ip6[40] >= 133 and ip6[40] <= 136)'
184     static sock_filter filter_code[] = {
185         // Load the link layer next payload field.
186         BPF_STMT(BPF_LD  | BPF_H    | BPF_ABS,  kEtherTypeOffset),
187 
188         // Accept all ARP.
189         // TODO: Figure out how to better filter ARPs on noisy networks.
190         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   ETHERTYPE_ARP, 16, 0),
191 
192         // If IPv4:
193         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   ETHERTYPE_IP, 0, 9),
194 
195         // Check the protocol is UDP.
196         BPF_STMT(BPF_LD  | BPF_B    | BPF_ABS, kIPv4Protocol),
197         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   IPPROTO_UDP, 0, 14),
198 
199         // Check this is not a fragment.
200         BPF_STMT(BPF_LD  | BPF_H    | BPF_ABS, kIPv4FlagsOffset),
201         BPF_JUMP(BPF_JMP | BPF_JSET | BPF_K,   IP_OFFMASK, 12, 0),
202 
203         // Get the IP header length.
204         BPF_STMT(BPF_LDX | BPF_B    | BPF_MSH, kEtherHeaderLen),
205 
206         // Check the source port.
207         BPF_STMT(BPF_LD  | BPF_H    | BPF_IND, kUDPSrcPortIndirectOffset),
208         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   kDhcpClientPort, 8, 0),
209 
210         // Check the destination port.
211         BPF_STMT(BPF_LD  | BPF_H    | BPF_IND, kUDPDstPortIndirectOffset),
212         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   kDhcpClientPort, 6, 7),
213 
214         // IPv6 ...
215         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   ETHERTYPE_IPV6, 0, 6),
216         // ... check IPv6 Next Header is ICMPv6 (ignore fragments), ...
217         BPF_STMT(BPF_LD  | BPF_B    | BPF_ABS, kIPv6NextHeader),
218         BPF_JUMP(BPF_JMP | BPF_JEQ  | BPF_K,   IPPROTO_ICMPV6, 0, 4),
219         // ... and check the ICMPv6 type is one of RS/RA/NS/NA.
220         BPF_STMT(BPF_LD  | BPF_B    | BPF_ABS, kICMPv6TypeOffset),
221         BPF_JUMP(BPF_JMP | BPF_JGE  | BPF_K,   ND_ROUTER_SOLICIT, 0, 2),
222         BPF_JUMP(BPF_JMP | BPF_JGT  | BPF_K,   ND_NEIGHBOR_ADVERT, 1, 0),
223 
224         // Accept or reject.
225         BPF_STMT(BPF_RET | BPF_K,              0xffff),
226         BPF_STMT(BPF_RET | BPF_K,              0)
227     };
228     static const sock_fprog filter = {
229         sizeof(filter_code) / sizeof(filter_code[0]),
230         filter_code,
231     };
232 
233     int fd = jniGetFDFromFileDescriptor(env, javaFd);
234     if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
235         jniThrowExceptionFmt(env, "java/net/SocketException",
236                 "setsockopt(SO_ATTACH_FILTER): %s", strerror(errno));
237     }
238 }
239 
240 /*
241  * JNI registration.
242  */
243 static const JNINativeMethod gNetworkStackUtilsMethods[] = {
244     /* name, signature, funcPtr */
245     { "addArpEntry", "([B[BLjava/lang/String;Ljava/io/FileDescriptor;)V", (void*) network_stack_utils_addArpEntry },
246     { "attachDhcpFilter", "(Ljava/io/FileDescriptor;)V", (void*) network_stack_utils_attachDhcpFilter },
247     { "attachRaFilter", "(Ljava/io/FileDescriptor;I)V", (void*) network_stack_utils_attachRaFilter },
248     { "attachControlPacketFilter", "(Ljava/io/FileDescriptor;I)V", (void*) network_stack_utils_attachControlPacketFilter },
249 };
250 
JNI_OnLoad(JavaVM * vm,void *)251 extern "C" jint JNI_OnLoad(JavaVM* vm, void*) {
252     JNIEnv *env;
253     if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
254         __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "ERROR: GetEnv failed");
255         return JNI_ERR;
256     }
257 
258     if (jniRegisterNativeMethods(env, NETWORKSTACKUTILS_PKG_NAME,
259             gNetworkStackUtilsMethods, NELEM(gNetworkStackUtilsMethods)) < 0) {
260         return JNI_ERR;
261     }
262 
263     return JNI_VERSION_1_6;
264 
265 }
266 }; // namespace android
267