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