7bab2e4d0852be09b97ad8e025dd564dc9145eda
[citadel.git] / citadel / locate_host.c
1 /*
2  * Functions which handle hostname/address lookups and resolution
3  *
4  * Copyright (c) 1987-2018 by the citadel.org team
5  *
6  * This program is open source software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License, version 3.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include "sysdep.h"
16 #include <string.h>
17 #include <stdio.h>
18 #include <syslog.h>
19 #include <ctype.h>
20 #include <netdb.h>
21 #include <netinet/in.h>
22 #include <arpa/inet.h>
23 #include <libcitadel.h>
24
25 #include "context.h"
26 #ifdef HAVE_RESOLV_H
27 #include <arpa/nameser.h>
28 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
29 #include <arpa/nameser_compat.h>
30 #endif
31 #include <resolv.h>
32 #endif
33
34 #include "domain.h"
35 #include "locate_host.h"
36
37 /* START: some missing macros on OpenBSD 3.9 */
38 #ifndef NS_CMPRSFLGS
39 #define NS_CMPRSFLGS   0xc0
40 #endif
41 #if !defined(NS_MAXCDNAME) && defined (MAXCDNAME)
42 #define NS_MAXCDNAME MAXCDNAME
43 #endif
44 #if !defined(NS_INT16SZ) && defined(INT16SZ)
45 #define NS_INT16SZ INT16SZ
46 #define NS_INT32SZ INT32SZ
47 #endif
48 #ifndef NS_GET16
49 #  define NS_GET16 GETSHORT
50 #endif
51 /* END: some missing macros on OpenBSD 3.9 */
52
53
54 /*
55  * Given an open client socket, return the host name and IP address at the other end.
56  * (IPv4 and IPv6 compatible)
57  */
58 void locate_host(char *tbuf, size_t n, char *abuf, size_t na, int client_socket)
59 {
60         struct sockaddr_in6 clientaddr;
61         unsigned int addrlen = sizeof(clientaddr);
62
63         tbuf[0] = 0;
64         abuf[0] = 0;
65
66         getpeername(client_socket, (struct sockaddr *)&clientaddr, &addrlen);
67         getnameinfo((struct sockaddr *)&clientaddr, addrlen, tbuf, n, NULL, 0, 0);
68         getnameinfo((struct sockaddr *)&clientaddr, addrlen, abuf, na, NULL, 0, NI_NUMERICHOST);
69
70         /* Convert IPv6-mapped IPv4 addresses back to traditional dotted quad.
71          *
72          * Other code here, such as the RBL check, will expect IPv4 addresses to be represented
73          * as dotted-quad, even if they come in over a hybrid IPv6/IPv4 socket.
74          */
75         if ( (strlen(abuf) > 7) && (!strncasecmp(abuf, "::ffff:", 7)) ) {
76                 if (!strcmp(abuf, tbuf)) strcpy(tbuf, &tbuf[7]);
77                 strcpy(abuf, &abuf[7]);
78         }
79 }
80
81
82 /*
83  * RBL check written by Edward S. Marshall [http://rblcheck.sourceforge.net]
84  */
85 #define RESULT_SIZE 4096 /* What is the longest result text we support? */
86 int rblcheck_backend(char *domain, char *txtbuf, int txtbufsize) {
87         int a, b, c;
88         char *result = NULL;
89         u_char fixedans[ PACKETSZ ];
90         u_char *answer;
91         int need_to_free_answer = 0;
92         const u_char *cp;
93         u_char *rp;
94         const u_char *cend;
95         const u_char *rend;
96         int len;
97         char *p = NULL;
98         static int res_initted = 0;
99
100         if (!res_initted) {             /* only have to do this once */
101                 res_init();
102                 res_initted = 1;
103         }
104
105         /* Make our DNS query. */
106         answer = fixedans;
107         if (server_shutting_down)
108         {
109                 if (txtbuf != NULL) {
110                         snprintf(txtbuf, txtbufsize, "System shutting down");
111                 }
112                 return (1);
113         }
114         len = res_query(domain, C_IN, T_A, answer, PACKETSZ);
115
116         /* Was there a problem? If so, the domain doesn't exist. */
117         if (len == -1) {
118                 if (txtbuf != NULL) {
119                         strcpy(txtbuf, "");
120                 }
121                 return(0);
122         }
123
124         if (len > PACKETSZ)
125         {
126                 answer = malloc(len);
127                 need_to_free_answer = 1;
128                 len = res_query(domain, C_IN, T_A, answer, len);
129                 if( len == -1 ) {
130                         if (txtbuf != NULL) {
131                                 snprintf(txtbuf, txtbufsize, "Message rejected due to known spammer source IP address");
132                         }
133                         if (need_to_free_answer) free(answer);
134                         return(1);
135                 }
136         }
137         if (server_shutting_down)
138         {
139                 if (txtbuf != NULL) {
140                         snprintf(txtbuf, txtbufsize, "System shutting down");
141                 }
142                 if (need_to_free_answer) free(answer);
143                 return (1);
144         }
145
146         result = (char *) malloc(RESULT_SIZE);
147         result[0] = '\0';
148
149         /* Make another DNS query for textual data; this shouldn't
150          * be a performance hit, since it'll now be cached at the
151          * nameserver we're using.
152          */
153         len = res_query(domain, C_IN, T_TXT, answer, PACKETSZ);
154         if (server_shutting_down)
155         {
156                 if (txtbuf != NULL) {
157                         snprintf(txtbuf, txtbufsize, "System shutting down");
158                 }
159                 if (need_to_free_answer) free(answer);
160                 free(result);
161                 return (1);
162         }
163
164         /* Just in case there's no TXT record... */
165         if (len ==(-1))
166         {
167                 if (txtbuf != NULL) {
168                         snprintf(txtbuf, txtbufsize, "Message rejected due to known spammer source IP address");
169                 }
170                 if (need_to_free_answer) free(answer);
171                 free(result);
172                 return(1);
173         }
174
175         /* Skip the header and the address we queried. */
176         cp = answer + sizeof( HEADER );
177         while( *cp != '\0' )
178         {
179                 a = *cp++;
180                 while( a-- )
181                         cp++;
182         }
183
184         /* This seems to be a bit of magic data that we need to
185          * skip. I wish there were good online documentation
186          * for programming for libresolv, so I'd know what I'm
187          * skipping here. Anyone reading this, feel free to
188          * enlighten me.
189          */
190         cp += 1 + NS_INT16SZ + NS_INT32SZ;
191
192         /* Skip the type, class and ttl. */
193         cp += (NS_INT16SZ * 2) + NS_INT32SZ;
194
195         /* Get the length and end of the buffer. */
196         NS_GET16(c, cp);
197         cend = cp + c;
198
199         /* Iterate over any multiple answers we might have. In
200          * this context, it's unlikely, but anyway.
201          */
202         rp = (u_char *) result;
203         rend = (u_char *) result + RESULT_SIZE - 1;
204         while (cp < cend && rp < rend)
205         {
206                 a = *cp++;
207                 if( a != 0 )
208                         for (b = a; b > 0 && cp < cend && rp < rend; b--)
209                         {
210                                 if (*cp == '\n' || *cp == '"' || *cp == '\\')
211                                 {
212                                         *rp++ = '\\';
213                                 }
214                                 *rp++ = *cp++;
215                         }
216         }
217         *rp = '\0';
218         if (txtbuf != NULL) {
219                 long len;
220                 len = snprintf(txtbuf, txtbufsize, "%s", result);
221         
222                 /* Remove nonprintable characters */
223                 for (p = txtbuf; *p != '\0'; p++) {
224                         if (!isprint(*p)) {
225                                 memmove (p,
226                                          p + 1,
227                                          len - (p - txtbuf) - 1);
228                         }
229                 }
230         }
231         if (need_to_free_answer) free(answer);
232         free(result);
233         return(1);
234 }
235
236
237 /*
238  * Check to see if the client host is on some sort of spam list (RBL)
239  * If spammer, returns nonzero and places reason in 'message_to_spammer'
240  */
241 int rbl_check(char *cs_addr, char *message_to_spammer)
242 {
243         char tbuf[256] = "";
244         int suffix_pos = 0;
245         int rbl;
246         int rc;
247         int num_rbl;
248         char rbl_domains[SIZ];
249         char txt_answer[1024];
250         struct timeval tx_start;
251         struct timeval tx_finish;
252
253         rc = 0;
254         strcpy(message_to_spammer, "ok");
255         gettimeofday(&tx_start, NULL);          /* start a stopwatch for performance timing */
256
257         if ((strchr(cs_addr, '.')) && (!strchr(cs_addr, ':'))) {
258                 int a1, a2, a3, a4;
259
260                 sscanf(cs_addr, "%d.%d.%d.%d", &a1, &a2, &a3, &a4);
261                 snprintf(tbuf, sizeof tbuf, "%d.%d.%d.%d.", a4, a3, a2, a1);
262                 suffix_pos = strlen(tbuf);
263         }
264         else if ((!strchr(cs_addr, '.')) && (strchr(cs_addr, ':'))) {
265                 int num_colons = 0;
266                 int i = 0;
267                 char workbuf[sizeof tbuf];
268                 char *ptr;
269
270                 /* tedious code to expand and reverse an IPv6 address */
271                 safestrncpy(tbuf, cs_addr, sizeof tbuf);
272                 num_colons = haschar(tbuf, ':');
273                 if ((num_colons < 2) || (num_colons > 7))
274                         goto finish_rbl;        /* badly formed address */
275
276                 /* expand the "::" shorthand */
277                 while (num_colons < 7) {
278                         ptr = strstr(tbuf, "::");
279                         if (!ptr)
280                                 goto finish_rbl;                                /* badly formed address */
281
282                         ++ptr;
283                         strcpy(workbuf, ptr);
284                         strcpy(ptr, ":");
285                         strcat(ptr, workbuf);
286                         ++num_colons;
287                 }
288
289                 /* expand to 32 hex characters with no colons */
290                 strcpy(workbuf, tbuf);
291                 strcpy(tbuf, "00000000000000000000000000000000");
292                 for (i=0; i<8; ++i) {
293                         char tokbuf[5];
294                         extract_token(tokbuf, workbuf, i, ':', sizeof tokbuf);
295                         memcpy(&tbuf[ (i*4) + (4-strlen(tokbuf)) ], tokbuf, strlen(tokbuf) );
296                 }
297                 if (strlen(tbuf) != 32) {
298                         goto finish_rbl;
299                 }
300
301                 /* now reverse it and add dots */
302                 strcpy(workbuf, tbuf);
303                 for (i=0; i<32; ++i) {
304                         tbuf[i*2] = workbuf[31-i];
305                         tbuf[(i*2)+1] = '.';
306                 }
307                 tbuf[64] = 0;
308                 suffix_pos = 64;
309         }
310         else {
311                 goto finish_rbl;        /* unknown address format */
312         }
313
314         /* See if we have any RBL domains configured */
315         num_rbl = get_hosts(rbl_domains, "rbl");
316         if (num_rbl < 1)
317         {
318                 goto finish_rbl;
319         }
320
321         /* Try all configured RBL's */
322         for (rbl=0; rbl<num_rbl; ++rbl) {
323                 extract_token(&tbuf[suffix_pos], rbl_domains, rbl, '|', (sizeof tbuf - suffix_pos));
324
325                 if (rblcheck_backend(tbuf, txt_answer, sizeof txt_answer)) {
326                         strcpy(message_to_spammer, txt_answer);
327                         syslog(LOG_INFO, "RBL: %s %s", cs_addr, txt_answer);
328                         rc = 1;
329                 }
330         }
331 finish_rbl:
332         /* How long did this transaction take? */
333         gettimeofday(&tx_finish, NULL);
334
335         syslog(LOG_WARNING, "rbl: %s [%ld.%06ld] %s",
336                 cs_addr,
337                 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
338                 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000,
339                 (rc)?"found":"none found"
340         );
341
342         return rc;
343 }
344                         
345
346 /*
347  * Convert a host name to a dotted quad address. 
348  * Returns zero on success or nonzero on failure.
349  *
350  * FIXME this is obviously not IPv6 compatible.
351  */
352 int hostname_to_dotted_quad(char *addr, char *host) {
353         struct hostent *ch;
354         const char *i;
355         int a1, a2, a3, a4;
356
357         ch = gethostbyname(host);
358         if (ch == NULL) {
359                 strcpy(addr, "0.0.0.0");
360                 return(1);
361         }
362
363         i = (const char *) ch->h_addr_list[0];
364         a1 = ((*i++) & 0xff);
365         a2 = ((*i++) & 0xff);
366         a3 = ((*i++) & 0xff);
367         a4 = ((*i++) & 0xff);
368         sprintf(addr, "%d.%d.%d.%d", a1, a2, a3, a4);
369         return(0);
370 }