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 <arpa/inet.h>
18 #include <dirent.h>
19 #include <errno.h>
20 #include <linux/if.h>
21 #include <math.h>
22 #include <netdb.h>
23 #include <netinet/in.h>
24 #include <stdlib.h>
25 #include <sys/socket.h>
26 #include <sys/types.h>
27 #include <string.h>
28 #include <pthread.h>
29 #include <resolv_netid.h>
30 #include <net/if.h>
31 
32 #define LOG_TAG "DnsProxyListener"
33 #define DBG 0
34 #define VDBG 0
35 
36 #include <chrono>
37 
38 #include <cutils/log.h>
39 #include <binder/IServiceManager.h>
40 #include <utils/String16.h>
41 #include <sysutils/SocketClient.h>
42 
43 #include "Fwmark.h"
44 #include "DnsProxyListener.h"
45 #include "NetdConstants.h"
46 #include "NetworkController.h"
47 #include "ResponseCode.h"
48 #include "android/net/metrics/IDnsEventListener.h"
49 
50 using android::String16;
51 using android::interface_cast;
52 using android::net::metrics::IDnsEventListener;
53 
DnsProxyListener(const NetworkController * netCtrl)54 DnsProxyListener::DnsProxyListener(const NetworkController* netCtrl) :
55         FrameworkListener("dnsproxyd"), mNetCtrl(netCtrl) {
56     registerCmd(new GetAddrInfoCmd(this));
57     registerCmd(new GetHostByAddrCmd(this));
58     registerCmd(new GetHostByNameCmd(this));
59 }
60 
GetAddrInfoHandler(SocketClient * c,char * host,char * service,struct addrinfo * hints,const struct android_net_context & netcontext,const android::sp<android::net::metrics::IDnsEventListener> & dnsEventListener)61 DnsProxyListener::GetAddrInfoHandler::GetAddrInfoHandler(
62         SocketClient *c, char* host, char* service, struct addrinfo* hints,
63         const struct android_net_context& netcontext,
64         const android::sp<android::net::metrics::IDnsEventListener>& dnsEventListener)
65         : mClient(c),
66           mHost(host),
67           mService(service),
68           mHints(hints),
69           mNetContext(netcontext),
70           mDnsEventListener(dnsEventListener) {
71 }
72 
~GetAddrInfoHandler()73 DnsProxyListener::GetAddrInfoHandler::~GetAddrInfoHandler() {
74     free(mHost);
75     free(mService);
76     free(mHints);
77 }
78 
start()79 void DnsProxyListener::GetAddrInfoHandler::start() {
80     pthread_t thread;
81     pthread_create(&thread, NULL,
82                    DnsProxyListener::GetAddrInfoHandler::threadStart, this);
83     pthread_detach(thread);
84 }
85 
threadStart(void * obj)86 void* DnsProxyListener::GetAddrInfoHandler::threadStart(void* obj) {
87     GetAddrInfoHandler* handler = reinterpret_cast<GetAddrInfoHandler*>(obj);
88     handler->run();
89     delete handler;
90     pthread_exit(NULL);
91     return NULL;
92 }
93 
getDnsEventListener()94 android::sp<IDnsEventListener> DnsProxyListener::getDnsEventListener() {
95     if (mDnsEventListener == nullptr) {
96         // Use checkService instead of getService because getService waits for 5 seconds for the
97         // service to become available. The DNS resolver inside netd is started much earlier in the
98         // boot sequence than the framework DNS listener, and we don't want to delay all DNS lookups
99         // for 5 seconds until the DNS listener starts up.
100         android::sp<android::IBinder> b = android::defaultServiceManager()->checkService(
101                 android::String16("dns_listener"));
102         if (b != nullptr) {
103             mDnsEventListener = interface_cast<IDnsEventListener>(b);
104         }
105     }
106     // If the DNS listener service is dead, the binder call will just return an error, which should
107     // be fine because the only impact is that we can't log DNS events. In any case, this should
108     // only happen if the system server is going down, which means it will shortly be taking us down
109     // with it.
110     return mDnsEventListener;
111 }
112 
sendBE32(SocketClient * c,uint32_t data)113 static bool sendBE32(SocketClient* c, uint32_t data) {
114     uint32_t be_data = htonl(data);
115     return c->sendData(&be_data, sizeof(be_data)) == 0;
116 }
117 
118 // Sends 4 bytes of big-endian length, followed by the data.
119 // Returns true on success.
sendLenAndData(SocketClient * c,const int len,const void * data)120 static bool sendLenAndData(SocketClient* c, const int len, const void* data) {
121     return sendBE32(c, len) && (len == 0 || c->sendData(data, len) == 0);
122 }
123 
124 // Returns true on success
sendhostent(SocketClient * c,struct hostent * hp)125 static bool sendhostent(SocketClient *c, struct hostent *hp) {
126     bool success = true;
127     int i;
128     if (hp->h_name != NULL) {
129         success &= sendLenAndData(c, strlen(hp->h_name)+1, hp->h_name);
130     } else {
131         success &= sendLenAndData(c, 0, "") == 0;
132     }
133 
134     for (i=0; hp->h_aliases[i] != NULL; i++) {
135         success &= sendLenAndData(c, strlen(hp->h_aliases[i])+1, hp->h_aliases[i]);
136     }
137     success &= sendLenAndData(c, 0, ""); // null to indicate we're done
138 
139     uint32_t buf = htonl(hp->h_addrtype);
140     success &= c->sendData(&buf, sizeof(buf)) == 0;
141 
142     buf = htonl(hp->h_length);
143     success &= c->sendData(&buf, sizeof(buf)) == 0;
144 
145     for (i=0; hp->h_addr_list[i] != NULL; i++) {
146         success &= sendLenAndData(c, 16, hp->h_addr_list[i]);
147     }
148     success &= sendLenAndData(c, 0, ""); // null to indicate we're done
149     return success;
150 }
151 
sendaddrinfo(SocketClient * c,struct addrinfo * ai)152 static bool sendaddrinfo(SocketClient* c, struct addrinfo* ai) {
153     // struct addrinfo {
154     //      int     ai_flags;       /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
155     //      int     ai_family;      /* PF_xxx */
156     //      int     ai_socktype;    /* SOCK_xxx */
157     //      int     ai_protocol;    /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
158     //      socklen_t ai_addrlen;   /* length of ai_addr */
159     //      char    *ai_canonname;  /* canonical name for hostname */
160     //      struct  sockaddr *ai_addr;      /* binary address */
161     //      struct  addrinfo *ai_next;      /* next structure in linked list */
162     // };
163 
164     // Write the struct piece by piece because we might be a 64-bit netd
165     // talking to a 32-bit process.
166     bool success =
167             sendBE32(c, ai->ai_flags) &&
168             sendBE32(c, ai->ai_family) &&
169             sendBE32(c, ai->ai_socktype) &&
170             sendBE32(c, ai->ai_protocol);
171     if (!success) {
172         return false;
173     }
174 
175     // ai_addrlen and ai_addr.
176     if (!sendLenAndData(c, ai->ai_addrlen, ai->ai_addr)) {
177         return false;
178     }
179 
180     // strlen(ai_canonname) and ai_canonname.
181     if (!sendLenAndData(c, ai->ai_canonname ? strlen(ai->ai_canonname) + 1 : 0, ai->ai_canonname)) {
182         return false;
183     }
184 
185     return true;
186 }
187 
run()188 void DnsProxyListener::GetAddrInfoHandler::run() {
189     if (DBG) {
190         ALOGD("GetAddrInfoHandler, now for %s / %s / {%u,%u,%u,%u,%u}", mHost, mService,
191                 mNetContext.app_netid, mNetContext.app_mark,
192                 mNetContext.dns_netid, mNetContext.dns_mark,
193                 mNetContext.uid);
194     }
195 
196     struct addrinfo* result = NULL;
197     Stopwatch s;
198     uint32_t rv = android_getaddrinfofornetcontext(mHost, mService, mHints, &mNetContext, &result);
199     const int latencyMs = lround(s.timeTaken());
200 
201     if (rv) {
202         // getaddrinfo failed
203         mClient->sendBinaryMsg(ResponseCode::DnsProxyOperationFailed, &rv, sizeof(rv));
204     } else {
205         bool success = !mClient->sendCode(ResponseCode::DnsProxyQueryResult);
206         struct addrinfo* ai = result;
207         while (ai && success) {
208             success = sendBE32(mClient, 1) && sendaddrinfo(mClient, ai);
209             ai = ai->ai_next;
210         }
211         success = success && sendBE32(mClient, 0);
212         if (!success) {
213             ALOGW("Error writing DNS result to client");
214         }
215     }
216     if (result) {
217         freeaddrinfo(result);
218     }
219     mClient->decRef();
220     if (mDnsEventListener != nullptr) {
221         mDnsEventListener->onDnsEvent(mNetContext.dns_netid, IDnsEventListener::EVENT_GETADDRINFO,
222                                       (int32_t) rv, latencyMs);
223     }
224 }
225 
GetAddrInfoCmd(DnsProxyListener * dnsProxyListener)226 DnsProxyListener::GetAddrInfoCmd::GetAddrInfoCmd(DnsProxyListener* dnsProxyListener) :
227     NetdCommand("getaddrinfo"),
228     mDnsProxyListener(dnsProxyListener) {
229 }
230 
runCommand(SocketClient * cli,int argc,char ** argv)231 int DnsProxyListener::GetAddrInfoCmd::runCommand(SocketClient *cli,
232                                             int argc, char **argv) {
233     if (DBG) {
234         for (int i = 0; i < argc; i++) {
235             ALOGD("argv[%i]=%s", i, argv[i]);
236         }
237     }
238     if (argc != 8) {
239         char* msg = NULL;
240         asprintf( &msg, "Invalid number of arguments to getaddrinfo: %i", argc);
241         ALOGW("%s", msg);
242         cli->sendMsg(ResponseCode::CommandParameterError, msg, false);
243         free(msg);
244         return -1;
245     }
246 
247     char* name = argv[1];
248     if (strcmp("^", name) == 0) {
249         name = NULL;
250     } else {
251         name = strdup(name);
252     }
253 
254     char* service = argv[2];
255     if (strcmp("^", service) == 0) {
256         service = NULL;
257     } else {
258         service = strdup(service);
259     }
260 
261     struct addrinfo* hints = NULL;
262     int ai_flags = atoi(argv[3]);
263     int ai_family = atoi(argv[4]);
264     int ai_socktype = atoi(argv[5]);
265     int ai_protocol = atoi(argv[6]);
266     unsigned netId = strtoul(argv[7], NULL, 10);
267     uid_t uid = cli->getUid();
268 
269     struct android_net_context netcontext;
270     mDnsProxyListener->mNetCtrl->getNetworkContext(netId, uid, &netcontext);
271 
272     if (ai_flags != -1 || ai_family != -1 ||
273         ai_socktype != -1 || ai_protocol != -1) {
274         hints = (struct addrinfo*) calloc(1, sizeof(struct addrinfo));
275         hints->ai_flags = ai_flags;
276         hints->ai_family = ai_family;
277         hints->ai_socktype = ai_socktype;
278         hints->ai_protocol = ai_protocol;
279     }
280 
281     if (DBG) {
282         ALOGD("GetAddrInfoHandler for %s / %s / {%u,%u,%u,%u,%u}",
283              name ? name : "[nullhost]",
284              service ? service : "[nullservice]",
285              netcontext.app_netid, netcontext.app_mark,
286              netcontext.dns_netid, netcontext.dns_mark,
287              netcontext.uid);
288     }
289 
290     cli->incRef();
291     DnsProxyListener::GetAddrInfoHandler* handler =
292             new DnsProxyListener::GetAddrInfoHandler(cli, name, service, hints, netcontext,
293                                                      mDnsProxyListener->getDnsEventListener());
294     handler->start();
295 
296     return 0;
297 }
298 
299 /*******************************************************
300  *                  GetHostByName                      *
301  *******************************************************/
GetHostByNameCmd(DnsProxyListener * dnsProxyListener)302 DnsProxyListener::GetHostByNameCmd::GetHostByNameCmd(DnsProxyListener* dnsProxyListener) :
303       NetdCommand("gethostbyname"),
304       mDnsProxyListener(dnsProxyListener) {
305 }
306 
runCommand(SocketClient * cli,int argc,char ** argv)307 int DnsProxyListener::GetHostByNameCmd::runCommand(SocketClient *cli,
308                                             int argc, char **argv) {
309     if (DBG) {
310         for (int i = 0; i < argc; i++) {
311             ALOGD("argv[%i]=%s", i, argv[i]);
312         }
313     }
314     if (argc != 4) {
315         char* msg = NULL;
316         asprintf(&msg, "Invalid number of arguments to gethostbyname: %i", argc);
317         ALOGW("%s", msg);
318         cli->sendMsg(ResponseCode::CommandParameterError, msg, false);
319         free(msg);
320         return -1;
321     }
322 
323     uid_t uid = cli->getUid();
324     unsigned netId = strtoul(argv[1], NULL, 10);
325     char* name = argv[2];
326     int af = atoi(argv[3]);
327 
328     if (strcmp(name, "^") == 0) {
329         name = NULL;
330     } else {
331         name = strdup(name);
332     }
333 
334     uint32_t mark = mDnsProxyListener->mNetCtrl->getNetworkForDns(&netId, uid);
335 
336     cli->incRef();
337     DnsProxyListener::GetHostByNameHandler* handler =
338             new DnsProxyListener::GetHostByNameHandler(cli, name, af, netId, mark,
339                                                        mDnsProxyListener->getDnsEventListener());
340     handler->start();
341 
342     return 0;
343 }
344 
GetHostByNameHandler(SocketClient * c,char * name,int af,unsigned netId,uint32_t mark,const android::sp<android::net::metrics::IDnsEventListener> & dnsEventListener)345 DnsProxyListener::GetHostByNameHandler::GetHostByNameHandler(
346         SocketClient* c, char* name, int af, unsigned netId, uint32_t mark,
347         const android::sp<android::net::metrics::IDnsEventListener>& dnsEventListener)
348         : mClient(c),
349           mName(name),
350           mAf(af),
351           mNetId(netId),
352           mMark(mark),
353           mDnsEventListener(dnsEventListener) {
354 }
355 
~GetHostByNameHandler()356 DnsProxyListener::GetHostByNameHandler::~GetHostByNameHandler() {
357     free(mName);
358 }
359 
start()360 void DnsProxyListener::GetHostByNameHandler::start() {
361     pthread_t thread;
362     pthread_create(&thread, NULL,
363             DnsProxyListener::GetHostByNameHandler::threadStart, this);
364     pthread_detach(thread);
365 }
366 
threadStart(void * obj)367 void* DnsProxyListener::GetHostByNameHandler::threadStart(void* obj) {
368     GetHostByNameHandler* handler = reinterpret_cast<GetHostByNameHandler*>(obj);
369     handler->run();
370     delete handler;
371     pthread_exit(NULL);
372     return NULL;
373 }
374 
run()375 void DnsProxyListener::GetHostByNameHandler::run() {
376     if (DBG) {
377         ALOGD("DnsProxyListener::GetHostByNameHandler::run\n");
378     }
379 
380     Stopwatch s;
381     struct hostent* hp = android_gethostbynamefornet(mName, mAf, mNetId, mMark);
382     const int latencyMs = lround(s.timeTaken());
383 
384     if (DBG) {
385         ALOGD("GetHostByNameHandler::run gethostbyname errno: %s hp->h_name = %s, name_len = %zu\n",
386                 hp ? "success" : strerror(errno),
387                 (hp && hp->h_name) ? hp->h_name : "null",
388                 (hp && hp->h_name) ? strlen(hp->h_name) + 1 : 0);
389     }
390 
391     bool success = true;
392     if (hp) {
393         success = mClient->sendCode(ResponseCode::DnsProxyQueryResult) == 0;
394         success &= sendhostent(mClient, hp);
395     } else {
396         success = mClient->sendBinaryMsg(ResponseCode::DnsProxyOperationFailed, NULL, 0) == 0;
397     }
398 
399     if (!success) {
400         ALOGW("GetHostByNameHandler: Error writing DNS result to client\n");
401     }
402     mClient->decRef();
403 
404     if (mDnsEventListener != nullptr) {
405         mDnsEventListener->onDnsEvent(mNetId, IDnsEventListener::EVENT_GETHOSTBYNAME,
406                                       h_errno, latencyMs);
407     }
408 }
409 
410 
411 /*******************************************************
412  *                  GetHostByAddr                      *
413  *******************************************************/
GetHostByAddrCmd(const DnsProxyListener * dnsProxyListener)414 DnsProxyListener::GetHostByAddrCmd::GetHostByAddrCmd(const DnsProxyListener* dnsProxyListener) :
415         NetdCommand("gethostbyaddr"),
416         mDnsProxyListener(dnsProxyListener) {
417 }
418 
runCommand(SocketClient * cli,int argc,char ** argv)419 int DnsProxyListener::GetHostByAddrCmd::runCommand(SocketClient *cli,
420                                             int argc, char **argv) {
421     if (DBG) {
422         for (int i = 0; i < argc; i++) {
423             ALOGD("argv[%i]=%s", i, argv[i]);
424         }
425     }
426     if (argc != 5) {
427         char* msg = NULL;
428         asprintf(&msg, "Invalid number of arguments to gethostbyaddr: %i", argc);
429         ALOGW("%s", msg);
430         cli->sendMsg(ResponseCode::CommandParameterError, msg, false);
431         free(msg);
432         return -1;
433     }
434 
435     char* addrStr = argv[1];
436     int addrLen = atoi(argv[2]);
437     int addrFamily = atoi(argv[3]);
438     uid_t uid = cli->getUid();
439     unsigned netId = strtoul(argv[4], NULL, 10);
440 
441     void* addr = malloc(sizeof(struct in6_addr));
442     errno = 0;
443     int result = inet_pton(addrFamily, addrStr, addr);
444     if (result <= 0) {
445         char* msg = NULL;
446         asprintf(&msg, "inet_pton(\"%s\") failed %s", addrStr, strerror(errno));
447         ALOGW("%s", msg);
448         cli->sendMsg(ResponseCode::OperationFailed, msg, false);
449         free(addr);
450         free(msg);
451         return -1;
452     }
453 
454     uint32_t mark = mDnsProxyListener->mNetCtrl->getNetworkForDns(&netId, uid);
455 
456     cli->incRef();
457     DnsProxyListener::GetHostByAddrHandler* handler =
458             new DnsProxyListener::GetHostByAddrHandler(cli, addr, addrLen, addrFamily, netId, mark);
459     handler->start();
460 
461     return 0;
462 }
463 
GetHostByAddrHandler(SocketClient * c,void * address,int addressLen,int addressFamily,unsigned netId,uint32_t mark)464 DnsProxyListener::GetHostByAddrHandler::GetHostByAddrHandler(SocketClient* c,
465                                                              void* address,
466                                                              int   addressLen,
467                                                              int   addressFamily,
468                                                              unsigned netId,
469                                                              uint32_t mark)
470         : mClient(c),
471           mAddress(address),
472           mAddressLen(addressLen),
473           mAddressFamily(addressFamily),
474           mNetId(netId),
475           mMark(mark) {
476 }
477 
~GetHostByAddrHandler()478 DnsProxyListener::GetHostByAddrHandler::~GetHostByAddrHandler() {
479     free(mAddress);
480 }
481 
start()482 void DnsProxyListener::GetHostByAddrHandler::start() {
483     pthread_t thread;
484     pthread_create(&thread, NULL,
485                    DnsProxyListener::GetHostByAddrHandler::threadStart, this);
486     pthread_detach(thread);
487 }
488 
threadStart(void * obj)489 void* DnsProxyListener::GetHostByAddrHandler::threadStart(void* obj) {
490     GetHostByAddrHandler* handler = reinterpret_cast<GetHostByAddrHandler*>(obj);
491     handler->run();
492     delete handler;
493     pthread_exit(NULL);
494     return NULL;
495 }
496 
run()497 void DnsProxyListener::GetHostByAddrHandler::run() {
498     if (DBG) {
499         ALOGD("DnsProxyListener::GetHostByAddrHandler::run\n");
500     }
501     struct hostent* hp;
502 
503     // NOTE gethostbyaddr should take a void* but bionic thinks it should be char*
504     hp = android_gethostbyaddrfornet((char*)mAddress, mAddressLen, mAddressFamily, mNetId, mMark);
505 
506     if (DBG) {
507         ALOGD("GetHostByAddrHandler::run gethostbyaddr errno: %s hp->h_name = %s, name_len = %zu\n",
508                 hp ? "success" : strerror(errno),
509                 (hp && hp->h_name) ? hp->h_name : "null",
510                 (hp && hp->h_name) ? strlen(hp->h_name) + 1 : 0);
511     }
512 
513     bool success = true;
514     if (hp) {
515         success = mClient->sendCode(ResponseCode::DnsProxyQueryResult) == 0;
516         success &= sendhostent(mClient, hp);
517     } else {
518         success = mClient->sendBinaryMsg(ResponseCode::DnsProxyOperationFailed, NULL, 0) == 0;
519     }
520 
521     if (!success) {
522         ALOGW("GetHostByAddrHandler: Error writing DNS result to client\n");
523     }
524     mClient->decRef();
525 }
526