dnsresolver_binder_test.cpp 15 KB

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