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 * binder_test.cpp - unit tests for netd binder RPCs.
17 */
18
19 #ifdef NDEBUG
20 #undef NDEBUG
21 #endif
22
23 #include <vector>
24
25 #include <openssl/base64.h>
26
27 #include <android-base/strings.h>
28 #include <android/net/IDnsResolver.h>
29 #include <binder/IPCThreadState.h>
30 #include <binder/IServiceManager.h>
31 #include <gmock/gmock-matchers.h>
32 #include <gtest/gtest.h>
33 #include <netdb.h>
34 #include <netdutils/Stopwatch.h>
35 #include "tests/BaseTestMetricsListener.h"
36 #include "tests/TestMetrics.h"
37
38 #include "NetdConstants.h" // SHA256_SIZE
39 #include "ResolverStats.h"
40 #include "dns_responder.h"
41 #include "dns_responder_client.h"
42
43 namespace binder = android::binder;
44
45 using android::IBinder;
46 using android::IServiceManager;
47 using android::ProcessState;
48 using android::sp;
49 using android::String16;
50 using android::String8;
51 using android::net::IDnsResolver;
52 using android::net::ResolverParamsParcel;
53 using android::net::ResolverStats;
54 using android::net::metrics::INetdEventListener;
55 using android::net::metrics::TestOnDnsEvent;
56 using android::netdutils::Stopwatch;
57
58 // TODO: make this dynamic and stop depending on implementation details.
59 // Sync from TEST_NETID in dns_responder_client.cpp as resolver_test.cpp does.
60 constexpr int TEST_NETID = 30;
61
62 class DnsResolverBinderTest : public ::testing::Test {
63 public:
DnsResolverBinderTest()64 DnsResolverBinderTest() {
65 sp<IServiceManager> sm = android::defaultServiceManager();
66 sp<IBinder> binder = sm->getService(String16("dnsresolver"));
67 if (binder != nullptr) {
68 mDnsResolver = android::interface_cast<IDnsResolver>(binder);
69 }
70 assert(nullptr != mDnsResolver.get());
71 // Create cache for test
72 mDnsResolver->createNetworkCache(TEST_NETID);
73 }
74
~DnsResolverBinderTest()75 ~DnsResolverBinderTest() {
76 // Destroy cache for test
77 mDnsResolver->destroyNetworkCache(TEST_NETID);
78 }
79
80 protected:
81 sp<IDnsResolver> mDnsResolver;
82 };
83
84 class TimedOperation : public Stopwatch {
85 public:
TimedOperation(const std::string & name)86 explicit TimedOperation(const std::string& name) : mName(name) {}
~TimedOperation()87 virtual ~TimedOperation() { fprintf(stderr, " %s: %6.1f ms\n", mName.c_str(), timeTaken()); }
88
89 private:
90 std::string mName;
91 };
92
93 namespace {
94
base64Encode(const std::vector<uint8_t> & input)95 std::string base64Encode(const std::vector<uint8_t>& input) {
96 size_t out_len;
97 EXPECT_EQ(1, EVP_EncodedLength(&out_len, input.size()));
98 // out_len includes the trailing NULL.
99 uint8_t output_bytes[out_len];
100 EXPECT_EQ(out_len - 1, EVP_EncodeBlock(output_bytes, input.data(), input.size()));
101 return std::string(reinterpret_cast<char*>(output_bytes));
102 }
103
104 // TODO: Convert tests to ResolverParamsParcel and delete this stub.
makeResolverParamsParcel(int netId,const std::vector<int> & params,const std::vector<std::string> & servers,const std::vector<std::string> & domains,const std::string & tlsHostname,const std::vector<std::string> & tlsServers,const std::vector<std::string> & tlsFingerprints)105 ResolverParamsParcel makeResolverParamsParcel(int netId, const std::vector<int>& params,
106 const std::vector<std::string>& servers,
107 const std::vector<std::string>& domains,
108 const std::string& tlsHostname,
109 const std::vector<std::string>& tlsServers,
110 const std::vector<std::string>& tlsFingerprints) {
111 using android::net::IDnsResolver;
112 ResolverParamsParcel paramsParcel;
113
114 paramsParcel.netId = netId;
115 paramsParcel.sampleValiditySeconds = params[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY];
116 paramsParcel.successThreshold = params[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD];
117 paramsParcel.minSamples = params[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES];
118 paramsParcel.maxSamples = params[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES];
119 if (params.size() > IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC) {
120 paramsParcel.baseTimeoutMsec = params[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC];
121 } else {
122 paramsParcel.baseTimeoutMsec = 0;
123 }
124 if (params.size() > IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT) {
125 paramsParcel.retryCount = params[IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT];
126 } else {
127 paramsParcel.retryCount = 0;
128 }
129 paramsParcel.servers = servers;
130 paramsParcel.domains = domains;
131 paramsParcel.tlsName = tlsHostname;
132 paramsParcel.tlsServers = tlsServers;
133 paramsParcel.tlsFingerprints = tlsFingerprints;
134
135 return paramsParcel;
136 }
137
138 } // namespace
139
TEST_F(DnsResolverBinderTest,IsAlive)140 TEST_F(DnsResolverBinderTest, IsAlive) {
141 TimedOperation t("isAlive RPC");
142 bool isAlive = false;
143 mDnsResolver->isAlive(&isAlive);
144 ASSERT_TRUE(isAlive);
145 }
146
147 // TODO: Move this test to resolver_test.cpp
TEST_F(DnsResolverBinderTest,EventListener_onDnsEvent)148 TEST_F(DnsResolverBinderTest, EventListener_onDnsEvent) {
149 // The test configs are used to trigger expected events. The expected results are defined in
150 // expectedResults.
151 static const struct TestConfig {
152 std::string hostname;
153 int returnCode;
154 } testConfigs[] = {
155 {"hi", 0 /*success*/},
156 {"nonexistent", EAI_NODATA},
157 };
158
159 // The expected results define expected event content for test verification.
160 static const std::vector<TestOnDnsEvent::TestResult> expectedResults = {
161 {TEST_NETID, INetdEventListener::EVENT_GETADDRINFO, 0 /*success*/, 1, "hi", "1.2.3.4"},
162 {TEST_NETID, INetdEventListener::EVENT_GETADDRINFO, EAI_NODATA, 0, "nonexistent", ""},
163 };
164
165 // Start the Binder thread pool.
166 // TODO: Consider doing this once if there has another event listener unit test.
167 android::ProcessState::self()->startThreadPool();
168
169 // Setup network.
170 // TODO: Setup device configuration and DNS responser server as resolver test does.
171 // Currently, leave DNS related configuration in this test because only it needs DNS
172 // client-server testing environment.
173 DnsResponderClient dnsClient;
174 dnsClient.SetUp();
175
176 // Setup DNS responder server.
177 constexpr char listen_addr[] = "127.0.0.3";
178 constexpr char listen_srv[] = "53";
179 test::DNSResponder dns(listen_addr, listen_srv, 250, ns_rcode::ns_r_servfail);
180 dns.addMapping("hi.example.com.", ns_type::ns_t_a, "1.2.3.4");
181 ASSERT_TRUE(dns.startServer());
182
183 // Setup DNS configuration.
184 const std::vector<std::string> test_servers = {listen_addr};
185 std::vector<std::string> test_domains = {"example.com"};
186 std::vector<int> test_params = {300 /*sample_validity*/, 25 /*success_threshold*/,
187 8 /*min_samples*/, 8 /*max_samples*/};
188
189 ASSERT_TRUE(dnsClient.SetResolversForNetwork(test_servers, test_domains, test_params));
190 dns.clearQueries();
191
192 // Register event listener.
193 android::sp<TestOnDnsEvent> testOnDnsEvent = new TestOnDnsEvent(expectedResults);
194 android::binder::Status status = mDnsResolver->registerEventListener(
195 android::interface_cast<INetdEventListener>(testOnDnsEvent));
196 ASSERT_TRUE(status.isOk()) << status.exceptionMessage();
197
198 // DNS queries.
199 // Once all expected events of expectedResults are received by the listener, the unit test will
200 // be notified. Otherwise, notified with a timeout expired failure.
201 auto& cv = testOnDnsEvent->getCv();
202 auto& cvMutex = testOnDnsEvent->getCvMutex();
203 {
204 std::unique_lock lock(cvMutex);
205
206 for (const auto& config : testConfigs) {
207 SCOPED_TRACE(config.hostname);
208
209 addrinfo* result = nullptr;
210 addrinfo hints = {.ai_family = AF_INET, .ai_socktype = SOCK_DGRAM};
211 int status = getaddrinfo(config.hostname.c_str(), nullptr, &hints, &result);
212 EXPECT_EQ(config.returnCode, status);
213
214 if (result) freeaddrinfo(result);
215 }
216
217 // Wait for receiving expected events.
218 EXPECT_EQ(std::cv_status::no_timeout, cv.wait_for(lock, std::chrono::seconds(2)));
219 }
220
221 // Verify that all testcases are passed.
222 EXPECT_TRUE(testOnDnsEvent->isVerified());
223
224 dnsClient.TearDown();
225 }
226
TEST_F(DnsResolverBinderTest,SetResolverConfiguration_Tls)227 TEST_F(DnsResolverBinderTest, SetResolverConfiguration_Tls) {
228 const std::vector<std::string> LOCALLY_ASSIGNED_DNS{"8.8.8.8", "2001:4860:4860::8888"};
229 std::vector<uint8_t> fp(SHA256_SIZE);
230 std::vector<uint8_t> short_fp(1);
231 std::vector<uint8_t> long_fp(SHA256_SIZE + 1);
232 std::vector<std::string> test_domains;
233 std::vector<int> test_params = {300, 25, 8, 8};
234 static const struct TestData {
235 const std::vector<std::string> servers;
236 const std::string tlsName;
237 const std::vector<std::vector<uint8_t>> tlsFingerprints;
238 const int expectedReturnCode;
239 } kTlsTestData[] = {
240 {{"192.0.2.1"}, "", {}, 0},
241 {{"2001:db8::2"}, "host.name", {}, 0},
242 {{"192.0.2.3"}, "@@@@", {fp}, 0},
243 {{"2001:db8::4"}, "", {fp}, 0},
244 {{}, "", {}, 0},
245 {{""}, "", {}, EINVAL},
246 {{"192.0.*.5"}, "", {}, EINVAL},
247 {{"2001:dg8::6"}, "", {}, EINVAL},
248 {{"2001:db8::c"}, "", {short_fp}, EINVAL},
249 {{"192.0.2.12"}, "", {long_fp}, EINVAL},
250 {{"2001:db8::e"}, "", {fp, fp, fp}, 0},
251 {{"192.0.2.14"}, "", {fp, short_fp}, EINVAL},
252 };
253
254 for (size_t i = 0; i < std::size(kTlsTestData); i++) {
255 const auto& td = kTlsTestData[i];
256
257 std::vector<std::string> fingerprints;
258 for (const auto& fingerprint : td.tlsFingerprints) {
259 fingerprints.push_back(base64Encode(fingerprint));
260 }
261 const auto resolverParams =
262 makeResolverParamsParcel(TEST_NETID, test_params, LOCALLY_ASSIGNED_DNS,
263 test_domains, td.tlsName, td.servers, fingerprints);
264 binder::Status status = mDnsResolver->setResolverConfiguration(resolverParams);
265
266 if (td.expectedReturnCode == 0) {
267 SCOPED_TRACE(String8::format("test case %zu should have passed", i));
268 SCOPED_TRACE(status.toString8());
269 EXPECT_EQ(0, status.exceptionCode());
270 } else {
271 SCOPED_TRACE(String8::format("test case %zu should have failed", i));
272 EXPECT_EQ(binder::Status::EX_SERVICE_SPECIFIC, status.exceptionCode());
273 EXPECT_EQ(td.expectedReturnCode, status.serviceSpecificErrorCode());
274 }
275 }
276 }
277
TEST_F(DnsResolverBinderTest,GetResolverInfo)278 TEST_F(DnsResolverBinderTest, GetResolverInfo) {
279 std::vector<std::string> servers = {"127.0.0.1", "127.0.0.2"};
280 std::vector<std::string> domains = {"example.com"};
281 std::vector<int> testParams = {
282 300, // sample validity in seconds
283 25, // success threshod in percent
284 8, 8, // {MIN,MAX}_SAMPLES
285 100, // BASE_TIMEOUT_MSEC
286 2, // retry count
287 };
288 const auto resolverParams =
289 makeResolverParamsParcel(TEST_NETID, testParams, servers, domains, "", {}, {});
290 binder::Status status = mDnsResolver->setResolverConfiguration(resolverParams);
291 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
292
293 std::vector<std::string> res_servers;
294 std::vector<std::string> res_domains;
295 std::vector<std::string> res_tls_servers;
296 std::vector<int32_t> params32;
297 std::vector<int32_t> stats32;
298 std::vector<int32_t> wait_for_pending_req_timeout_count32{0};
299 status = mDnsResolver->getResolverInfo(TEST_NETID, &res_servers, &res_domains, &res_tls_servers,
300 ¶ms32, &stats32,
301 &wait_for_pending_req_timeout_count32);
302
303 EXPECT_TRUE(status.isOk()) << status.exceptionMessage();
304 EXPECT_EQ(servers.size(), res_servers.size());
305 EXPECT_EQ(domains.size(), res_domains.size());
306 EXPECT_EQ(0U, res_tls_servers.size());
307 ASSERT_EQ(static_cast<size_t>(IDnsResolver::RESOLVER_PARAMS_COUNT), testParams.size());
308 EXPECT_EQ(testParams[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY],
309 params32[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY]);
310 EXPECT_EQ(testParams[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD],
311 params32[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD]);
312 EXPECT_EQ(testParams[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES],
313 params32[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES]);
314 EXPECT_EQ(testParams[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES],
315 params32[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES]);
316 EXPECT_EQ(testParams[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
317 params32[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC]);
318
319 std::vector<ResolverStats> stats;
320 ResolverStats::decodeAll(stats32, &stats);
321
322 EXPECT_EQ(servers.size(), stats.size());
323
324 EXPECT_THAT(res_servers, testing::UnorderedElementsAreArray(servers));
325 EXPECT_THAT(res_domains, testing::UnorderedElementsAreArray(domains));
326 }
327
TEST_F(DnsResolverBinderTest,CreateDestroyNetworkCache)328 TEST_F(DnsResolverBinderTest, CreateDestroyNetworkCache) {
329 // Must not be the same as TEST_NETID
330 const int ANOTHER_TEST_NETID = TEST_NETID + 1;
331
332 // Create a new network cache.
333 EXPECT_TRUE(mDnsResolver->createNetworkCache(ANOTHER_TEST_NETID).isOk());
334
335 // create it again, expect a EEXIST.
336 EXPECT_EQ(EEXIST,
337 mDnsResolver->createNetworkCache(ANOTHER_TEST_NETID).serviceSpecificErrorCode());
338
339 // destroy it.
340 EXPECT_TRUE(mDnsResolver->destroyNetworkCache(ANOTHER_TEST_NETID).isOk());
341
342 // re-create it
343 EXPECT_TRUE(mDnsResolver->createNetworkCache(ANOTHER_TEST_NETID).isOk());
344
345 // destroy it.
346 EXPECT_TRUE(mDnsResolver->destroyNetworkCache(ANOTHER_TEST_NETID).isOk());
347
348 // re-destroy it
349 EXPECT_TRUE(mDnsResolver->destroyNetworkCache(ANOTHER_TEST_NETID).isOk());
350 }
351
TEST_F(DnsResolverBinderTest,setLogSeverity)352 TEST_F(DnsResolverBinderTest, setLogSeverity) {
353 // Expect fail
354 EXPECT_EQ(EINVAL, mDnsResolver->setLogSeverity(-1).serviceSpecificErrorCode());
355
356 // Test set different log level
357 EXPECT_TRUE(mDnsResolver->setLogSeverity(IDnsResolver::DNS_RESOLVER_LOG_VERBOSE).isOk());
358
359 EXPECT_TRUE(mDnsResolver->setLogSeverity(IDnsResolver::DNS_RESOLVER_LOG_DEBUG).isOk());
360
361 EXPECT_TRUE(mDnsResolver->setLogSeverity(IDnsResolver::DNS_RESOLVER_LOG_INFO).isOk());
362
363 EXPECT_TRUE(mDnsResolver->setLogSeverity(IDnsResolver::DNS_RESOLVER_LOG_WARNING).isOk());
364
365 EXPECT_TRUE(mDnsResolver->setLogSeverity(IDnsResolver::DNS_RESOLVER_LOG_ERROR).isOk());
366
367 // Set back to default
368 EXPECT_TRUE(mDnsResolver->setLogSeverity(IDnsResolver::DNS_RESOLVER_LOG_WARNING).isOk());
369 }
370