• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 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 #include "DnsProxyListener.h"
18 
19 #include <arpa/inet.h>
20 #include <dirent.h>
21 #include <linux/if.h>
22 #include <math.h>
23 #include <net/if.h>
24 #include <netdb.h>
25 #include <netinet/in.h>
26 #include <resolv.h>  // b64_pton()
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/socket.h>
30 
31 #define LOG_TAG "resolv"
32 
33 #include <algorithm>
34 #include <vector>
35 
36 #include <android-base/parseint.h>
37 #include <android/multinetwork.h>  // ResNsendFlags
38 #include <cutils/misc.h>           // FIRST_APPLICATION_UID
39 #include <cutils/multiuser.h>
40 #include <netdutils/InternetAddresses.h>
41 #include <netdutils/ResponseCode.h>
42 #include <netdutils/Stopwatch.h>
43 #include <netdutils/ThreadUtil.h>
44 #include <private/android_filesystem_config.h>  // AID_SYSTEM
45 #include <statslog_resolv.h>
46 #include <sysutils/SocketClient.h>
47 
48 #include "DnsResolver.h"
49 #include "Experiments.h"
50 #include "NetdPermissions.h"
51 #include "OperationLimiter.h"
52 #include "PrivateDnsConfiguration.h"
53 #include "ResolverEventReporter.h"
54 #include "dnsproxyd_protocol/DnsProxydProtocol.h"  // NETID_USE_LOCAL_NAMESERVERS
55 #include "getaddrinfo.h"
56 #include "gethnamaddr.h"
57 #include "res_send.h"
58 #include "resolv_cache.h"
59 #include "resolv_private.h"
60 #include "stats.h"  // RCODE_TIMEOUT
61 #include "stats.pb.h"
62 #include "util.h"
63 
64 using aidl::android::net::metrics::INetdEventListener;
65 using aidl::android::net::resolv::aidl::DnsHealthEventParcel;
66 using aidl::android::net::resolv::aidl::IDnsResolverUnsolicitedEventListener;
67 using android::base::ParseInt;
68 using android::base::ParseUint;
69 using std::span;
70 
71 namespace android {
72 
73 using netdutils::ResponseCode;
74 using netdutils::Stopwatch;
75 
76 namespace net {
77 namespace {
78 
79 // Limits the number of outstanding DNS queries by client UID.
80 constexpr int MAX_QUERIES_PER_UID = 256;
81 
82 android::netdutils::OperationLimiter<uid_t> queryLimiter(MAX_QUERIES_PER_UID);
83 
startQueryLimiter(uid_t uid)84 bool startQueryLimiter(uid_t uid) {
85     const int globalLimit =
86             android::net::Experiments::getInstance()->getFlag("max_queries_global", INT_MAX);
87     return queryLimiter.start(uid, globalLimit);
88 }
89 
endQueryLimiter(uid_t uid)90 void endQueryLimiter(uid_t uid) {
91     queryLimiter.finish(uid);
92 }
93 
logArguments(int argc,char ** argv)94 void logArguments(int argc, char** argv) {
95     if (!WOULD_LOG(VERBOSE)) return;
96     for (int i = 0; i < argc; i++) {
97         LOG(VERBOSE) << __func__ << ": argv[" << i << "]=" << (argv[i] ? argv[i] : "null");
98     }
99 }
100 
checkAndClearUseLocalNameserversFlag(unsigned * netid)101 bool checkAndClearUseLocalNameserversFlag(unsigned* netid) {
102     if (netid == nullptr || ((*netid) & NETID_USE_LOCAL_NAMESERVERS) == 0) {
103         return false;
104     }
105     *netid = (*netid) & ~NETID_USE_LOCAL_NAMESERVERS;
106     return true;
107 }
108 
requestingUseLocalNameservers(unsigned flags)109 constexpr bool requestingUseLocalNameservers(unsigned flags) {
110     return (flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS) != 0;
111 }
112 
queryingViaTls(unsigned dns_netid)113 bool queryingViaTls(unsigned dns_netid) {
114     const auto privateDnsStatus = PrivateDnsConfiguration::getInstance().getStatus(dns_netid);
115     switch (privateDnsStatus.mode) {
116         case PrivateDnsMode::OPPORTUNISTIC:
117             return !privateDnsStatus.validatedServers().empty();
118         case PrivateDnsMode::STRICT:
119             return true;
120         default:
121             return false;
122     }
123 }
124 
hasPermissionToBypassPrivateDns(uid_t uid)125 bool hasPermissionToBypassPrivateDns(uid_t uid) {
126     static_assert(AID_SYSTEM >= 0 && AID_SYSTEM < FIRST_APPLICATION_UID,
127                   "Calls from AID_SYSTEM must not result in a permission check to avoid deadlock.");
128     if (uid >= 0 && uid < FIRST_APPLICATION_UID) {
129         return true;
130     }
131 
132     for (const char* const permission :
133          {PERM_CONNECTIVITY_USE_RESTRICTED_NETWORKS, PERM_NETWORK_BYPASS_PRIVATE_DNS,
134           PERM_MAINLINE_NETWORK_STACK}) {
135         if (gResNetdCallbacks.check_calling_permission(permission)) {
136             return true;
137         }
138     }
139     return false;
140 }
141 
maybeFixupNetContext(android_net_context * ctx,pid_t pid)142 void maybeFixupNetContext(android_net_context* ctx, pid_t pid) {
143     if (requestingUseLocalNameservers(ctx->flags) && !hasPermissionToBypassPrivateDns(ctx->uid)) {
144         // Not permitted; clear the flag.
145         ctx->flags &= ~NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS;
146     }
147 
148     if (!requestingUseLocalNameservers(ctx->flags)) {
149         // If we're not explicitly bypassing DNS-over-TLS servers, check whether
150         // DNS-over-TLS is in use as an indicator for when to use more modern
151         // DNS resolution mechanics.
152         if (queryingViaTls(ctx->dns_netid)) {
153             ctx->flags |= NET_CONTEXT_FLAG_USE_DNS_OVER_TLS | NET_CONTEXT_FLAG_USE_EDNS;
154         }
155     }
156     ctx->pid = pid;
157 }
158 
159 void addIpAddrWithinLimit(std::vector<std::string>* ip_addrs, const sockaddr* addr,
160                           socklen_t addrlen);
161 
extractResNsendAnswers(std::span<const uint8_t> answer,int ipType,std::vector<std::string> * ip_addrs)162 int extractResNsendAnswers(std::span<const uint8_t> answer, int ipType,
163                            std::vector<std::string>* ip_addrs) {
164     int total_ip_addr_count = 0;
165     ns_msg handle;
166     if (ns_initparse(answer.data(), answer.size(), &handle) < 0) {
167         return 0;
168     }
169     int ancount = ns_msg_count(handle, ns_s_an);
170     ns_rr rr;
171     for (int i = 0; i < ancount; i++) {
172         if (ns_parserr(&handle, ns_s_an, i, &rr) < 0) {
173             continue;
174         }
175         const uint8_t* rdata = ns_rr_rdata(rr);
176         if (ipType == ns_t_a) {
177             sockaddr_in sin = {.sin_family = AF_INET};
178             memcpy(&sin.sin_addr, rdata, sizeof(sin.sin_addr));
179             addIpAddrWithinLimit(ip_addrs, (sockaddr*)&sin, sizeof(sin));
180             total_ip_addr_count++;
181         } else if (ipType == ns_t_aaaa) {
182             sockaddr_in6 sin6 = {.sin6_family = AF_INET6};
183             memcpy(&sin6.sin6_addr, rdata, sizeof(sin6.sin6_addr));
184             addIpAddrWithinLimit(ip_addrs, (sockaddr*)&sin6, sizeof(sin6));
185             total_ip_addr_count++;
186         }
187     }
188 
189     return total_ip_addr_count;
190 }
191 
extractGetAddrInfoAnswers(const addrinfo * result,std::vector<std::string> * ip_addrs)192 int extractGetAddrInfoAnswers(const addrinfo* result, std::vector<std::string>* ip_addrs) {
193     int total_ip_addr_count = 0;
194     if (result == nullptr) {
195         return 0;
196     }
197     for (const addrinfo* ai = result; ai; ai = ai->ai_next) {
198         sockaddr* ai_addr = ai->ai_addr;
199         if (ai_addr) {
200             addIpAddrWithinLimit(ip_addrs, ai_addr, ai->ai_addrlen);
201             total_ip_addr_count++;
202         }
203     }
204     return total_ip_addr_count;
205 }
206 
extractGetHostByNameAnswers(const hostent * hp,std::vector<std::string> * ip_addrs)207 int extractGetHostByNameAnswers(const hostent* hp, std::vector<std::string>* ip_addrs) {
208     int total_ip_addr_count = 0;
209     if (hp == nullptr) {
210         return 0;
211     }
212     if (hp->h_addrtype == AF_INET) {
213         in_addr** list = (in_addr**)hp->h_addr_list;
214         for (int i = 0; list[i] != nullptr; i++) {
215             sockaddr_in sin = {.sin_family = AF_INET, .sin_addr = *list[i]};
216             addIpAddrWithinLimit(ip_addrs, (sockaddr*)&sin, sizeof(sin));
217             total_ip_addr_count++;
218         }
219     } else if (hp->h_addrtype == AF_INET6) {
220         in6_addr** list = (in6_addr**)hp->h_addr_list;
221         for (int i = 0; list[i] != nullptr; i++) {
222             sockaddr_in6 sin6 = {.sin6_family = AF_INET6, .sin6_addr = *list[i]};
223             addIpAddrWithinLimit(ip_addrs, (sockaddr*)&sin6, sizeof(sin6));
224             total_ip_addr_count++;
225         }
226     }
227     return total_ip_addr_count;
228 }
229 
rcodeToAiError(int rcode)230 int rcodeToAiError(int rcode) {
231     switch (rcode) {
232         case NOERROR:
233             return 0;
234         case RCODE_TIMEOUT:
235             return NETD_RESOLV_TIMEOUT;
236         default:
237             return EAI_NODATA;
238     }
239 }
240 
resNSendToAiError(int err,int rcode)241 int resNSendToAiError(int err, int rcode) {
242     if (err > 0) {
243         return rcodeToAiError(rcode);
244     }
245     if (err == -ETIMEDOUT) {
246         return NETD_RESOLV_TIMEOUT;
247     }
248     return EAI_SYSTEM;
249 }
250 
setQueryId(span<uint8_t> msg,uint16_t query_id)251 bool setQueryId(span<uint8_t> msg, uint16_t query_id) {
252     if ((size_t)msg.size() < sizeof(HEADER)) {
253         LOG(ERROR) << __func__ << ": Invalid parameter";
254         return false;
255     }
256     auto hp = reinterpret_cast<HEADER*>(msg.data());
257     hp->id = htons(query_id);
258     return true;
259 }
260 
parseQuery(span<const uint8_t> msg,uint16_t * query_id,int * rr_type,std::string * rr_name)261 bool parseQuery(span<const uint8_t> msg, uint16_t* query_id, int* rr_type, std::string* rr_name) {
262     ns_msg handle;
263     ns_rr rr;
264     if (ns_initparse(msg.data(), msg.size(), &handle) < 0 ||
265         ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
266         return false;
267     }
268     *query_id = ns_msg_id(handle);
269     *rr_name = ns_rr_name(rr);
270     *rr_type = ns_rr_type(rr);
271     return true;
272 }
273 
274 // Note: Even if it returns PDM_OFF, it doesn't mean there's no DoT stats in the message
275 // because Private DNS mode can change at any time.
getPrivateDnsModeForMetrics(uint32_t netId)276 PrivateDnsModes getPrivateDnsModeForMetrics(uint32_t netId) {
277     // If the network `netId` doesn't exist, getStatus() sets the mode to PrivateDnsMode::OFF and
278     // returns it. This is incorrect for the metrics. Consider returning PDM_UNKNOWN in such case.
279     return convertEnumType(PrivateDnsConfiguration::getInstance().getStatus(netId).mode);
280 }
281 
initDnsEvent(NetworkDnsEventReported * event,const android_net_context & netContext)282 void initDnsEvent(NetworkDnsEventReported* event, const android_net_context& netContext) {
283     // The value 0 has the special meaning of unset/unknown in Statsd atoms. So, we set both
284     // flags to -1 as default value.
285     //  1. The hints flag is only used in resolv_getaddrinfo. When user set it to -1 in
286     //     resolv_getaddrinfo, the flag will cause validation (validateHints) failure in
287     //     getaddrinfo, so it will not do DNS query and will upload DNS stats log with
288     //     return_code = RC_EAI_BADFLAGS.
289     //  2. The res_nsend flags are only used in resolv_res_nsend. When user set it to -1 in
290     //     resolv_res_nsend,res_nsend will do nothing special by the setting.
291     event->set_hints_ai_flags(-1);
292     event->set_res_nsend_flags(-1);
293     event->set_private_dns_modes(getPrivateDnsModeForMetrics(netContext.dns_netid));
294 }
295 
296 // Return 0 if the event should not be logged.
297 // Otherwise, return subsampling_denom
getDnsEventSubsamplingRate(int netid,int returnCode,bool isMdns)298 uint32_t getDnsEventSubsamplingRate(int netid, int returnCode, bool isMdns) {
299     uint32_t subsampling_denom = resolv_cache_get_subsampling_denom(netid, returnCode, isMdns);
300     if (subsampling_denom == 0) return 0;
301     // Sample the event with a chance of 1 / denom.
302     return (arc4random_uniform(subsampling_denom) == 0) ? subsampling_denom : 0;
303 }
304 
maybeLogQuery(int eventType,const android_net_context & netContext,const NetworkDnsEventReported & event,const std::string & query_name,const std::vector<std::string> & ip_addrs)305 void maybeLogQuery(int eventType, const android_net_context& netContext,
306                    const NetworkDnsEventReported& event, const std::string& query_name,
307                    const std::vector<std::string>& ip_addrs) {
308     // Skip reverse queries.
309     if (eventType == INetdEventListener::EVENT_GETHOSTBYADDR) return;
310 
311     for (const auto& query : event.dns_query_events().dns_query_event()) {
312         // Log it when the cache misses.
313         if (query.cache_hit() != CS_FOUND) {
314             const int timeTakenMs = event.latency_micros() / 1000;
315             DnsQueryLog::Record record(netContext.dns_netid, netContext.uid, netContext.pid,
316                                        query_name, ip_addrs, timeTakenMs);
317             gDnsResolv->dnsQueryLog().push(std::move(record));
318             return;
319         }
320     }
321 }
322 
reportDnsEvent(int eventType,const android_net_context & netContext,int latencyUs,int returnCode,NetworkDnsEventReported & event,const std::string & query_name,const std::vector<std::string> & ip_addrs={},int total_ip_addr_count=0)323 void reportDnsEvent(int eventType, const android_net_context& netContext, int latencyUs,
324                     int returnCode, NetworkDnsEventReported& event, const std::string& query_name,
325                     const std::vector<std::string>& ip_addrs = {}, int total_ip_addr_count = 0) {
326     uint32_t rate =
327             (query_name.ends_with(".local") && is_mdns_supported_network(netContext.dns_netid) &&
328              android::net::Experiments::getInstance()->getFlag("mdns_resolution", 1))
329                     ? getDnsEventSubsamplingRate(netContext.dns_netid, returnCode, true)
330                     : getDnsEventSubsamplingRate(netContext.dns_netid, returnCode, false);
331 
332     if (rate) {
333         const std::string& dnsQueryStats = event.dns_query_events().SerializeAsString();
334         stats::BytesField dnsQueryBytesField{dnsQueryStats.c_str(), dnsQueryStats.size()};
335         event.set_return_code(static_cast<ReturnCode>(returnCode));
336         event.set_network_type(resolv_get_network_types_for_net(netContext.dns_netid));
337         android::net::stats::stats_write(android::net::stats::NETWORK_DNS_EVENT_REPORTED,
338                                          event.event_type(), event.return_code(),
339                                          event.latency_micros(), event.hints_ai_flags(),
340                                          event.res_nsend_flags(), event.network_type(),
341                                          event.private_dns_modes(), dnsQueryBytesField, rate);
342     }
343 
344     maybeLogQuery(eventType, netContext, event, query_name, ip_addrs);
345 
346     const auto& listeners = ResolverEventReporter::getInstance().getListeners();
347     if (listeners.empty()) {
348         LOG(ERROR) << __func__
349                    << ": DNS event not sent since no INetdEventListener receiver is available.";
350     }
351     const int latencyMs = latencyUs / 1000;
352     for (const auto& it : listeners) {
353         it->onDnsEvent(netContext.dns_netid, eventType, returnCode, latencyMs, query_name, ip_addrs,
354                        total_ip_addr_count, netContext.uid);
355     }
356 
357     const auto& unsolEventListeners = ResolverEventReporter::getInstance().getUnsolEventListeners();
358 
359     if (returnCode == NETD_RESOLV_TIMEOUT) {
360         const DnsHealthEventParcel dnsHealthEvent = {
361                 .netId = static_cast<int32_t>(netContext.dns_netid),
362                 .healthResult = IDnsResolverUnsolicitedEventListener::DNS_HEALTH_RESULT_TIMEOUT,
363         };
364         for (const auto& it : unsolEventListeners) {
365             it->onDnsHealthEvent(dnsHealthEvent);
366         }
367     } else if (returnCode == NOERROR) {
368         DnsHealthEventParcel dnsHealthEvent = {
369                 .netId = static_cast<int32_t>(netContext.dns_netid),
370                 .healthResult = IDnsResolverUnsolicitedEventListener::DNS_HEALTH_RESULT_OK,
371         };
372         for (const auto& query : event.dns_query_events().dns_query_event()) {
373             if (query.cache_hit() != CS_FOUND && query.rcode() == NS_R_NO_ERROR) {
374                 dnsHealthEvent.successRttMicros.push_back(query.latency_micros());
375             }
376         }
377 
378         if (!dnsHealthEvent.successRttMicros.empty()) {
379             for (const auto& it : unsolEventListeners) {
380                 it->onDnsHealthEvent(dnsHealthEvent);
381             }
382         }
383     }
384 }
385 
onlyIPv4Answers(const addrinfo * res)386 bool onlyIPv4Answers(const addrinfo* res) {
387     // Null addrinfo pointer isn't checked because the caller doesn't pass null pointer.
388 
389     for (const addrinfo* ai = res; ai; ai = ai->ai_next)
390         if (ai->ai_family != AF_INET) return false;
391 
392     return true;
393 }
394 
isSpecialUseIPv4Address(const struct in_addr & ia)395 bool isSpecialUseIPv4Address(const struct in_addr& ia) {
396     const uint32_t addr = ntohl(ia.s_addr);
397 
398     // Only check necessary IP ranges in RFC 5735 section 4
399     return ((addr & 0xff000000) == 0x00000000) ||  // "This" Network
400            ((addr & 0xff000000) == 0x7f000000) ||  // Loopback
401            ((addr & 0xffff0000) == 0xa9fe0000) ||  // Link Local
402            ((addr & 0xf0000000) == 0xe0000000) ||  // Multicast
403            (addr == INADDR_BROADCAST);             // Limited Broadcast
404 }
405 
isSpecialUseIPv4Address(const struct sockaddr * sa)406 bool isSpecialUseIPv4Address(const struct sockaddr* sa) {
407     if (sa->sa_family != AF_INET) return false;
408 
409     return isSpecialUseIPv4Address(((struct sockaddr_in*)sa)->sin_addr);
410 }
411 
onlyNonSpecialUseIPv4Addresses(struct hostent * hp)412 bool onlyNonSpecialUseIPv4Addresses(struct hostent* hp) {
413     // Null hostent pointer isn't checked because the caller doesn't pass null pointer.
414 
415     if (hp->h_addrtype != AF_INET) return false;
416 
417     for (int i = 0; hp->h_addr_list[i] != nullptr; i++)
418         if (isSpecialUseIPv4Address(*(struct in_addr*)hp->h_addr_list[i])) return false;
419 
420     return true;
421 }
422 
onlyNonSpecialUseIPv4Addresses(const addrinfo * res)423 bool onlyNonSpecialUseIPv4Addresses(const addrinfo* res) {
424     // Null addrinfo pointer isn't checked because the caller doesn't pass null pointer.
425 
426     for (const addrinfo* ai = res; ai; ai = ai->ai_next) {
427         if (ai->ai_family != AF_INET) return false;
428         if (isSpecialUseIPv4Address(ai->ai_addr)) return false;
429     }
430 
431     return true;
432 }
433 
logDnsQueryResult(const struct hostent * hp)434 void logDnsQueryResult(const struct hostent* hp) {
435     if (!WOULD_LOG(DEBUG)) return;
436     if (hp == nullptr) return;
437 
438     LOG(DEBUG) << __func__ << ": DNS records:";
439     for (int i = 0; hp->h_addr_list[i] != nullptr; i++) {
440         char ip_addr[INET6_ADDRSTRLEN];
441         if (inet_ntop(hp->h_addrtype, hp->h_addr_list[i], ip_addr, sizeof(ip_addr)) != nullptr) {
442             LOG(DEBUG) << __func__ << ": [" << i << "] " << hp->h_addrtype;
443         } else {
444             PLOG(DEBUG) << __func__ << ": [" << i << "] numeric hostname translation fail";
445         }
446     }
447 }
448 
logDnsQueryResult(const addrinfo * res)449 void logDnsQueryResult(const addrinfo* res) {
450     if (!WOULD_LOG(DEBUG)) return;
451     if (res == nullptr) return;
452 
453     int i;
454     const addrinfo* ai;
455     LOG(DEBUG) << __func__ << ": DNS records:";
456     for (ai = res, i = 0; ai; ai = ai->ai_next, i++) {
457         if ((ai->ai_family != AF_INET) && (ai->ai_family != AF_INET6)) continue;
458         char ip_addr[INET6_ADDRSTRLEN];
459         int ret = getnameinfo(ai->ai_addr, ai->ai_addrlen, ip_addr, sizeof(ip_addr), nullptr, 0,
460                               NI_NUMERICHOST);
461         if (!ret) {
462             LOG(DEBUG) << __func__ << ": [" << i << "] " << ai->ai_flags << " " << ai->ai_family
463                        << " " << ai->ai_socktype << " " << ai->ai_protocol << " " << ip_addr;
464         } else {
465             LOG(DEBUG) << __func__ << ": [" << i << "] numeric hostname translation fail " << ret;
466         }
467     }
468 }
469 
isValidNat64Prefix(const netdutils::IPPrefix prefix)470 bool isValidNat64Prefix(const netdutils::IPPrefix prefix) {
471     if (prefix.family() != AF_INET6) {
472         LOG(ERROR) << __func__ << ": Only IPv6 NAT64 prefixes are supported " << prefix.family();
473         return false;
474     }
475     if (prefix.length() != 96) {
476         LOG(ERROR) << __func__ << ": Only /96 NAT64 prefixes are supported " << prefix.length();
477         return false;
478     }
479     return true;
480 }
481 
synthesizeNat64PrefixWithARecord(const netdutils::IPPrefix & prefix,struct hostent * hp)482 bool synthesizeNat64PrefixWithARecord(const netdutils::IPPrefix& prefix, struct hostent* hp) {
483     if (hp == nullptr) return false;
484     if (!onlyNonSpecialUseIPv4Addresses(hp)) return false;
485     if (!isValidNat64Prefix(prefix)) return false;
486 
487     struct sockaddr_storage ss = netdutils::IPSockAddr(prefix.ip());
488     struct sockaddr_in6* v6prefix = (struct sockaddr_in6*)&ss;
489     for (int i = 0; hp->h_addr_list[i] != nullptr; i++) {
490         struct in_addr iaOriginal = *(struct in_addr*)hp->h_addr_list[i];
491         struct in6_addr* ia6 = (struct in6_addr*)hp->h_addr_list[i];
492         memset(ia6, 0, sizeof(struct in6_addr));
493 
494         // Synthesize /96 NAT64 prefix in place. The space has reserved by getanswer() and
495         // _hf_gethtbyname2() in system/netd/resolv/gethnamaddr.cpp and
496         // system/netd/resolv/sethostent.cpp.
497         *ia6 = v6prefix->sin6_addr;
498         ia6->s6_addr32[3] = iaOriginal.s_addr;
499 
500         if (WOULD_LOG(VERBOSE)) {
501             char buf[INET6_ADDRSTRLEN];  // big enough for either IPv4 or IPv6
502             inet_ntop(AF_INET, &iaOriginal.s_addr, buf, sizeof(buf));
503             LOG(VERBOSE) << __func__ << ": DNS A record: " << buf;
504             inet_ntop(AF_INET6, &v6prefix->sin6_addr, buf, sizeof(buf));
505             LOG(VERBOSE) << __func__ << ": NAT64 prefix: " << buf;
506             inet_ntop(AF_INET6, ia6, buf, sizeof(buf));
507             LOG(VERBOSE) << __func__ << ": DNS64 Synthesized AAAA record: " << buf;
508         }
509     }
510     hp->h_addrtype = AF_INET6;
511     hp->h_length = sizeof(in6_addr);
512 
513     logDnsQueryResult(hp);
514     return true;
515 }
516 
synthesizeNat64PrefixWithARecord(const netdutils::IPPrefix & prefix,addrinfo ** res,bool unspecWantedButNoIPv6,const android_net_context * netcontext)517 bool synthesizeNat64PrefixWithARecord(const netdutils::IPPrefix& prefix, addrinfo** res,
518                                       bool unspecWantedButNoIPv6,
519                                       const android_net_context* netcontext) {
520     if (*res == nullptr) return false;
521     if (!onlyNonSpecialUseIPv4Addresses(*res)) return false;
522     if (!isValidNat64Prefix(prefix)) return false;
523 
524     const sockaddr_storage ss = netdutils::IPSockAddr(prefix.ip());
525     const sockaddr_in6* v6prefix = (sockaddr_in6*)&ss;
526     addrinfo* const head4 = *res;
527     addrinfo* head6 = nullptr;
528     addrinfo* cur6 = nullptr;
529 
530     // Build a synthesized AAAA addrinfo list from the queried A addrinfo list. Here is the diagram
531     // for the relationship of pointers.
532     //
533     // head4: point to the first queried A addrinfo
534     // |
535     // v
536     // +-------------+   +-------------+
537     // | addrinfo4#1 |-->| addrinfo4#2 |--> .. queried A addrinfo(s) for DNS64 synthesis
538     // +-------------+   +-------------+
539     //                   ^
540     //                   |
541     //                   cur4: current worked-on queried A addrinfo
542     //
543     // head6: point to the first synthesized AAAA addrinfo
544     // |
545     // v
546     // +-------------+   +-------------+
547     // | addrinfo6#1 |-->| addrinfo6#2 |--> .. synthesized DNS64 AAAA addrinfo(s)
548     // +-------------+   +-------------+
549     //                   ^
550     //                   |
551     //                   cur6: current worked-on synthesized addrinfo
552     //
553     for (const addrinfo* cur4 = head4; cur4; cur4 = cur4->ai_next) {
554         // Allocate a space for a synthesized AAAA addrinfo. Note that the addrinfo and sockaddr
555         // occupy one contiguous block of memory and are allocated and freed as a single block.
556         // See get_ai and freeaddrinfo in packages/modules/DnsResolver/getaddrinfo.cpp.
557         addrinfo* sa = (addrinfo*)calloc(1, sizeof(addrinfo) + sizeof(sockaddr_in6));
558         if (sa == nullptr) {
559             LOG(ERROR) << "allocate memory failed for synthesized result";
560             freeaddrinfo(head6);
561             return false;
562         }
563 
564         // Initialize the synthesized AAAA addrinfo by the queried A addrinfo. The ai_addr will be
565         // set lately.
566         sa->ai_flags = cur4->ai_flags;
567         sa->ai_family = AF_INET6;
568         sa->ai_socktype = cur4->ai_socktype;
569         sa->ai_protocol = cur4->ai_protocol;
570         sa->ai_addrlen = sizeof(sockaddr_in6);
571         sa->ai_addr = (sockaddr*)(sa + 1);
572         sa->ai_canonname = nullptr;
573         sa->ai_next = nullptr;
574 
575         if (cur4->ai_canonname != nullptr) {
576             sa->ai_canonname = strdup(cur4->ai_canonname);
577             if (sa->ai_canonname == nullptr) {
578                 LOG(ERROR) << "allocate memory failed for canonname";
579                 freeaddrinfo(sa);
580                 freeaddrinfo(head6);
581                 return false;
582             }
583         }
584 
585         // Synthesize /96 NAT64 prefix with the queried IPv4 address.
586         const sockaddr_in* sin4 = (sockaddr_in*)cur4->ai_addr;
587         sockaddr_in6* sin6 = (sockaddr_in6*)sa->ai_addr;
588         sin6->sin6_addr = v6prefix->sin6_addr;
589         sin6->sin6_addr.s6_addr32[3] = sin4->sin_addr.s_addr;
590         sin6->sin6_family = AF_INET6;
591         sin6->sin6_port = sin4->sin_port;
592 
593         // If the synthesized list is empty, this becomes the first element.
594         if (head6 == nullptr) {
595             head6 = sa;
596         }
597 
598         // Add this element to the end of the synthesized list.
599         if (cur6 != nullptr) {
600             cur6->ai_next = sa;
601         }
602         cur6 = sa;
603 
604         if (WOULD_LOG(VERBOSE)) {
605             char buf[INET6_ADDRSTRLEN];  // big enough for either IPv4 or IPv6
606             inet_ntop(AF_INET, &sin4->sin_addr.s_addr, buf, sizeof(buf));
607             LOG(VERBOSE) << __func__ << ": DNS A record: " << buf;
608             inet_ntop(AF_INET6, &v6prefix->sin6_addr, buf, sizeof(buf));
609             LOG(VERBOSE) << __func__ << ": NAT64 prefix: " << buf;
610             inet_ntop(AF_INET6, &sin6->sin6_addr, buf, sizeof(buf));
611             LOG(VERBOSE) << __func__ << ": DNS64 Synthesized AAAA record: " << buf;
612         }
613     }
614 
615     // Simply concatenate the synthesized AAAA addrinfo list and the queried A addrinfo list when
616     // AF_UNSPEC is specified. In the other words, the IPv6 addresses are listed first and then
617     // IPv4 addresses. For example:
618     //     64:ff9b::102:304 (socktype=2, protocol=17) ->
619     //     64:ff9b::102:304 (socktype=1, protocol=6) ->
620     //     1.2.3.4 (socktype=2, protocol=17) ->
621     //     1.2.3.4 (socktype=1, protocol=6)
622     // Note that head6 and cur6 should be non-null because there was at least one IPv4 address
623     // synthesized. From the above example, the synthesized addrinfo list puts IPv6 and IPv4 in
624     // groups and sort by RFC 6724 later. This ordering is different from no synthesized case
625     // because resolv_getaddrinfo() sorts results in explore_options. resolv_getaddrinfo() calls
626     // explore_fqdn() many times by the different items of explore_options. It means that
627     // resolv_rfc6724_sort() only sorts the results in each explore_options and concatenates each
628     // results into one. For example, getaddrinfo() is called with null hints for a domain name
629     // which has both IPv4 and IPv6 addresses. The address order of the result addrinfo may be:
630     //     2001:db8::102:304 (socktype=2, protocol=17) -> 1.2.3.4 (socktype=2, protocol=17) ->
631     //     2001:db8::102:304 (socktype=1, protocol=6) -> 1.2.3.4 (socktype=1, protocol=6)
632     // In above example, the first two results come from one explore option and the last two come
633     // from another one. They are sorted first, and then concatenate together to be the result.
634     // See also resolv_getaddrinfo in packages/modules/DnsResolver/getaddrinfo.cpp.
635     if (unspecWantedButNoIPv6) {
636         cur6->ai_next = head4;
637     } else {
638         freeaddrinfo(head4);
639     }
640 
641     // Sort the concatenated addresses by RFC 6724 section 2.1.
642     struct addrinfo sorting_head = {.ai_next = head6};
643     resolv_rfc6724_sort(&sorting_head, netcontext->app_mark, netcontext->uid);
644 
645     *res = sorting_head.ai_next;
646     logDnsQueryResult(*res);
647     return true;
648 }
649 
getDns64Prefix(unsigned netId,netdutils::IPPrefix * prefix)650 bool getDns64Prefix(unsigned netId, netdutils::IPPrefix* prefix) {
651     return !gDnsResolv->resolverCtrl.getPrefix64(netId, prefix);
652 }
653 
makeThreadName(unsigned netId,uint32_t uid)654 std::string makeThreadName(unsigned netId, uint32_t uid) {
655     // The maximum of netId and app_id are 5-digit numbers.
656     return fmt::format("Dns_{}_{}", netId, multiuser_get_app_id(uid));
657 }
658 
659 }  // namespace
660 
DnsProxyListener()661 DnsProxyListener::DnsProxyListener() : FrameworkListener(SOCKET_NAME) {
662     mGetAddrInfoCmd = std::make_unique<GetAddrInfoCmd>();
663     registerCmd(mGetAddrInfoCmd.get());
664 
665     mGetHostByAddrCmd = std::make_unique<GetHostByAddrCmd>();
666     registerCmd(mGetHostByAddrCmd.get());
667 
668     mGetHostByNameCmd = std::make_unique<GetHostByNameCmd>();
669     registerCmd(mGetHostByNameCmd.get());
670 
671     mResNSendCommand = std::make_unique<ResNSendCommand>();
672     registerCmd(mResNSendCommand.get());
673 
674     mGetDnsNetIdCommand = std::make_unique<GetDnsNetIdCommand>();
675     registerCmd(mGetDnsNetIdCommand.get());
676 }
677 
spawn()678 void DnsProxyListener::Handler::spawn() {
679     const int rval = netdutils::threadLaunch(this);
680     if (rval == 0) {
681         return;
682     }
683 
684     char* msg = nullptr;
685     asprintf(&msg, "%s (%d)", strerror(-rval), -rval);
686     mClient->sendMsg(ResponseCode::OperationFailed, msg, false);
687     free(msg);
688     delete this;
689 }
690 
GetAddrInfoHandler(SocketClient * c,std::string host,std::string service,std::unique_ptr<addrinfo> hints,const android_net_context & netcontext)691 DnsProxyListener::GetAddrInfoHandler::GetAddrInfoHandler(SocketClient* c, std::string host,
692                                                          std::string service,
693                                                          std::unique_ptr<addrinfo> hints,
694                                                          const android_net_context& netcontext)
695     : Handler(c),
696       mHost(std::move(host)),
697       mService(std::move(service)),
698       mHints(std::move(hints)),
699       mNetContext(netcontext) {}
700 
701 // Before U, the Netd callback is implemented by OEM to evaluate if a DNS query for the provided
702 // hostname is allowed. On U+, the Netd callback also checks if the user is allowed to send DNS on
703 // the specified network.
evaluate_domain_name(const android_net_context & netcontext,const char * host)704 static bool evaluate_domain_name(const android_net_context& netcontext, const char* host) {
705     if (!gResNetdCallbacks.evaluate_domain_name) return true;
706     return gResNetdCallbacks.evaluate_domain_name(netcontext, host);
707 }
708 
HandleArgumentError(SocketClient * cli,int errorcode,std::string strerrormessage,int argc,char ** argv)709 static int HandleArgumentError(SocketClient* cli, int errorcode, std::string strerrormessage,
710                                int argc, char** argv) {
711     for (int i = 0; i < argc; i++) {
712         strerrormessage += "argv[" + std::to_string(i) + "]=" + (argv[i] ? argv[i] : "null") + " ";
713     }
714 
715     LOG(WARNING) << strerrormessage;
716     cli->sendMsg(errorcode, strerrormessage.c_str(), false);
717     return -1;
718 }
719 
sendBE32(SocketClient * c,uint32_t data)720 static bool sendBE32(SocketClient* c, uint32_t data) {
721     uint32_t be_data = htonl(data);
722     return c->sendData(&be_data, sizeof(be_data)) == 0;
723 }
724 
725 // Sends 4 bytes of big-endian length, followed by the data.
726 // Returns true on success.
sendLenAndData(SocketClient * c,const int len,const void * data)727 static bool sendLenAndData(SocketClient* c, const int len, const void* data) {
728     return sendBE32(c, len) && (len == 0 || c->sendData(data, len) == 0);
729 }
730 
731 // Returns true on success
sendhostent(SocketClient * c,hostent * hp)732 static bool sendhostent(SocketClient* c, hostent* hp) {
733     bool success = true;
734     int i;
735     if (hp->h_name != nullptr) {
736         success &= sendLenAndData(c, strlen(hp->h_name) + 1, hp->h_name);
737     } else {
738         success &= sendLenAndData(c, 0, "") == 0;
739     }
740 
741     for (i = 0; hp->h_aliases[i] != nullptr; i++) {
742         success &= sendLenAndData(c, strlen(hp->h_aliases[i]) + 1, hp->h_aliases[i]);
743     }
744     success &= sendLenAndData(c, 0, "");  // null to indicate we're done
745 
746     uint32_t buf = htonl(hp->h_addrtype);
747     success &= c->sendData(&buf, sizeof(buf)) == 0;
748 
749     buf = htonl(hp->h_length);
750     success &= c->sendData(&buf, sizeof(buf)) == 0;
751 
752     for (i = 0; hp->h_addr_list[i] != nullptr; i++) {
753         success &= sendLenAndData(c, 16, hp->h_addr_list[i]);
754     }
755     success &= sendLenAndData(c, 0, "");  // null to indicate we're done
756     return success;
757 }
758 
sendaddrinfo(SocketClient * c,addrinfo * ai)759 static bool sendaddrinfo(SocketClient* c, addrinfo* ai) {
760     // struct addrinfo {
761     //      int     ai_flags;       /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
762     //      int     ai_family;      /* PF_xxx */
763     //      int     ai_socktype;    /* SOCK_xxx */
764     //      int     ai_protocol;    /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
765     //      socklen_t ai_addrlen;   /* length of ai_addr */
766     //      char    *ai_canonname;  /* canonical name for hostname */
767     //      struct  sockaddr *ai_addr;      /* binary address */
768     //      struct  addrinfo *ai_next;      /* next structure in linked list */
769     // };
770 
771     // Write the struct piece by piece because we might be a 64-bit netd
772     // talking to a 32-bit process.
773     bool success = sendBE32(c, ai->ai_flags) && sendBE32(c, ai->ai_family) &&
774                    sendBE32(c, ai->ai_socktype) && sendBE32(c, ai->ai_protocol);
775     if (!success) {
776         return false;
777     }
778 
779     // ai_addrlen and ai_addr.
780     if (!sendLenAndData(c, ai->ai_addrlen, ai->ai_addr)) {
781         return false;
782     }
783 
784     // strlen(ai_canonname) and ai_canonname.
785     if (!sendLenAndData(c, ai->ai_canonname ? strlen(ai->ai_canonname) + 1 : 0, ai->ai_canonname)) {
786         return false;
787     }
788 
789     return true;
790 }
791 
doDns64Synthesis(int32_t * rv,addrinfo ** res,NetworkDnsEventReported * event)792 void DnsProxyListener::GetAddrInfoHandler::doDns64Synthesis(int32_t* rv, addrinfo** res,
793                                                             NetworkDnsEventReported* event) {
794     const bool ipv6WantedButNoData = (mHints && mHints->ai_family == AF_INET6 && *rv == EAI_NODATA);
795     const bool unspecWantedButNoIPv6 =
796             ((!mHints || mHints->ai_family == AF_UNSPEC) && *rv == 0 && onlyIPv4Answers(*res));
797 
798     if (!ipv6WantedButNoData && !unspecWantedButNoIPv6) {
799         return;
800     }
801 
802     netdutils::IPPrefix prefix{};
803     if (!getDns64Prefix(mNetContext.dns_netid, &prefix)) {
804         return;
805     }
806 
807     if (ipv6WantedButNoData) {
808         // If caller wants IPv6 answers but no data, try to query IPv4 answers for synthesis
809         const uid_t uid = mClient->getUid();
810         if (startQueryLimiter(uid)) {
811             const char* host = mHost.starts_with('^') ? nullptr : mHost.c_str();
812             const char* service = mService.starts_with('^') ? nullptr : mService.c_str();
813             mHints->ai_family = AF_INET;
814             // Don't need to do freeaddrinfo(res) before starting new DNS lookup because previous
815             // DNS lookup is failed with error EAI_NODATA.
816             *rv = resolv_getaddrinfo(host, service, mHints.get(), &mNetContext, res, event);
817             endQueryLimiter(uid);
818             if (*rv) {
819                 *rv = EAI_NODATA;  // return original error code
820                 return;
821             }
822         } else {
823             LOG(ERROR) << __func__ << ": from UID " << uid << ", max concurrent queries reached";
824             return;
825         }
826     }
827 
828     if (!synthesizeNat64PrefixWithARecord(prefix, res, unspecWantedButNoIPv6, &mNetContext)) {
829         if (ipv6WantedButNoData) {
830             // If caller wants IPv6 answers but no data and failed to synthesize IPv6 answers,
831             // don't return the IPv4 answers.
832             *rv = EAI_NODATA;  // return original error code
833             if (*res) {
834                 freeaddrinfo(*res);
835                 *res = nullptr;
836             }
837         }
838     }
839 }
840 
run()841 void DnsProxyListener::GetAddrInfoHandler::run() {
842     LOG(INFO) << "GetAddrInfoHandler::run: {" << mNetContext.toString() << "}";
843 
844     addrinfo* result = nullptr;
845     Stopwatch s;
846     maybeFixupNetContext(&mNetContext, mClient->getPid());
847     const uid_t uid = mClient->getUid();
848     int32_t rv = 0;
849     NetworkDnsEventReported event;
850     initDnsEvent(&event, mNetContext);
851     if (startQueryLimiter(uid)) {
852         const char* host = mHost.starts_with('^') ? nullptr : mHost.c_str();
853         const char* service = mService.starts_with('^') ? nullptr : mService.c_str();
854         if (evaluate_domain_name(mNetContext, host)) {
855             rv = resolv_getaddrinfo(host, service, mHints.get(), &mNetContext, &result, &event);
856         } else {
857             rv = EAI_SYSTEM;
858         }
859         endQueryLimiter(uid);
860     } else {
861         // Note that this error code is currently not passed down to the client.
862         // android_getaddrinfo_proxy() returns EAI_NODATA on any error.
863         rv = EAI_MEMORY;
864         LOG(ERROR) << "GetAddrInfoHandler::run: from UID " << uid
865                    << ", max concurrent queries reached";
866     }
867 
868     doDns64Synthesis(&rv, &result, &event);
869     const int32_t latencyUs = saturate_cast<int32_t>(s.timeTakenUs());
870     event.set_latency_micros(latencyUs);
871     event.set_event_type(EVENT_GETADDRINFO);
872     event.set_hints_ai_flags((mHints ? mHints->ai_flags : 0));
873 
874     bool success = true;
875     if (rv) {
876         // getaddrinfo failed
877         success = !mClient->sendBinaryMsg(ResponseCode::DnsProxyOperationFailed, &rv, sizeof(rv));
878     } else {
879         success = !mClient->sendCode(ResponseCode::DnsProxyQueryResult);
880         addrinfo* ai = result;
881         while (ai && success) {
882             success = sendBE32(mClient, 1) && sendaddrinfo(mClient, ai);
883             ai = ai->ai_next;
884         }
885         success = success && sendBE32(mClient, 0);
886     }
887 
888     if (!success) {
889         PLOG(WARNING) << "GetAddrInfoHandler::run: Error writing DNS result to client uid " << uid
890                       << " pid " << mClient->getPid();
891     }
892 
893     std::vector<std::string> ip_addrs;
894     const int total_ip_addr_count = extractGetAddrInfoAnswers(result, &ip_addrs);
895     reportDnsEvent(INetdEventListener::EVENT_GETADDRINFO, mNetContext, latencyUs, rv, event, mHost,
896                    ip_addrs, total_ip_addr_count);
897     freeaddrinfo(result);
898 }
899 
threadName()900 std::string DnsProxyListener::GetAddrInfoHandler::threadName() {
901     return makeThreadName(mNetContext.dns_netid, mClient->getUid());
902 }
903 
904 namespace {
905 
addIpAddrWithinLimit(std::vector<std::string> * ip_addrs,const sockaddr * addr,socklen_t addrlen)906 void addIpAddrWithinLimit(std::vector<std::string>* ip_addrs, const sockaddr* addr,
907                           socklen_t addrlen) {
908     // ipAddresses array is limited to first INetdEventListener::DNS_REPORTED_IP_ADDRESSES_LIMIT
909     // addresses for A and AAAA. Total count of addresses is provided, to be able to tell whether
910     // some addresses didn't get logged.
911     if (ip_addrs->size() < INetdEventListener::DNS_REPORTED_IP_ADDRESSES_LIMIT) {
912         char ip_addr[INET6_ADDRSTRLEN];
913         if (getnameinfo(addr, addrlen, ip_addr, sizeof(ip_addr), nullptr, 0, NI_NUMERICHOST) == 0) {
914             ip_addrs->push_back(std::string(ip_addr));
915         }
916     }
917 }
918 
919 }  // namespace
920 
GetAddrInfoCmd()921 DnsProxyListener::GetAddrInfoCmd::GetAddrInfoCmd() : FrameworkCommand("getaddrinfo") {}
922 
runCommand(SocketClient * cli,int argc,char ** argv)923 int DnsProxyListener::GetAddrInfoCmd::runCommand(SocketClient* cli, int argc, char** argv) {
924     logArguments(argc, argv);
925 
926     int ai_flags = 0;
927     int ai_family = 0;
928     int ai_socktype = 0;
929     int ai_protocol = 0;
930     unsigned netId = 0;
931     std::string strErr = "GetAddrInfoCmd::runCommand: ";
932 
933     if (argc != 8) {
934         strErr = strErr + "invalid number of arguments: " + std::to_string(argc);
935         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, 0, NULL);
936     }
937 
938     const std::string name = argv[1];
939     const std::string service = argv[2];
940     if (!ParseInt(argv[3], &ai_flags))
941         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, argc, argv);
942     if (!ParseInt(argv[4], &ai_family))
943         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, argc, argv);
944     if (!ParseInt(argv[5], &ai_socktype))
945         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, argc, argv);
946     if (!ParseInt(argv[6], &ai_protocol))
947         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, argc, argv);
948     if (!ParseUint(argv[7], &netId))
949         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, argc, argv);
950 
951     const bool useLocalNameservers = checkAndClearUseLocalNameserversFlag(&netId);
952     const uid_t uid = cli->getUid();
953 
954     android_net_context netcontext;
955     gResNetdCallbacks.get_network_context(netId, uid, &netcontext);
956 
957     if (useLocalNameservers) {
958         netcontext.flags |= NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS;
959     }
960 
961     std::unique_ptr<addrinfo> hints;
962     if (ai_flags != -1 || ai_family != -1 || ai_socktype != -1 || ai_protocol != -1) {
963         hints.reset((addrinfo*)calloc(1, sizeof(addrinfo)));
964         hints->ai_flags = ai_flags;
965         hints->ai_family = ai_family;
966         hints->ai_socktype = ai_socktype;
967         hints->ai_protocol = ai_protocol;
968     }
969 
970     (new GetAddrInfoHandler(cli, name, service, std::move(hints), netcontext))->spawn();
971     return 0;
972 }
973 
974 /*******************************************************
975  *                  ResNSendCommand                    *
976  *******************************************************/
ResNSendCommand()977 DnsProxyListener::ResNSendCommand::ResNSendCommand() : FrameworkCommand("resnsend") {}
978 
runCommand(SocketClient * cli,int argc,char ** argv)979 int DnsProxyListener::ResNSendCommand::runCommand(SocketClient* cli, int argc, char** argv) {
980     logArguments(argc, argv);
981 
982     const uid_t uid = cli->getUid();
983     if (argc != 4) {
984         LOG(WARNING) << "ResNSendCommand::runCommand: resnsend: from UID " << uid
985                      << ", invalid number of arguments to resnsend: " << argc;
986         sendBE32(cli, -EINVAL);
987         return -1;
988     }
989 
990     unsigned netId;
991     if (!ParseUint(argv[1], &netId)) {
992         LOG(WARNING) << "ResNSendCommand::runCommand: resnsend: from UID " << uid
993                      << ", invalid netId";
994         sendBE32(cli, -EINVAL);
995         return -1;
996     }
997 
998     uint32_t flags;
999     if (!ParseUint(argv[2], &flags)) {
1000         LOG(WARNING) << "ResNSendCommand::runCommand: resnsend: from UID " << uid
1001                      << ", invalid flags";
1002         sendBE32(cli, -EINVAL);
1003         return -1;
1004     }
1005 
1006     const bool useLocalNameservers = checkAndClearUseLocalNameserversFlag(&netId);
1007 
1008     android_net_context netcontext;
1009     gResNetdCallbacks.get_network_context(netId, uid, &netcontext);
1010 
1011     if (useLocalNameservers) {
1012         netcontext.flags |= NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS;
1013     }
1014 
1015     (new ResNSendHandler(cli, argv[3], flags, netcontext))->spawn();
1016     return 0;
1017 }
1018 
ResNSendHandler(SocketClient * c,std::string msg,uint32_t flags,const android_net_context & netcontext)1019 DnsProxyListener::ResNSendHandler::ResNSendHandler(SocketClient* c, std::string msg, uint32_t flags,
1020                                                    const android_net_context& netcontext)
1021     : Handler(c), mMsg(std::move(msg)), mFlags(flags), mNetContext(netcontext) {}
1022 
run()1023 void DnsProxyListener::ResNSendHandler::run() {
1024     LOG(INFO) << "ResNSendHandler::run: " << mFlags << " / {" << mNetContext.toString() << "}";
1025 
1026     Stopwatch s;
1027     maybeFixupNetContext(&mNetContext, mClient->getPid());
1028 
1029     // Decode
1030     std::vector<uint8_t> msg(MAXPACKET, 0);
1031 
1032     // Max length of mMsg is less than 1024 since the CMD_BUF_SIZE in FrameworkListener is 1024
1033     int msgLen = b64_pton(mMsg.c_str(), msg.data(), MAXPACKET);
1034     if (msgLen == -1) {
1035         // Decode fail
1036         sendBE32(mClient, -EILSEQ);
1037         return;
1038     }
1039 
1040     const uid_t uid = mClient->getUid();
1041     int rr_type = 0;
1042     std::string rr_name;
1043     uint16_t original_query_id = 0;
1044 
1045     // TODO: Handle the case which is msg contains more than one query
1046     if (!parseQuery({msg.data(), msgLen}, &original_query_id, &rr_type, &rr_name) ||
1047         !setQueryId({msg.data(), msgLen}, arc4random_uniform(65536))) {
1048         // If the query couldn't be parsed, block the request.
1049         LOG(WARNING) << "ResNSendHandler::run: resnsend: from UID " << uid << ", invalid query";
1050         sendBE32(mClient, -EINVAL);
1051         return;
1052     }
1053 
1054     // Send DNS query
1055     std::vector<uint8_t> ansBuf(MAXPACKET, 0);
1056     int rcode = ns_r_noerror;
1057     int ansLen = -1;
1058     NetworkDnsEventReported event;
1059     initDnsEvent(&event, mNetContext);
1060     if (startQueryLimiter(uid)) {
1061         if (evaluate_domain_name(mNetContext, rr_name.c_str())) {
1062             ansLen = resolv_res_nsend(&mNetContext, {msg.data(), msgLen}, ansBuf, &rcode,
1063                                       static_cast<ResNsendFlags>(mFlags), &event);
1064         } else {
1065             ansLen = -EAI_SYSTEM;
1066         }
1067         endQueryLimiter(uid);
1068     } else {
1069         LOG(WARNING) << "ResNSendHandler::run: resnsend: from UID " << uid
1070                      << ", max concurrent queries reached";
1071         ansLen = -EBUSY;
1072     }
1073 
1074     const int32_t latencyUs = saturate_cast<int32_t>(s.timeTakenUs());
1075     event.set_latency_micros(latencyUs);
1076     event.set_event_type(EVENT_RES_NSEND);
1077     event.set_res_nsend_flags(static_cast<ResNsendFlags>(mFlags));
1078 
1079     // Fail, send -errno
1080     if (ansLen < 0) {
1081         if (!sendBE32(mClient, ansLen)) {
1082             PLOG(WARNING) << "ResNSendHandler::run: resnsend: failed to send errno to uid " << uid
1083                           << " pid " << mClient->getPid();
1084         }
1085         if (rr_type == ns_t_a || rr_type == ns_t_aaaa) {
1086             reportDnsEvent(INetdEventListener::EVENT_RES_NSEND, mNetContext, latencyUs,
1087                            resNSendToAiError(ansLen, rcode), event, rr_name);
1088         }
1089         return;
1090     }
1091 
1092     // Send rcode
1093     if (!sendBE32(mClient, rcode)) {
1094         PLOG(WARNING) << "ResNSendHandler::run: resnsend: failed to send rcode to uid " << uid
1095                       << " pid " << mClient->getPid();
1096         return;
1097     }
1098 
1099     // Restore query id
1100     if (!setQueryId({ansBuf.data(), ansLen}, original_query_id)) {
1101         LOG(WARNING) << "ResNSendHandler::run: resnsend: failed to restore query id";
1102         return;
1103     }
1104 
1105     // Send answer
1106     if (!sendLenAndData(mClient, ansLen, ansBuf.data())) {
1107         PLOG(WARNING) << "ResNSendHandler::run: resnsend: failed to send answer to uid " << uid
1108                       << " pid " << mClient->getPid();
1109         return;
1110     }
1111 
1112     if (rr_type == ns_t_a || rr_type == ns_t_aaaa) {
1113         std::vector<std::string> ip_addrs;
1114         const int total_ip_addr_count =
1115                 extractResNsendAnswers({ansBuf.data(), ansLen}, rr_type, &ip_addrs);
1116         reportDnsEvent(INetdEventListener::EVENT_RES_NSEND, mNetContext, latencyUs,
1117                        resNSendToAiError(ansLen, rcode), event, rr_name, ip_addrs,
1118                        total_ip_addr_count);
1119     }
1120 }
1121 
threadName()1122 std::string DnsProxyListener::ResNSendHandler::threadName() {
1123     return makeThreadName(mNetContext.dns_netid, mClient->getUid());
1124 }
1125 
1126 namespace {
1127 
sendCodeAndBe32(SocketClient * c,int code,int data)1128 bool sendCodeAndBe32(SocketClient* c, int code, int data) {
1129     return !c->sendCode(code) && sendBE32(c, data);
1130 }
1131 
1132 }  // namespace
1133 
1134 /*******************************************************
1135  *                  GetDnsNetId                        *
1136  *******************************************************/
GetDnsNetIdCommand()1137 DnsProxyListener::GetDnsNetIdCommand::GetDnsNetIdCommand() : FrameworkCommand("getdnsnetid") {}
1138 
runCommand(SocketClient * cli,int argc,char ** argv)1139 int DnsProxyListener::GetDnsNetIdCommand::runCommand(SocketClient* cli, int argc, char** argv) {
1140     logArguments(argc, argv);
1141 
1142     const uid_t uid = cli->getUid();
1143     if (argc != 2) {
1144         LOG(WARNING) << "GetDnsNetIdCommand::runCommand: getdnsnetid: from UID " << uid
1145                      << ", invalid number of arguments to getdnsnetid: " << argc;
1146         sendCodeAndBe32(cli, ResponseCode::DnsProxyQueryResult, -EINVAL);
1147         return -1;
1148     }
1149 
1150     unsigned netId;
1151     if (!ParseUint(argv[1], &netId)) {
1152         LOG(WARNING) << "GetDnsNetIdCommand::runCommand: getdnsnetid: from UID " << uid
1153                      << ", invalid netId";
1154         sendCodeAndBe32(cli, ResponseCode::DnsProxyQueryResult, -EINVAL);
1155         return -1;
1156     }
1157 
1158     const bool useLocalNameservers = checkAndClearUseLocalNameserversFlag(&netId);
1159     android_net_context netcontext;
1160     gResNetdCallbacks.get_network_context(netId, uid, &netcontext);
1161 
1162     if (useLocalNameservers) {
1163         netcontext.app_netid |= NETID_USE_LOCAL_NAMESERVERS;
1164     }
1165 
1166     const bool success =
1167             sendCodeAndBe32(cli, ResponseCode::DnsProxyQueryResult, netcontext.app_netid);
1168     if (!success) {
1169         PLOG(WARNING)
1170                 << "GetDnsNetIdCommand::runCommand: getdnsnetid: failed to send result to uid "
1171                 << uid << " pid " << cli->getPid();
1172     }
1173 
1174     return success ? 0 : -1;
1175 }
1176 
1177 /*******************************************************
1178  *                  GetHostByName                      *
1179  *******************************************************/
GetHostByNameCmd()1180 DnsProxyListener::GetHostByNameCmd::GetHostByNameCmd() : FrameworkCommand("gethostbyname") {}
1181 
runCommand(SocketClient * cli,int argc,char ** argv)1182 int DnsProxyListener::GetHostByNameCmd::runCommand(SocketClient* cli, int argc, char** argv) {
1183     logArguments(argc, argv);
1184 
1185     unsigned netId = 0;
1186     int af = 0;
1187     std::string strErr = "GetHostByNameCmd::runCommand: ";
1188 
1189     if (argc != 4) {
1190         strErr = strErr + "invalid number of arguments: " + std::to_string(argc);
1191         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, 0, NULL);
1192     }
1193 
1194     if (!ParseUint(argv[1], &netId))
1195         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, argc, argv);
1196     std::string name = argv[2];
1197     if (!ParseInt(argv[3], &af))
1198         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, argc, argv);
1199     uid_t uid = cli->getUid();
1200     const bool useLocalNameservers = checkAndClearUseLocalNameserversFlag(&netId);
1201 
1202     android_net_context netcontext;
1203     gResNetdCallbacks.get_network_context(netId, uid, &netcontext);
1204 
1205     if (useLocalNameservers) {
1206         netcontext.flags |= NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS;
1207     }
1208 
1209     (new GetHostByNameHandler(cli, name, af, netcontext))->spawn();
1210     return 0;
1211 }
1212 
GetHostByNameHandler(SocketClient * c,std::string name,int af,const android_net_context & netcontext)1213 DnsProxyListener::GetHostByNameHandler::GetHostByNameHandler(SocketClient* c, std::string name,
1214                                                              int af,
1215                                                              const android_net_context& netcontext)
1216     : Handler(c), mName(std::move(name)), mAf(af), mNetContext(netcontext) {}
1217 
doDns64Synthesis(int32_t * rv,hostent * hbuf,char * buf,size_t buflen,struct hostent ** hpp,NetworkDnsEventReported * event)1218 void DnsProxyListener::GetHostByNameHandler::doDns64Synthesis(int32_t* rv, hostent* hbuf, char* buf,
1219                                                               size_t buflen, struct hostent** hpp,
1220                                                               NetworkDnsEventReported* event) {
1221     // Don't have to consider family AF_UNSPEC case because gethostbyname{, 2} only supports
1222     // family AF_INET or AF_INET6.
1223     const bool ipv6WantedButNoData = (mAf == AF_INET6 && *rv == EAI_NODATA);
1224 
1225     if (!ipv6WantedButNoData) {
1226         return;
1227     }
1228 
1229     netdutils::IPPrefix prefix{};
1230     if (!getDns64Prefix(mNetContext.dns_netid, &prefix)) {
1231         return;
1232     }
1233 
1234     // If caller wants IPv6 answers but no data, try to query IPv4 answers for synthesis
1235     const uid_t uid = mClient->getUid();
1236     if (startQueryLimiter(uid)) {
1237         const char* name = mName.starts_with('^') ? nullptr : mName.c_str();
1238         *rv = resolv_gethostbyname(name, AF_INET, hbuf, buf, buflen, &mNetContext, hpp, event);
1239         endQueryLimiter(uid);
1240         if (*rv) {
1241             *rv = EAI_NODATA;  // return original error code
1242             return;
1243         }
1244     } else {
1245         LOG(ERROR) << __func__ << ": from UID " << uid << ", max concurrent queries reached";
1246         return;
1247     }
1248 
1249     if (!synthesizeNat64PrefixWithARecord(prefix, *hpp)) {
1250         // If caller wants IPv6 answers but no data and failed to synthesize IPv4 answers,
1251         // don't return the IPv4 answers.
1252         *hpp = nullptr;
1253     }
1254 }
1255 
run()1256 void DnsProxyListener::GetHostByNameHandler::run() {
1257     LOG(INFO) << "GetHostByNameHandler::run: {" << mNetContext.toString() << "}";
1258     Stopwatch s;
1259     maybeFixupNetContext(&mNetContext, mClient->getPid());
1260     const uid_t uid = mClient->getUid();
1261     hostent* hp = nullptr;
1262     hostent hbuf;
1263     char tmpbuf[MAXPACKET];
1264     int32_t rv = 0;
1265     NetworkDnsEventReported event;
1266     initDnsEvent(&event, mNetContext);
1267     if (startQueryLimiter(uid)) {
1268         const char* name = mName.starts_with('^') ? nullptr : mName.c_str();
1269         if (evaluate_domain_name(mNetContext, name)) {
1270             rv = resolv_gethostbyname(name, mAf, &hbuf, tmpbuf, sizeof tmpbuf, &mNetContext, &hp,
1271                                       &event);
1272         } else {
1273             rv = EAI_SYSTEM;
1274         }
1275         endQueryLimiter(uid);
1276     } else {
1277         rv = EAI_MEMORY;
1278         LOG(ERROR) << "GetHostByNameHandler::run: from UID " << uid
1279                    << ", max concurrent queries reached";
1280     }
1281 
1282     doDns64Synthesis(&rv, &hbuf, tmpbuf, sizeof tmpbuf, &hp, &event);
1283     const int32_t latencyUs = saturate_cast<int32_t>(s.timeTakenUs());
1284     event.set_latency_micros(latencyUs);
1285     event.set_event_type(EVENT_GETHOSTBYNAME);
1286 
1287     if (rv) {
1288         LOG(DEBUG) << "GetHostByNameHandler::run: result failed: " << gai_strerror(rv);
1289     }
1290 
1291     bool success = true;
1292     if (hp) {
1293         // hp is not nullptr iff. rv is 0.
1294         success = mClient->sendCode(ResponseCode::DnsProxyQueryResult) == 0;
1295         success &= sendhostent(mClient, hp);
1296     } else {
1297         success = mClient->sendBinaryMsg(ResponseCode::DnsProxyOperationFailed, nullptr, 0) == 0;
1298     }
1299 
1300     if (!success) {
1301         PLOG(WARNING) << "GetHostByNameHandler::run: Error writing DNS result to client uid " << uid
1302                       << " pid " << mClient->getPid();
1303     }
1304 
1305     std::vector<std::string> ip_addrs;
1306     const int total_ip_addr_count = extractGetHostByNameAnswers(hp, &ip_addrs);
1307     reportDnsEvent(INetdEventListener::EVENT_GETHOSTBYNAME, mNetContext, latencyUs, rv, event,
1308                    mName, ip_addrs, total_ip_addr_count);
1309 }
1310 
threadName()1311 std::string DnsProxyListener::GetHostByNameHandler::threadName() {
1312     return makeThreadName(mNetContext.dns_netid, mClient->getUid());
1313 }
1314 
1315 /*******************************************************
1316  *                  GetHostByAddr                      *
1317  *******************************************************/
GetHostByAddrCmd()1318 DnsProxyListener::GetHostByAddrCmd::GetHostByAddrCmd() : FrameworkCommand("gethostbyaddr") {}
1319 
runCommand(SocketClient * cli,int argc,char ** argv)1320 int DnsProxyListener::GetHostByAddrCmd::runCommand(SocketClient* cli, int argc, char** argv) {
1321     logArguments(argc, argv);
1322     int addrLen = 0;
1323     int addrFamily = 0;
1324     unsigned netId = 0;
1325     std::string strErr = "GetHostByAddrCmd::runCommand: ";
1326 
1327     if (argc != 5) {
1328         strErr = strErr + "invalid number of arguments: " + std::to_string(argc);
1329         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, 0, NULL);
1330     }
1331 
1332     char* addrStr = argv[1];
1333     if (!ParseInt(argv[2], &addrLen))
1334         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, argc, argv);
1335     if (!ParseInt(argv[3], &addrFamily))
1336         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, argc, argv);
1337     if (!ParseUint(argv[4], &netId))
1338         return HandleArgumentError(cli, ResponseCode::CommandParameterError, strErr, argc, argv);
1339     uid_t uid = cli->getUid();
1340     const bool useLocalNameservers = checkAndClearUseLocalNameserversFlag(&netId);
1341 
1342     in6_addr addr;
1343     errno = 0;
1344     int result = inet_pton(addrFamily, addrStr, &addr);
1345     if (result <= 0) {
1346         strErr = strErr + "inet_pton(\"" + addrStr + "\") failed " + strerror(errno);
1347         return HandleArgumentError(cli, ResponseCode::OperationFailed, strErr, 0, NULL);
1348     }
1349 
1350     android_net_context netcontext;
1351     gResNetdCallbacks.get_network_context(netId, uid, &netcontext);
1352 
1353     if (useLocalNameservers) {
1354         netcontext.flags |= NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS;
1355     }
1356 
1357     (new GetHostByAddrHandler(cli, addr, addrLen, addrFamily, netcontext))->spawn();
1358     return 0;
1359 }
1360 
GetHostByAddrHandler(SocketClient * c,in6_addr address,int addressLen,int addressFamily,const android_net_context & netcontext)1361 DnsProxyListener::GetHostByAddrHandler::GetHostByAddrHandler(SocketClient* c, in6_addr address,
1362                                                              int addressLen, int addressFamily,
1363                                                              const android_net_context& netcontext)
1364     : Handler(c),
1365       mAddress(address),
1366       mAddressLen(addressLen),
1367       mAddressFamily(addressFamily),
1368       mNetContext(netcontext) {}
1369 
doDns64ReverseLookup(hostent * hbuf,char * buf,size_t buflen,struct hostent ** hpp,NetworkDnsEventReported * event)1370 void DnsProxyListener::GetHostByAddrHandler::doDns64ReverseLookup(hostent* hbuf, char* buf,
1371                                                                   size_t buflen,
1372                                                                   struct hostent** hpp,
1373                                                                   NetworkDnsEventReported* event) {
1374     if (*hpp != nullptr || mAddressFamily != AF_INET6) {
1375         return;
1376     }
1377 
1378     netdutils::IPPrefix prefix{};
1379     if (!getDns64Prefix(mNetContext.dns_netid, &prefix)) {
1380         return;
1381     }
1382 
1383     if (!isValidNat64Prefix(prefix)) {
1384         return;
1385     }
1386 
1387     struct sockaddr_storage ss = netdutils::IPSockAddr(prefix.ip());
1388     struct sockaddr_in6* v6prefix = (struct sockaddr_in6*)&ss;
1389     struct in6_addr v6addr = mAddress;
1390     // Check if address has NAT64 prefix. Only /96 IPv6 NAT64 prefixes are supported
1391     if ((v6addr.s6_addr32[0] != v6prefix->sin6_addr.s6_addr32[0]) ||
1392         (v6addr.s6_addr32[1] != v6prefix->sin6_addr.s6_addr32[1]) ||
1393         (v6addr.s6_addr32[2] != v6prefix->sin6_addr.s6_addr32[2])) {
1394         return;
1395     }
1396 
1397     const uid_t uid = mClient->getUid();
1398     if (startQueryLimiter(uid)) {
1399         // Remove NAT64 prefix and do reverse DNS query
1400         struct in_addr v4addr = {.s_addr = v6addr.s6_addr32[3]};
1401         resolv_gethostbyaddr(&v4addr, sizeof(v4addr), AF_INET, hbuf, buf, buflen, &mNetContext, hpp,
1402                              event);
1403         endQueryLimiter(uid);
1404         if (*hpp) {
1405             // Replace IPv4 address with original queried IPv6 address in place. The space has
1406             // reserved by dns_gethtbyaddr() and netbsd_gethostent_r() in
1407             // system/netd/resolv/gethnamaddr.cpp.
1408             // Note that resolv_gethostbyaddr() returns only one entry in result.
1409             memcpy((*hpp)->h_addr_list[0], &v6addr, sizeof(v6addr));
1410             (*hpp)->h_addrtype = AF_INET6;
1411             (*hpp)->h_length = sizeof(struct in6_addr);
1412         }
1413     } else {
1414         LOG(ERROR) << __func__ << ": from UID " << uid << ", max concurrent queries reached";
1415     }
1416 }
1417 
run()1418 void DnsProxyListener::GetHostByAddrHandler::run() {
1419     LOG(INFO) << "GetHostByAddrHandler::run: {" << mNetContext.toString() << "}";
1420     Stopwatch s;
1421     maybeFixupNetContext(&mNetContext, mClient->getPid());
1422     const uid_t uid = mClient->getUid();
1423     hostent* hp = nullptr;
1424     hostent hbuf;
1425     char tmpbuf[MAXPACKET];
1426     int32_t rv = 0;
1427     NetworkDnsEventReported event;
1428     initDnsEvent(&event, mNetContext);
1429     if (startQueryLimiter(uid)) {
1430         // From Android U, evaluate_domain_name() is not only for OEM customization, but also tells
1431         // DNS resolver whether the UID can send DNS on the specified network. The function needs
1432         // to be called even when there is no domain name to evaluate (GetHostByAddr). This is
1433         // applied on U+ only so that the behavior won’t change on T- OEM devices.
1434         // TODO: pass the actual name into evaluate_domain_name, e.g., 238.26.217.172.in-addr.arpa
1435         //       when the lookup address is 172.217.26.238.
1436         if (isAtLeastU() && !evaluate_domain_name(mNetContext, nullptr)) {
1437             rv = EAI_SYSTEM;
1438         } else {
1439             rv = resolv_gethostbyaddr(&mAddress, mAddressLen, mAddressFamily, &hbuf, tmpbuf,
1440                                       sizeof tmpbuf, &mNetContext, &hp, &event);
1441         }
1442         endQueryLimiter(uid);
1443     } else {
1444         rv = EAI_MEMORY;
1445         LOG(ERROR) << "GetHostByAddrHandler::run: from UID " << uid
1446                    << ", max concurrent queries reached";
1447     }
1448 
1449     doDns64ReverseLookup(&hbuf, tmpbuf, sizeof tmpbuf, &hp, &event);
1450     const int32_t latencyUs = saturate_cast<int32_t>(s.timeTakenUs());
1451     event.set_latency_micros(latencyUs);
1452     event.set_event_type(EVENT_GETHOSTBYADDR);
1453 
1454     if (rv) {
1455         LOG(DEBUG) << "GetHostByAddrHandler::run: result failed: " << gai_strerror(rv);
1456     }
1457 
1458     bool success = true;
1459     if (hp) {
1460         success = mClient->sendCode(ResponseCode::DnsProxyQueryResult) == 0;
1461         success &= sendhostent(mClient, hp);
1462     } else {
1463         success = mClient->sendBinaryMsg(ResponseCode::DnsProxyOperationFailed, nullptr, 0) == 0;
1464     }
1465 
1466     if (!success) {
1467         PLOG(WARNING) << "GetHostByAddrHandler::run: Error writing DNS result to client uid " << uid
1468                       << " pid " << mClient->getPid();
1469     }
1470 
1471     reportDnsEvent(INetdEventListener::EVENT_GETHOSTBYADDR, mNetContext, latencyUs, rv, event,
1472                    (hp && hp->h_name) ? hp->h_name : "null", {}, 0);
1473 }
1474 
threadName()1475 std::string DnsProxyListener::GetHostByAddrHandler::threadName() {
1476     return makeThreadName(mNetContext.dns_netid, mClient->getUid());
1477 }
1478 
1479 }  // namespace net
1480 }  // namespace android
1481