1 // Copyright (C) 2022 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "libclat/clatutils.h"
16 
17 #include <android-base/stringprintf.h>
18 #include <arpa/inet.h>
19 #include <gtest/gtest.h>
20 #include <linux/if_packet.h>
21 #include <linux/if_tun.h>
22 #include <netinet/in.h>
23 #include "tun_interface.h"
24 
25 extern "C" {
26 #include "checksum.h"
27 }
28 
29 #include <aidl/android/net/INetd.h>
30 #include "clat_mark.h"
31 static_assert(aidl::android::net::INetd::CLAT_MARK == CLAT_MARK, "must be 0xDEADC1A7");
32 
33 // Default translation parameters.
34 static const char kIPv4LocalAddr[] = "192.0.0.4";
35 
36 namespace android {
37 namespace net {
38 namespace clat {
39 
40 using android::net::TunInterface;
41 using base::StringPrintf;
42 
43 class ClatUtils : public ::testing::Test {};
44 
45 // Mock functions for isIpv4AddressFree.
neverFree(in_addr_t)46 bool neverFree(in_addr_t /* addr */) {
47     return 0;
48 }
alwaysFree(in_addr_t)49 bool alwaysFree(in_addr_t /* addr */) {
50     return 1;
51 }
only2Free(in_addr_t addr)52 bool only2Free(in_addr_t addr) {
53     return (ntohl(addr) & 0xff) == 2;
54 }
over6Free(in_addr_t addr)55 bool over6Free(in_addr_t addr) {
56     return (ntohl(addr) & 0xff) >= 6;
57 }
only10Free(in_addr_t addr)58 bool only10Free(in_addr_t addr) {
59     return (ntohl(addr) & 0xff) == 10;
60 }
61 
62 // Apply mocked isIpv4AddressFree function for selectIpv4Address test.
selectIpv4Address(const in_addr ip,int16_t prefixlen,isIpv4AddrFreeFn fn)63 in_addr_t selectIpv4Address(const in_addr ip, int16_t prefixlen,
64                             isIpv4AddrFreeFn fn /* mocked function */) {
65     // Call internal function to replace isIpv4AddressFreeFn for testing.
66     return selectIpv4AddressInternal(ip, prefixlen, fn);
67 }
68 
TEST_F(ClatUtils,SelectIpv4Address)69 TEST_F(ClatUtils, SelectIpv4Address) {
70     struct in_addr addr;
71 
72     inet_pton(AF_INET, kIPv4LocalAddr, &addr);
73 
74     // If no addresses are free, return INADDR_NONE.
75     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 29, neverFree));
76     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 16, neverFree));
77 
78     // If the configured address is free, pick that. But a prefix that's too big is invalid.
79     EXPECT_EQ(inet_addr(kIPv4LocalAddr), selectIpv4Address(addr, 29, alwaysFree));
80     EXPECT_EQ(inet_addr(kIPv4LocalAddr), selectIpv4Address(addr, 20, alwaysFree));
81     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 15, alwaysFree));
82 
83     // A prefix length of 32 works, but anything above it is invalid.
84     EXPECT_EQ(inet_addr(kIPv4LocalAddr), selectIpv4Address(addr, 32, alwaysFree));
85     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 33, alwaysFree));
86 
87     // If another address is free, pick it.
88     EXPECT_EQ(inet_addr("192.0.0.6"), selectIpv4Address(addr, 29, over6Free));
89 
90     // Check that we wrap around to addresses that are lower than the first address.
91     EXPECT_EQ(inet_addr("192.0.0.2"), selectIpv4Address(addr, 29, only2Free));
92     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 30, only2Free));
93 
94     // If a free address exists outside the prefix, we don't pick it.
95     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 29, only10Free));
96     EXPECT_EQ(inet_addr("192.0.0.10"), selectIpv4Address(addr, 24, only10Free));
97 
98     // Now try using the real function which sees if IP addresses are free using bind().
99     // Assume that the machine running the test has the address 127.0.0.1, but not 8.8.8.8.
100     addr.s_addr = inet_addr("8.8.8.8");
101     EXPECT_EQ(inet_addr("8.8.8.8"), selectIpv4Address(addr, 29));
102 
103     addr.s_addr = inet_addr("127.0.0.1");
104     EXPECT_EQ(inet_addr("127.0.0.2"), selectIpv4Address(addr, 29));
105 }
106 
TEST_F(ClatUtils,MakeChecksumNeutral)107 TEST_F(ClatUtils, MakeChecksumNeutral) {
108     // We can't test generateIPv6Address here since it requires manipulating routing, which we can't
109     // do without talking to the real netd on the system.
110     uint32_t rand = arc4random_uniform(0xffffffff);
111     uint16_t rand1 = rand & 0xffff;
112     uint16_t rand2 = (rand >> 16) & 0xffff;
113     std::string v6PrefixStr = StringPrintf("2001:db8:%x:%x", rand1, rand2);
114     std::string v6InterfaceAddrStr = StringPrintf("%s::%x:%x", v6PrefixStr.c_str(), rand2, rand1);
115     std::string nat64PrefixStr = StringPrintf("2001:db8:%x:%x::", rand2, rand1);
116 
117     in_addr v4 = {inet_addr(kIPv4LocalAddr)};
118     in6_addr v6InterfaceAddr;
119     ASSERT_TRUE(inet_pton(AF_INET6, v6InterfaceAddrStr.c_str(), &v6InterfaceAddr));
120     in6_addr nat64Prefix;
121     ASSERT_TRUE(inet_pton(AF_INET6, nat64PrefixStr.c_str(), &nat64Prefix));
122 
123     // Generate a boatload of random IIDs.
124     int onebits = 0;
125     uint64_t prev_iid = 0;
126     for (int i = 0; i < 100000; i++) {
127         in6_addr v6 = v6InterfaceAddr;
128         makeChecksumNeutral(&v6, v4, nat64Prefix);
129 
130         // Check the generated IP address is in the same prefix as the interface IPv6 address.
131         EXPECT_EQ(0, memcmp(&v6, &v6InterfaceAddr, 8));
132 
133         // Check that consecutive IIDs are not the same.
134         uint64_t iid = *(uint64_t*)(&v6.s6_addr[8]);
135         ASSERT_TRUE(iid != prev_iid)
136                 << "Two consecutive random IIDs are the same: " << std::showbase << std::hex << iid
137                 << "\n";
138         prev_iid = iid;
139 
140         // Check that the IID is checksum-neutral with the NAT64 prefix and the
141         // local prefix.
142         uint16_t c1 = ip_checksum_finish(ip_checksum_add(0, &v4, sizeof(v4)));
143         uint16_t c2 = ip_checksum_finish(ip_checksum_add(0, &nat64Prefix, sizeof(nat64Prefix)) +
144                                          ip_checksum_add(0, &v6, sizeof(v6)));
145 
146         if (c1 != c2) {
147             char v6Str[INET6_ADDRSTRLEN];
148             inet_ntop(AF_INET6, &v6, v6Str, sizeof(v6Str));
149             FAIL() << "Bad IID: " << v6Str << " not checksum-neutral with " << kIPv4LocalAddr
150                    << " and " << nat64PrefixStr.c_str() << std::showbase << std::hex
151                    << "\n  IPv4 checksum: " << c1 << "\n  IPv6 checksum: " << c2 << "\n";
152         }
153 
154         // Check that IIDs are roughly random and use all the bits by counting the
155         // total number of bits set to 1 in a random sample of 100000 generated IIDs.
156         onebits += __builtin_popcountll(*(uint64_t*)&iid);
157     }
158     EXPECT_LE(3190000, onebits);
159     EXPECT_GE(3210000, onebits);
160 }
161 
TEST_F(ClatUtils,DetectMtu)162 TEST_F(ClatUtils, DetectMtu) {
163     // ::1 with bottom 32 bits set to 1 is still ::1 which routes via lo with mtu of 64KiB
164     ASSERT_EQ(detect_mtu(&in6addr_loopback, htonl(1), 0 /*MARK_UNSET*/), 65536);
165 }
166 
TEST_F(ClatUtils,ConfigurePacketSocket)167 TEST_F(ClatUtils, ConfigurePacketSocket) {
168     // Create an interface for configure_packet_socket to attach socket filter to.
169     TunInterface v6Iface;
170     ASSERT_EQ(0, v6Iface.init());
171 
172     const int s = socket(AF_PACKET, SOCK_RAW | SOCK_CLOEXEC, htons(ETH_P_IPV6));
173     EXPECT_LE(0, s);
174     struct in6_addr addr6;
175     EXPECT_EQ(1, inet_pton(AF_INET6, "2001:db8::f00", &addr6));
176     EXPECT_EQ(0, configure_packet_socket(s, &addr6, v6Iface.ifindex()));
177 
178     // Check that the packet socket is bound to the interface. We can't check the socket filter
179     // because there is no way to fetch it from the kernel.
180     sockaddr_ll sll;
181     socklen_t len = sizeof(sll);
182     ASSERT_EQ(0, getsockname(s, reinterpret_cast<sockaddr*>(&sll), &len));
183     EXPECT_EQ(htons(ETH_P_IPV6), sll.sll_protocol);
184     EXPECT_EQ(sll.sll_ifindex, v6Iface.ifindex());
185 
186     close(s);
187     v6Iface.destroy();
188 }
189 
190 // This is not a realistic test because we can't test generateIPv6Address here since it requires
191 // manipulating routing, which we can't do without talking to the real netd on the system.
192 // See test MakeChecksumNeutral.
193 // TODO: remove this test once EthernetTetheringTest can test on mainline test coverage branch.
TEST_F(ClatUtils,GenerateIpv6AddressFailWithUlaSocketAddress)194 TEST_F(ClatUtils, GenerateIpv6AddressFailWithUlaSocketAddress) {
195     // Create an interface for generateIpv6Address to connect to.
196     TunInterface tun;
197     ASSERT_EQ(0, tun.init());
198 
199     // Unused because v6 address is ULA and makeChecksumNeutral has never called.
200     in_addr v4 = {inet_addr(kIPv4LocalAddr)};
201     // Not a NAT64 prefix because test can't connect to in generateIpv6Address.
202     // Used to be a fake address from the tun interface for generating an IPv6 socket address.
203     // nat64Prefix won't be used in MakeChecksumNeutral because MakeChecksumNeutral has never
204     // be called.
205     in6_addr nat64Prefix = tun.dstAddr();  // not realistic
206     in6_addr v6;
207     EXPECT_EQ(1, inet_pton(AF_INET6, "::", &v6));  // initialize as zero
208 
209     // 0u is MARK_UNSET
210     EXPECT_EQ(-ENETUNREACH, generateIpv6Address(tun.name().c_str(), v4, nat64Prefix, &v6, 0u));
211     EXPECT_TRUE(IN6_IS_ADDR_ULA(&v6));
212 
213     tun.destroy();
214 }
215 
216 }  // namespace clat
217 }  // namespace net
218 }  // namespace android
219