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