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