]> arthur.barton.de Git - ngircd-alex.git/blob - src/ngircd/resolve.c
Do reverse lookups using the AF of the incoming connection
[ngircd-alex.git] / src / ngircd / resolve.c
1 /*
2  * ngIRCd -- The Next Generation IRC Daemon
3  * Copyright (c)2001-2009 by Alexander Barton (alex@barton.de)
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  * Please read the file COPYING, README and AUTHORS for more information.
10  */
11
12 #define RESOLVER_TIMEOUT (Conf_PongTimeout*3)/4
13
14 #include "portab.h"
15
16 /**
17  * @file
18  * Asynchronous resolver
19  */
20
21 #include "imp.h"
22 #include <assert.h>
23 #include <errno.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <sys/socket.h>
28 #include <netinet/in.h>
29 #include <netdb.h>
30 #include <signal.h>
31
32 #ifdef IDENTAUTH
33 #ifdef HAVE_IDENT_H
34 #include <ident.h>
35 #endif
36 #endif
37
38 #include "array.h"
39 #include "conn.h"
40 #include "conf.h"
41 #include "defines.h"
42 #include "log.h"
43 #include "ng_ipaddr.h"
44
45 #include "exp.h"
46 #include "resolve.h"
47 #include "io.h"
48
49
50 static void Do_ResolveAddr PARAMS(( const ng_ipaddr_t *Addr, int Sock, int w_fd ));
51 static void Do_ResolveName PARAMS(( const char *Host, int w_fd ));
52
53 #ifdef WANT_IPV6
54 extern bool Conf_ConnectIPv4;
55 extern bool Conf_ConnectIPv6;
56 #endif
57
58
59 /**
60  * Resolve IP (asynchronous!).
61  */
62 GLOBAL bool
63 Resolve_Addr(PROC_STAT * s, const ng_ipaddr_t *Addr, int identsock,
64              void (*cbfunc) (int, short))
65 {
66         int pipefd[2];
67         pid_t pid;
68
69         assert(s != NULL);
70
71         pid = Proc_Fork(s, pipefd, cbfunc, RESOLVER_TIMEOUT);
72         if (pid > 0) {
73                 LogDebug("Resolver for %s created (PID %d).", ng_ipaddr_tostr(Addr), pid);
74                 return true;
75         } else if( pid == 0 ) {
76                 /* Sub process */
77                 Log_Init_Subprocess("Resolver");
78                 Do_ResolveAddr( Addr, identsock, pipefd[1]);
79                 Log_Exit_Subprocess("Resolver");
80                 exit(0);
81         }
82         return false;
83 } /* Resolve_Addr */
84
85
86 /**
87  * Resolve hostname (asynchronous!).
88  */
89 GLOBAL bool
90 Resolve_Name( PROC_STAT *s, const char *Host, void (*cbfunc)(int, short))
91 {
92         int pipefd[2];
93         pid_t pid;
94
95         assert(s != NULL);
96
97         pid = Proc_Fork(s, pipefd, cbfunc, RESOLVER_TIMEOUT);
98         if (pid > 0) {
99                 /* Main process */
100 #ifdef DEBUG
101                 Log( LOG_DEBUG, "Resolver for \"%s\" created (PID %d).", Host, pid );
102 #endif
103                 return true;
104         } else if( pid == 0 ) {
105                 /* Sub process */
106                 Log_Init_Subprocess("Resolver");
107                 Do_ResolveName(Host, pipefd[1]);
108                 Log_Exit_Subprocess("Resolver");
109                 exit(0);
110         }
111         return false;
112 } /* Resolve_Name */
113
114
115 #if !defined(HAVE_GETADDRINFO) || !defined(HAVE_GETNAMEINFO)
116 #if !defined(WANT_IPV6) && defined(h_errno)
117 static char *
118 Get_Error( int H_Error )
119 {
120         /* Get error message for H_Error */
121         switch( H_Error ) {
122         case HOST_NOT_FOUND:
123                 return "host not found";
124         case NO_DATA:
125                 return "name valid but no IP address defined";
126         case NO_RECOVERY:
127                 return "name server error";
128         case TRY_AGAIN:
129                 return "name server temporary not available";
130         }
131         return "unknown error";
132 }
133 #endif
134 #endif
135
136
137 /* Do "IDENT" (aka "AUTH") lookup and append result to resolved_addr array */
138 static void
139 Do_IdentQuery(int identsock, array *resolved_addr)
140 {
141 #ifdef IDENTAUTH
142         char *res;
143
144         if (identsock < 0)
145                 return;
146
147 #ifdef DEBUG
148         Log_Subprocess(LOG_DEBUG, "Doing IDENT lookup on socket %d ...",
149                        identsock);
150 #endif
151         res = ident_id( identsock, 10 );
152 #ifdef DEBUG
153         Log_Subprocess(LOG_DEBUG, "Ok, IDENT lookup on socket %d done: \"%s\"",
154                        identsock, res ? res : "(NULL)");
155 #endif
156         if (!res) /* no result */
157                 return;
158         if (!array_cats(resolved_addr, res))
159                 Log_Subprocess(LOG_WARNING,
160                                "Resolver: Cannot copy IDENT result: %s!",
161                                strerror(errno));
162
163         free(res);
164 #else
165         (void) identsock;
166         (void) resolved_addr;
167 #endif
168 }
169
170
171 /**
172  * perform reverse DNS lookup and put result string into resbuf.
173  * If no hostname could be obtained, this function stores the string representation of
174  * the IP address in resbuf and returns false.
175  * @param IpAddr ip address to resolve
176  * @param resbuf result buffer to store DNS name/string representation of ip address
177  * @param reslen size of result buffer (must be >= NGT_INET_ADDRSTRLEN)
178  * @return true if reverse lookup successful, false otherwise
179  */
180 static bool
181 ReverseLookup(const ng_ipaddr_t *IpAddr, char *resbuf, size_t reslen)
182 {
183         char tmp_ip_str[NG_INET_ADDRSTRLEN];
184         const char *errmsg;
185 #ifdef HAVE_GETNAMEINFO
186         static const char funcname[]="getnameinfo";
187         int res;
188
189         *resbuf = 0;
190
191         res = getnameinfo((struct sockaddr *) IpAddr, ng_ipaddr_salen(IpAddr),
192                           resbuf, (socklen_t)reslen, NULL, 0, NI_NAMEREQD);
193         if (res == 0)
194                 return true;
195
196         if (res == EAI_SYSTEM)
197                 errmsg = strerror(errno);
198         else
199                 errmsg = gai_strerror(res);
200 #else
201         const struct sockaddr_in *Addr = (const struct sockaddr_in *) IpAddr;
202         struct hostent *h;
203         static const char funcname[]="gethostbyaddr";
204
205         h = gethostbyaddr((char *)&Addr->sin_addr, sizeof(Addr->sin_addr), AF_INET);
206         if (h) {
207                 if (strlcpy(resbuf, h->h_name, reslen) < reslen)
208                         return true;
209                 errmsg = "hostname too long";
210         } else {
211 # ifdef h_errno
212                 errmsg = Get_Error(h_errno);
213 # else
214                 errmsg = "unknown error";
215 # endif /* h_errno */
216         }
217 #endif  /* HAVE_GETNAMEINFO */
218
219         assert(errmsg);
220         assert(reslen >= NG_INET_ADDRSTRLEN);
221         ng_ipaddr_tostr_r(IpAddr, tmp_ip_str);
222
223         Log_Subprocess(LOG_WARNING, "%s: Can't resolve address \"%s\": %s",
224                                 funcname, tmp_ip_str, errmsg);
225         strlcpy(resbuf, tmp_ip_str, reslen);
226         return false;
227 }
228
229
230 /**
231  * perform DNS lookup of given host name and fill IpAddr with a list of
232  * ip addresses associated with that name.
233  * ip addresses found are stored in the "array *IpAddr" argument (type ng_ipaddr_t)
234  * @param hostname The domain name to look up.
235  * @param IpAddr pointer to empty and initialized array to store results
236  * @return true if lookup successful, false if domain name not found
237  */
238 static bool
239 ForwardLookup(const char *hostname, array *IpAddr, int af)
240 {
241         ng_ipaddr_t addr;
242
243 #ifdef HAVE_GETADDRINFO
244         int res;
245         struct addrinfo *a, *ai_results;
246         static struct addrinfo hints;
247
248 #ifdef AI_ADDRCONFIG    /* glibc has this, but not e.g. netbsd 4.0 */
249         hints.ai_flags = AI_ADDRCONFIG;
250 #endif
251         hints.ai_socktype = SOCK_STREAM;
252         hints.ai_protocol = IPPROTO_TCP;
253         hints.ai_family = af;
254
255         memset(&addr, 0, sizeof(addr));
256
257         res = getaddrinfo(hostname, NULL, &hints, &ai_results);
258         switch (res) {
259         case 0: break;
260         case EAI_SYSTEM:
261                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, strerror(errno));
262                 return false;
263         default:
264                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s", hostname, gai_strerror(res));
265                 return false;
266         }
267
268         for (a = ai_results; a != NULL; a = a->ai_next) {
269                 assert(a->ai_addrlen <= sizeof(addr));
270
271                 if (a->ai_addrlen > sizeof(addr))
272                         continue;
273
274                 memcpy(&addr, a->ai_addr, a->ai_addrlen);
275
276                 if (!array_catb(IpAddr, (char *)&addr, sizeof(addr)))
277                         break;
278         }
279
280         freeaddrinfo(ai_results);
281         return a == NULL;
282 #else
283         struct hostent *h = gethostbyname(hostname);
284
285         if (!h) {
286 #ifdef h_errno
287                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\": %s",
288                                hostname, Get_Error(h_errno));
289 #else
290                 Log_Subprocess(LOG_WARNING, "Can't resolve \"%s\"", hostname);
291 #endif
292                 return false;
293         }
294         memset(&addr, 0, sizeof(addr));
295
296         addr.sin4.sin_family = AF_INET;
297         memcpy(&addr.sin4.sin_addr, h->h_addr, sizeof(struct in_addr));
298
299         return array_copyb(IpAddr, (char *)&addr, sizeof(addr));
300 #endif /* HAVE_GETADDRINFO */
301 }
302
303
304 static bool
305 Addr_in_list(const array *resolved_addr, const ng_ipaddr_t *Addr)
306 {
307         char tmp_ip_str[NG_INET_ADDRSTRLEN];
308         const ng_ipaddr_t *tmpAddrs = array_start(resolved_addr);
309         size_t len = array_length(resolved_addr, sizeof(*tmpAddrs));
310
311         assert(len > 0);
312         assert(tmpAddrs);
313
314         while (len > 0) {
315                 if (ng_ipaddr_ipequal(Addr, tmpAddrs))
316                         return true;
317                 tmpAddrs++;
318                 len--;
319         }
320         /* failed; print list of addresses */
321         ng_ipaddr_tostr_r(Addr, tmp_ip_str);
322         len = array_length(resolved_addr, sizeof(*tmpAddrs));
323         tmpAddrs = array_start(resolved_addr);
324
325         while (len > 0) {
326                 Log_Subprocess(LOG_WARNING, "Address mismatch: %s != %s",
327                         tmp_ip_str, ng_ipaddr_tostr(tmpAddrs));
328                 tmpAddrs++;
329                 len--;
330         }
331
332         return false;
333 }
334
335
336 static void
337 Log_Forgery_NoIP(const char *ip, const char *host)
338 {
339         Log_Subprocess(LOG_WARNING,
340                 "Possible forgery: %s resolved to %s (which has no ip address)", ip, host);
341 }
342
343 static void
344 Log_Forgery_WrongIP(const char *ip, const char *host)
345 {
346         Log_Subprocess(LOG_WARNING,
347                 "Possible forgery: %s resolved to %s (which points to different address)", ip, host);
348 }
349
350
351 static void
352 ArrayWrite(int fd, const array *a)
353 {
354         size_t len = array_bytes(a);
355         const char *data = array_start(a);
356
357         assert(data);
358
359         if( (size_t)write(fd, data, len) != len )
360                 Log_Subprocess( LOG_CRIT, "Resolver: Can't write to parent: %s!",
361                                                         strerror(errno));
362 }
363
364
365 static void
366 Do_ResolveAddr(const ng_ipaddr_t *Addr, int identsock, int w_fd)
367 {
368         /* Resolver sub-process: resolve IP address and write result into
369          * pipe to parent. */
370         char hostname[CLIENT_HOST_LEN];
371         char tmp_ip_str[NG_INET_ADDRSTRLEN];
372         size_t len;
373         array resolved_addr;
374
375         array_init(&resolved_addr);
376         ng_ipaddr_tostr_r(Addr, tmp_ip_str);
377 #ifdef DEBUG
378         Log_Subprocess(LOG_DEBUG, "Now resolving %s ...", tmp_ip_str);
379 #endif
380         if (!ReverseLookup(Addr, hostname, sizeof(hostname)))
381                 goto dns_done;
382
383         if (ForwardLookup(hostname, &resolved_addr, ng_ipaddr_af(Addr))) {
384                 if (!Addr_in_list(&resolved_addr, Addr)) {
385                         Log_Forgery_WrongIP(tmp_ip_str, hostname);
386                         strlcpy(hostname, tmp_ip_str, sizeof(hostname));
387                 }
388         } else {
389                 Log_Forgery_NoIP(tmp_ip_str, hostname);
390                 strlcpy(hostname, tmp_ip_str, sizeof(hostname));
391         }
392 #ifdef DEBUG
393         Log_Subprocess(LOG_DEBUG, "Ok, translated %s to \"%s\".", tmp_ip_str, hostname);
394 #endif
395  dns_done:
396         len = strlen(hostname);
397         hostname[len] = '\n';
398         if (!array_copyb(&resolved_addr, hostname, ++len)) {
399                 Log_Subprocess(LOG_CRIT,
400                                "Resolver: Can't copy resolved name: %s!",
401                                strerror(errno));
402                 array_free(&resolved_addr);
403                 return;
404         }
405
406         Do_IdentQuery(identsock, &resolved_addr);
407
408         ArrayWrite(w_fd, &resolved_addr);
409
410         array_free(&resolved_addr);
411 } /* Do_ResolveAddr */
412
413
414 static void
415 Do_ResolveName( const char *Host, int w_fd )
416 {
417         /* Resolver sub-process: resolve name and write result into pipe
418          * to parent. */
419         array IpAddrs;
420         int af;
421 #ifdef DEBUG
422         ng_ipaddr_t *addr;
423         size_t len;
424 #endif
425         Log_Subprocess(LOG_DEBUG, "Now resolving \"%s\" ...", Host);
426
427         array_init(&IpAddrs);
428
429 #ifdef WANT_IPV6
430         af = AF_UNSPEC;
431         assert(Conf_ConnectIPv6 || Conf_ConnectIPv4);
432
433         if (!Conf_ConnectIPv6)
434                 af = AF_INET;
435         if (!Conf_ConnectIPv4)
436                 af = AF_INET6;
437 #else
438         af = AF_INET;
439 #endif
440         if (!ForwardLookup(Host, &IpAddrs, af)) {
441                 close(w_fd);
442                 return;
443         }
444 #ifdef DEBUG
445         len = array_length(&IpAddrs, sizeof(*addr));
446         assert(len > 0);
447         addr = array_start(&IpAddrs);
448         assert(addr);
449         for (; len > 0; --len,addr++) {
450                 Log_Subprocess(LOG_DEBUG, "translated \"%s\" to %s.",
451                                         Host, ng_ipaddr_tostr(addr));
452         }
453 #endif
454         /* Write result into pipe to parent */
455         ArrayWrite(w_fd, &IpAddrs);
456
457         array_free(&IpAddrs);
458 } /* Do_ResolveName */
459
460
461 /* -eof- */