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