1 /*
2  * Copyright (C) 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 
17 #define LOG_TAG "dns_responder_client"
18 
19 #include "dns_responder_client_ndk.h"
20 
21 #include <android/binder_manager.h>
22 #include "NetdClient.h"
23 
24 #define TEST_NETID 30
25 
26 // TODO: move this somewhere shared.
27 static const char* ANDROID_DNS_MODE = "ANDROID_DNS_MODE";
28 
29 using aidl::android::net::IDnsResolver;
30 using aidl::android::net::INetd;
31 using aidl::android::net::ResolverOptionsParcel;
32 using aidl::android::net::ResolverParamsParcel;
33 using aidl::android::net::resolv::aidl::DohParamsParcel;
34 using android::base::Error;
35 using android::base::Result;
36 using android::net::ResolverStats;
37 
Builder()38 ResolverParams::Builder::Builder() {
39     // Default resolver configuration for opportunistic mode.
40     mParcel.netId = TEST_NETID;
41 
42     // Default Resolver params.
43     mParcel.sampleValiditySeconds = 300;
44     mParcel.successThreshold = 25;
45     mParcel.minSamples = 8;
46     mParcel.maxSamples = 8;
47     mParcel.baseTimeoutMsec = 1000;
48     mParcel.retryCount = 2;
49 
50     mParcel.servers = {kDefaultServer};
51     mParcel.domains = {kDefaultSearchDomain};
52     mParcel.tlsServers = {kDefaultServer};
53     mParcel.caCertificate = kCaCert;
54     mParcel.resolverOptions = ResolverOptionsParcel{};  // optional, must be explicitly set.
55     mParcel.dohParams = std::nullopt;
56 }
57 
SetupMappings(unsigned numHosts,const std::vector<std::string> & domains,std::vector<Mapping> * mappings)58 void DnsResponderClient::SetupMappings(unsigned numHosts, const std::vector<std::string>& domains,
59                                        std::vector<Mapping>* mappings) {
60     mappings->resize(numHosts * domains.size());
61     auto mappingsIt = mappings->begin();
62     for (unsigned i = 0; i < numHosts; ++i) {
63         for (const auto& domain : domains) {
64             mappingsIt->host = fmt::format("host{}", i);
65             mappingsIt->entry = fmt::format("{}.{}.", mappingsIt->host, domain);
66             mappingsIt->ip4 = fmt::format("192.0.2.{}", i % 253 + 1);
67             mappingsIt->ip6 = fmt::format("2001:db8::{:x}", i % 65534 + 1);
68             ++mappingsIt;
69         }
70     }
71 }
72 
getResolverInfo()73 Result<ResolverInfo> DnsResponderClient::getResolverInfo() {
74     std::vector<std::string> dnsServers;
75     std::vector<std::string> domains;
76     std::vector<std::string> dotServers;
77     std::vector<int32_t> params;
78     std::vector<int32_t> stats;
79     std::vector<int32_t> waitForPendingReqTimeoutCount{0};
80     auto rv = mDnsResolvSrv->getResolverInfo(TEST_NETID, &dnsServers, &domains, &dotServers,
81                                              &params, &stats, &waitForPendingReqTimeoutCount);
82     if (!rv.isOk()) {
83         return Error() << "getResolverInfo failed: " << rv.getMessage();
84     }
85     if (stats.size() % IDnsResolver::RESOLVER_STATS_COUNT != 0) {
86         return Error() << "Unexpected stats size: " << stats.size();
87     }
88     if (params.size() != IDnsResolver::RESOLVER_PARAMS_COUNT) {
89         return Error() << "Unexpected params size: " << params.size();
90     }
91     if (waitForPendingReqTimeoutCount.size() != 1) {
92         return Error() << "Unexpected waitForPendingReqTimeoutCount size: "
93                        << waitForPendingReqTimeoutCount.size();
94     }
95 
96     ResolverInfo out = {
97             .dnsServers = std::move(dnsServers),
98             .domains = std::move(domains),
99             .dotServers = std::move(dotServers),
100             .params{
101                     .sample_validity = static_cast<uint16_t>(
102                             params[IDnsResolver::RESOLVER_PARAMS_SAMPLE_VALIDITY]),
103                     .success_threshold = static_cast<uint8_t>(
104                             params[IDnsResolver::RESOLVER_PARAMS_SUCCESS_THRESHOLD]),
105                     .min_samples =
106                             static_cast<uint8_t>(params[IDnsResolver::RESOLVER_PARAMS_MIN_SAMPLES]),
107                     .max_samples =
108                             static_cast<uint8_t>(params[IDnsResolver::RESOLVER_PARAMS_MAX_SAMPLES]),
109                     .base_timeout_msec = params[IDnsResolver::RESOLVER_PARAMS_BASE_TIMEOUT_MSEC],
110                     .retry_count = params[IDnsResolver::RESOLVER_PARAMS_RETRY_COUNT],
111             },
112             .stats = {},
113             .waitForPendingReqTimeoutCount = waitForPendingReqTimeoutCount[0],
114     };
115     ResolverStats::decodeAll(stats, &out.stats);
116 
117     return std::move(out);
118 }
119 
SetResolversForNetwork(const std::vector<std::string> & servers,const std::vector<std::string> & domains)120 bool DnsResponderClient::SetResolversForNetwork(const std::vector<std::string>& servers,
121                                                 const std::vector<std::string>& domains) {
122     const auto resolverParams = ResolverParams::Builder()
123                                         .setDomains(domains)
124                                         .setDnsServers(servers)
125                                         .setDotServers({})
126                                         .build();
127     const auto rv = mDnsResolvSrv->setResolverConfiguration(resolverParams);
128     return rv.isOk();
129 }
130 
SetResolversFromParcel(const ResolverParamsParcel & resolverParams)131 bool DnsResponderClient::SetResolversFromParcel(const ResolverParamsParcel& resolverParams) {
132     const auto rv = mDnsResolvSrv->setResolverConfiguration(resolverParams);
133     if (!rv.isOk()) LOG(ERROR) << "SetResolversFromParcel() -> " << rv.getMessage();
134     return rv.isOk();
135 }
136 
GetDefaultResolverParamsParcel()137 ResolverParamsParcel DnsResponderClient::GetDefaultResolverParamsParcel() {
138     return ResolverParams::Builder().build();
139 }
140 
SetupDNSServers(unsigned numServers,const std::vector<Mapping> & mappings,std::vector<std::unique_ptr<test::DNSResponder>> * dns,std::vector<std::string> * servers)141 void DnsResponderClient::SetupDNSServers(unsigned numServers, const std::vector<Mapping>& mappings,
142                                          std::vector<std::unique_ptr<test::DNSResponder>>* dns,
143                                          std::vector<std::string>* servers) {
144     const char* listenSrv = "53";
145     dns->resize(numServers);
146     servers->resize(numServers);
147     for (unsigned i = 0; i < numServers; ++i) {
148         auto& server = (*servers)[i];
149         auto& d = (*dns)[i];
150         server = fmt::format("127.0.0.{}", i + 100);
151         d = std::make_unique<test::DNSResponder>(server, listenSrv, ns_rcode::ns_r_servfail);
152         for (const auto& mapping : mappings) {
153             d->addMapping(mapping.entry.c_str(), ns_type::ns_t_a, mapping.ip4.c_str());
154             d->addMapping(mapping.entry.c_str(), ns_type::ns_t_aaaa, mapping.ip6.c_str());
155         }
156         d->startServer();
157     }
158 }
159 
SetupOemNetwork(int oemNetId)160 int DnsResponderClient::SetupOemNetwork(int oemNetId) {
161     mNetdSrv->networkDestroy(oemNetId);
162     mDnsResolvSrv->destroyNetworkCache(oemNetId);
163 
164     ::ndk::ScopedAStatus ret;
165     if (DnsResponderClient::isRemoteVersionSupported(mNetdSrv, 6)) {
166         const auto& config = DnsResponderClient::makeNativeNetworkConfig(
167                 oemNetId, NativeNetworkType::PHYSICAL, INetd::PERMISSION_NONE, /*secure=*/false);
168         ret = mNetdSrv->networkCreate(config);
169     } else {
170         // Only for presubmit tests that run mainline module (and its tests) on R or earlier images.
171 #pragma clang diagnostic push
172 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
173         ret = mNetdSrv->networkCreatePhysical(oemNetId, INetd::PERMISSION_NONE);
174 #pragma clang diagnostic pop
175     }
176     if (!ret.isOk()) {
177         fprintf(stderr, "Creating physical network %d failed, %s\n", oemNetId, ret.getMessage());
178         return -1;
179     }
180     ret = mDnsResolvSrv->createNetworkCache(oemNetId);
181     if (!ret.isOk()) {
182         fprintf(stderr, "Creating network cache %d failed, %s\n", oemNetId, ret.getMessage());
183         return -1;
184     }
185     setNetworkForProcess(oemNetId);
186     if ((unsigned)oemNetId != getNetworkForProcess()) {
187         return -1;
188     }
189     return 0;
190 }
191 
TearDownOemNetwork(int oemNetId)192 int DnsResponderClient::TearDownOemNetwork(int oemNetId) {
193     if (auto status = mNetdSrv->networkDestroy(oemNetId); !status.isOk()) {
194         fprintf(stderr, "Removing network %d failed, %s\n", oemNetId, status.getMessage());
195         return -1;
196     }
197     if (auto status = mDnsResolvSrv->destroyNetworkCache(oemNetId); !status.isOk()) {
198         fprintf(stderr, "Removing network cache %d failed, %s\n", oemNetId, status.getMessage());
199         return -1;
200     }
201     return 0;
202 }
203 
SetUp()204 void DnsResponderClient::SetUp() {
205     // binder setup
206     ndk::SpAIBinder netdBinder = ndk::SpAIBinder(AServiceManager_getService("netd"));
207     mNetdSrv = INetd::fromBinder(netdBinder);
208     if (mNetdSrv.get() == nullptr) {
209         LOG(FATAL) << "Can't connect to service 'netd'. Missing root privileges? uid=" << getuid();
210     }
211 
212     ndk::SpAIBinder resolvBinder = ndk::SpAIBinder(AServiceManager_getService("dnsresolver"));
213     mDnsResolvSrv = IDnsResolver::fromBinder(resolvBinder);
214     if (mDnsResolvSrv.get() == nullptr) {
215         LOG(FATAL) << "Can't connect to service 'dnsresolver'. Missing root privileges? uid="
216                    << getuid();
217     }
218 
219     // Ensure resolutions go via proxy.
220     setenv(ANDROID_DNS_MODE, "", 1);
221     SetupOemNetwork(TEST_NETID);
222 }
223 
TearDown()224 void DnsResponderClient::TearDown() {
225     TearDownOemNetwork(TEST_NETID);
226 }
227 
makeNativeNetworkConfig(int netId,NativeNetworkType networkType,int permission,bool secure)228 NativeNetworkConfig DnsResponderClient::makeNativeNetworkConfig(int netId,
229                                                                 NativeNetworkType networkType,
230                                                                 int permission, bool secure) {
231     NativeNetworkConfig config = {};
232     config.netId = netId;
233     config.networkType = networkType;
234     config.permission = permission;
235     config.secure = secure;
236     // The vpnType doesn't matter in AOSP. Just pick a well defined one from INetd.
237     config.vpnType = NativeVpnType::PLATFORM;
238     return config;
239 }
240