1 /*
2  * Copyright 2018 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  * ClatdControllerTest.cpp - unit tests for ClatdController.cpp
17  */
18 
19 #include <arpa/inet.h>
20 #include <netinet/in.h>
21 #include <string>
22 
23 #include <gtest/gtest.h>
24 
25 #include <android-base/stringprintf.h>
26 #include <android-base/strings.h>
27 #include <netutils/ifc.h>
28 
29 extern "C" {
30 #include <netutils/checksum.h>
31 }
32 
33 #include "ClatdController.h"
34 #include "IptablesBaseTest.h"
35 #include "NetworkController.h"
36 #include "tun_interface.h"
37 
38 static const char kIPv4LocalAddr[] = "192.0.0.4";
39 
40 namespace android {
41 namespace net {
42 
43 using android::base::StringPrintf;
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 class ClatdControllerTest : public IptablesBaseTest {
63   public:
ClatdControllerTest()64     ClatdControllerTest() : mClatdCtrl(nullptr) {
65         ClatdController::iptablesRestoreFunction = fakeExecIptablesRestore;
66     }
67 
SetUp()68     void SetUp() { resetIpv4AddressFreeFunc(); }
69 
70   protected:
71     ClatdController mClatdCtrl;
setIptablesDropRule(bool a,const char * b,const char * c,const char * d)72     void setIptablesDropRule(bool a, const char* b, const char* c, const char* d) {
73         std::lock_guard guard(mClatdCtrl.mutex);
74         return mClatdCtrl.setIptablesDropRule(a, b, c, d);
75     }
setIpv4AddressFreeFunc(bool (* func)(in_addr_t))76     void setIpv4AddressFreeFunc(bool (*func)(in_addr_t)) {
77         ClatdController::isIpv4AddressFreeFunc = func;
78     }
resetIpv4AddressFreeFunc()79     void resetIpv4AddressFreeFunc() {
80         ClatdController::isIpv4AddressFreeFunc = ClatdController::isIpv4AddressFree;
81     }
selectIpv4Address(const in_addr a,int16_t b)82     in_addr_t selectIpv4Address(const in_addr a, int16_t b) {
83         return ClatdController::selectIpv4Address(a, b);
84     }
makeChecksumNeutral(in6_addr * a,const in_addr b,const in6_addr & c)85     void makeChecksumNeutral(in6_addr* a, const in_addr b, const in6_addr& c) {
86         ClatdController::makeChecksumNeutral(a, b, c);
87     }
88 };
89 
TEST_F(ClatdControllerTest,SelectIpv4Address)90 TEST_F(ClatdControllerTest, SelectIpv4Address) {
91     struct in_addr addr;
92 
93     inet_pton(AF_INET, kIPv4LocalAddr, &addr);
94 
95     // If no addresses are free, return INADDR_NONE.
96     setIpv4AddressFreeFunc(neverFree);
97     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 29));
98     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 16));
99 
100     // If the configured address is free, pick that. But a prefix that's too big is invalid.
101     setIpv4AddressFreeFunc(alwaysFree);
102     EXPECT_EQ(inet_addr(kIPv4LocalAddr), selectIpv4Address(addr, 29));
103     EXPECT_EQ(inet_addr(kIPv4LocalAddr), selectIpv4Address(addr, 20));
104     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 15));
105 
106     // A prefix length of 32 works, but anything above it is invalid.
107     EXPECT_EQ(inet_addr(kIPv4LocalAddr), selectIpv4Address(addr, 32));
108     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 33));
109 
110     // If another address is free, pick it.
111     setIpv4AddressFreeFunc(over6Free);
112     EXPECT_EQ(inet_addr("192.0.0.6"), selectIpv4Address(addr, 29));
113 
114     // Check that we wrap around to addresses that are lower than the first address.
115     setIpv4AddressFreeFunc(only2Free);
116     EXPECT_EQ(inet_addr("192.0.0.2"), selectIpv4Address(addr, 29));
117     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 30));
118 
119     // If a free address exists outside the prefix, we don't pick it.
120     setIpv4AddressFreeFunc(only10Free);
121     EXPECT_EQ(INADDR_NONE, selectIpv4Address(addr, 29));
122     EXPECT_EQ(inet_addr("192.0.0.10"), selectIpv4Address(addr, 24));
123 
124     // Now try using the real function which sees if IP addresses are free using bind().
125     // Assume that the machine running the test has the address 127.0.0.1, but not 8.8.8.8.
126     resetIpv4AddressFreeFunc();
127     addr.s_addr = inet_addr("8.8.8.8");
128     EXPECT_EQ(inet_addr("8.8.8.8"), selectIpv4Address(addr, 29));
129 
130     addr.s_addr = inet_addr("127.0.0.1");
131     EXPECT_EQ(inet_addr("127.0.0.2"), selectIpv4Address(addr, 29));
132 }
133 
TEST_F(ClatdControllerTest,MakeChecksumNeutral)134 TEST_F(ClatdControllerTest, MakeChecksumNeutral) {
135     // We can't test generateIPv6Address here since it requires manipulating routing, which we can't
136     // do without talking to the real netd on the system.
137     uint32_t rand = arc4random_uniform(0xffffffff);
138     uint16_t rand1 = rand & 0xffff;
139     uint16_t rand2 = (rand >> 16) & 0xffff;
140     std::string v6PrefixStr = StringPrintf("2001:db8:%x:%x", rand1, rand2);
141     std::string v6InterfaceAddrStr = StringPrintf("%s::%x:%x", v6PrefixStr.c_str(), rand2, rand1);
142     std::string nat64PrefixStr = StringPrintf("2001:db8:%x:%x::", rand2, rand1);
143 
144     in_addr v4 = {inet_addr(kIPv4LocalAddr)};
145     in6_addr v6InterfaceAddr;
146     ASSERT_TRUE(inet_pton(AF_INET6, v6InterfaceAddrStr.c_str(), &v6InterfaceAddr));
147     in6_addr nat64Prefix;
148     ASSERT_TRUE(inet_pton(AF_INET6, nat64PrefixStr.c_str(), &nat64Prefix));
149 
150     // Generate a boatload of random IIDs.
151     int onebits = 0;
152     uint64_t prev_iid = 0;
153     for (int i = 0; i < 100000; i++) {
154         in6_addr v6 = v6InterfaceAddr;
155         makeChecksumNeutral(&v6, v4, nat64Prefix);
156 
157         // Check the generated IP address is in the same prefix as the interface IPv6 address.
158         EXPECT_EQ(0, memcmp(&v6, &v6InterfaceAddr, 8));
159 
160         // Check that consecutive IIDs are not the same.
161         uint64_t iid = *(uint64_t*)(&v6.s6_addr[8]);
162         ASSERT_TRUE(iid != prev_iid)
163                 << "Two consecutive random IIDs are the same: " << std::showbase << std::hex << iid
164                 << "\n";
165         prev_iid = iid;
166 
167         // Check that the IID is checksum-neutral with the NAT64 prefix and the
168         // local prefix.
169         uint16_t c1 = ip_checksum_finish(ip_checksum_add(0, &v4, sizeof(v4)));
170         uint16_t c2 = ip_checksum_finish(ip_checksum_add(0, &nat64Prefix, sizeof(nat64Prefix)) +
171                                          ip_checksum_add(0, &v6, sizeof(v6)));
172 
173         if (c1 != c2) {
174             char v6Str[INET6_ADDRSTRLEN];
175             inet_ntop(AF_INET6, &v6, v6Str, sizeof(v6Str));
176             FAIL() << "Bad IID: " << v6Str << " not checksum-neutral with " << kIPv4LocalAddr
177                    << " and " << nat64PrefixStr.c_str() << std::showbase << std::hex
178                    << "\n  IPv4 checksum: " << c1 << "\n  IPv6 checksum: " << c2 << "\n";
179         }
180 
181         // Check that IIDs are roughly random and use all the bits by counting the
182         // total number of bits set to 1 in a random sample of 100000 generated IIDs.
183         onebits += __builtin_popcountll(*(uint64_t*)&iid);
184     }
185     EXPECT_LE(3190000, onebits);
186     EXPECT_GE(3210000, onebits);
187 }
188 
TEST_F(ClatdControllerTest,AddIptablesRule)189 TEST_F(ClatdControllerTest, AddIptablesRule) {
190     setIptablesDropRule(true, "wlan0", "64:ff9b::", "2001:db8::1:2:3:4");
191     expectIptablesRestoreCommands((ExpectedIptablesCommands){
192             {V6,
193              "*raw\n"
194              "-A clat_raw_PREROUTING -i wlan0 -s 64:ff9b::/96 -d 2001:db8::1:2:3:4 -j DROP\n"
195              "COMMIT\n"}});
196 }
197 
TEST_F(ClatdControllerTest,RemoveIptablesRule)198 TEST_F(ClatdControllerTest, RemoveIptablesRule) {
199     setIptablesDropRule(false, "wlan0", "64:ff9b::", "2001:db8::a:b:c:d");
200     expectIptablesRestoreCommands((ExpectedIptablesCommands){
201             {V6,
202              "*raw\n"
203              "-D clat_raw_PREROUTING -i wlan0 -s 64:ff9b::/96 -d 2001:db8::a:b:c:d -j DROP\n"
204              "COMMIT\n"}});
205 }
206 
207 }  // namespace net
208 }  // namespace android
209