Added debug notices for dnsbl matches in blacklist module.
[srvx.git] / src / mod-blacklist.c
1 /* Blacklist module for srvx 1.x
2  * Copyright 2007 Michael Poole <mdpoole@troilus.org>
3  *
4  * This file is part of srvx.
5  *
6  * srvx is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with srvx; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
19  */
20
21 #include "conf.h"
22 #include "gline.h"
23 #include "modcmd.h"
24 #include "proto.h"
25 #include "sar.h"
26
27 const char *blacklist_module_deps[] = { NULL };
28
29 struct dnsbl_zone {
30     struct string_list reasons;
31     const char *description;
32     const char *reason;
33     unsigned int duration;
34     unsigned int mask;
35     unsigned int debug : 1;
36     char zone[1];
37 };
38
39 struct dnsbl_data {
40     char client_ip[IRC_NTOP_MAX_SIZE];
41     char zone_name[1];
42 };
43
44 static struct log_type *bl_log;
45 static dict_t blacklist_zones; /* contains struct dnsbl_zone */
46 static dict_t blacklist_hosts; /* maps IPs or hostnames to reasons from blacklist_reasons */
47 static dict_t blacklist_reasons; /* maps strings to themselves (poor man's data sharing) */
48
49 static struct {
50     struct userNode *debug_bot;
51     struct chanNode *debug_channel;
52     unsigned long gline_duration;
53 } conf;
54
55 #define blacklist_debug(format...) do { if (conf.debug_bot && conf.debug_channel) send_channel_notice(conf.debug_channel , conf.debug_bot , ## format); } while (0)
56
57 static void
58 do_expandos(char *output, unsigned int out_len, const char *input, ...)
59 {
60     va_list args;
61     const char *key;
62     const char *datum;
63     char *found;
64     unsigned int klen;
65     unsigned int dlen;
66     unsigned int rlen;
67
68     safestrncpy(output, input, out_len);
69     va_start(args, input);
70     while ((key = va_arg(args, const char*)) != NULL) {
71         datum = va_arg(args, const char *);
72         klen = strlen(key);
73         dlen = strlen(datum);
74         for (found = output; (found = strstr(output, key)) != NULL; found += dlen) {
75             rlen = strlen(found + klen);
76             if ((dlen > klen) && ((unsigned)(found + dlen + rlen - output) > out_len))
77                 rlen = output + out_len - found - dlen;
78             memmove(found + dlen, found + klen, rlen);
79             memcpy(found, datum, dlen + 1);
80         }
81     }
82     va_end(args);
83 }
84
85 static void
86 dnsbl_hit(struct sar_request *req, struct dns_header *hdr, struct dns_rr *rr, unsigned char *raw, unsigned int raw_size)
87 {
88     struct dnsbl_data *data;
89     struct dnsbl_zone *zone;
90     const char *message;
91     char *txt;
92     unsigned int mask;
93     unsigned int pos;
94     unsigned int len;
95     unsigned int ii;
96     char reason[MAXLEN];
97     char target[IRC_NTOP_MAX_SIZE + 2];
98
99     /* Get the DNSBL zone (to make sure it has not disappeared in a rehash). */
100     data = (struct dnsbl_data*)(req + 1);
101     zone = dict_find(blacklist_zones, data->zone_name, NULL);
102     if (!zone)
103         return;
104
105     /* Scan the results. */
106     for (mask = 0, ii = 0, txt = NULL; ii < hdr->ancount; ++ii) {
107         pos = rr[ii].rd_start;
108         switch (rr[ii].type) {
109         case REQ_TYPE_A:
110             if (rr[ii].rdlength != 4)
111                 break;
112             if (pos + 3 < raw_size)
113                 mask |= (1 << raw[pos + 3]);
114             break;
115         case REQ_TYPE_TXT:
116             len = raw[pos];
117             txt = malloc(len + 1);
118             memcpy(txt, raw + pos + 1, len);
119             txt[len] = '\0';
120             break;
121         }
122     }
123
124     /* Do we care about one of the masks we found? */
125     if (mask & zone->mask) {
126         /* See if a per-result message was provided. */
127         for (ii = 0, message = NULL; mask && (ii < zone->reasons.used); ++ii, mask >>= 1) {
128             if (0 == (mask & 1))
129                 continue;
130             if (NULL != (message = zone->reasons.list[ii]))
131                 break;
132         }
133
134         /* If not, use a standard fallback. */
135         if (message == NULL) {
136             message = zone->reason;
137             if (message == NULL)
138                 message = "client is blacklisted";
139         }
140
141         /* Expand elements of the message as necessary. */
142         do_expandos(reason, sizeof(reason), message, "%txt%", (txt ? txt : "(no-txt)"), "%ip%", data->client_ip, NULL);
143
144         if (zone->debug) {
145             blacklist_debug("DNSBL match: [%s] %s (%s)", zone->zone, data->client_ip, reason);
146         } else {
147             /* Now generate the G-line. */
148             target[0] = '*';
149             target[1] = '@';
150             strcpy(target + 2, data->client_ip);
151             gline_add(self->name, target, zone->duration, reason, now, now, 1);
152         }
153     }
154     free(txt);
155 }
156
157 static int
158 blacklist_check_user(struct userNode *user)
159 {
160     static const char *hexdigits = "0123456789abcdef";
161     dict_iterator_t it;
162     const char *reason;
163     const char *host;
164     unsigned int dnsbl_len;
165     unsigned int ii;
166     char ip[IRC_NTOP_MAX_SIZE];
167     char dnsbl_target[128];
168
169     /* Users with bogus IPs are probably service bots. */
170     if (!irc_in_addr_is_valid(user->ip))
171         return 0;
172
173     /* Check local file-based blacklist. */
174     irc_ntop(ip, sizeof(ip), &user->ip);
175     reason = dict_find(blacklist_hosts, host = ip, NULL);
176     if (reason == NULL) {
177         reason = dict_find(blacklist_hosts, host = user->hostname, NULL);
178     }
179     if (reason != NULL) {
180         char *target;
181         target = alloca(strlen(host) + 3);
182         target[0] = '*';
183         target[1] = '@';
184         strcpy(target + 2, host);
185         gline_add(self->name, target, conf.gline_duration, reason, now, now, 1);
186     }
187
188     /* Figure out the base part of a DNS blacklist hostname. */
189     if (irc_in_addr_is_ipv4(user->ip)) {
190         dnsbl_len = snprintf(dnsbl_target, sizeof(dnsbl_target), "%d.%d.%d.%d.", user->ip.in6_8[15], user->ip.in6_8[14], user->ip.in6_8[13], user->ip.in6_8[12]);
191     } else if (irc_in_addr_is_ipv6(user->ip)) {
192         for (ii = 0; ii < 16; ++ii) {
193             dnsbl_target[ii * 4 + 0] = hexdigits[user->ip.in6_8[15 - ii] & 15];
194             dnsbl_target[ii * 4 + 1] = '.';
195             dnsbl_target[ii * 4 + 2] = hexdigits[user->ip.in6_8[15 - ii] >> 4];
196             dnsbl_target[ii * 4 + 3] = '.';
197         }
198         dnsbl_len = 48;
199     } else {
200         return 0;
201     }
202
203     /* Start a lookup for the appropriate hostname in each DNSBL. */
204     for (it = dict_first(blacklist_zones); it; it = iter_next(it)) {
205         struct dnsbl_data *data;
206         struct sar_request *req;
207         const char *zone;
208
209         zone = iter_key(it);
210         safestrncpy(dnsbl_target + dnsbl_len, zone, sizeof(dnsbl_target) - dnsbl_len);
211         req = sar_request_simple(sizeof(*data) + strlen(zone), dnsbl_hit, NULL, dnsbl_target, REQ_QTYPE_ALL, NULL);
212         if (req) {
213             data = (struct dnsbl_data*)(req + 1);
214             strcpy(data->client_ip, ip);
215             strcpy(data->zone_name, zone);
216         }
217     }
218     return 0;
219 }
220
221 static void
222 blacklist_load_file(const char *filename, const char *default_reason)
223 {
224     FILE *file;
225     const char *reason;
226     char *mapped_reason;
227     char *sep;
228     size_t len;
229     char linebuf[MAXLEN];
230
231     if (!filename)
232         return;
233     if (!default_reason)
234         default_reason = "client is blacklisted";
235     file = fopen(filename, "r");
236     if (!file) {
237         log_module(bl_log, LOG_ERROR, "Unable to open %s for reading: %s", filename, strerror(errno));
238         return;
239     }
240     log_module(bl_log, LOG_DEBUG, "Loading blacklist from %s.", filename);
241     while (fgets(linebuf, sizeof(linebuf), file)) {
242         /* Trim whitespace from end of line. */
243         len = strlen(linebuf);
244         while (isspace(linebuf[len-1]))
245             linebuf[--len] = '\0';
246
247         /* Figure out which reason string we should use. */
248         reason = default_reason;
249         sep = strchr(linebuf, ' ');
250         if (sep) {
251             *sep++ = '\0';
252             while (isspace(*sep))
253                 sep++;
254             if (*sep != '\0')
255                 reason = sep;
256         }
257
258         /* See if the reason string is already known. */
259         mapped_reason = dict_find(blacklist_reasons, reason, NULL);
260         if (!mapped_reason) {
261             mapped_reason = strdup(reason);
262             dict_insert(blacklist_reasons, mapped_reason, (char*)mapped_reason);
263         }
264
265         /* Store the blacklist entry. */
266         dict_insert(blacklist_hosts, strdup(linebuf), mapped_reason);
267     }
268     fclose(file);
269 }
270
271 static void
272 dnsbl_zone_free(void *pointer)
273 {
274     struct dnsbl_zone *zone;
275     zone = pointer;
276     free(zone->reasons.list);
277     free(zone);
278 }
279
280 static void
281 blacklist_conf_read(void)
282 {
283     dict_t node;
284     dict_t subnode;
285     const char *str1;
286     const char *str2;
287
288     dict_delete(blacklist_zones);
289     blacklist_zones = dict_new();
290     dict_set_free_data(blacklist_zones, dnsbl_zone_free);
291
292     dict_delete(blacklist_hosts);
293     blacklist_hosts = dict_new();
294     dict_set_free_keys(blacklist_hosts, free);
295
296     dict_delete(blacklist_reasons);
297     blacklist_reasons = dict_new();
298     dict_set_free_keys(blacklist_reasons, free);
299
300     node = conf_get_data("modules/blacklist", RECDB_OBJECT);
301     if (node == NULL)
302         return;
303
304     str1 = database_get_data(node, "debug_bot", RECDB_QSTRING);
305     if (str1)
306         conf.debug_bot = GetUserH(str1);
307
308     str1 = database_get_data(node, "debug_channel", RECDB_QSTRING);
309     if (conf.debug_bot && str1) {
310         str2 = database_get_data(node, "debug_channel_modes", RECDB_QSTRING);
311         if (!str2)
312             str2 = "+tinms";
313         conf.debug_channel = AddChannel(str1, now, str2, NULL);
314         AddChannelUser(conf.debug_bot, conf.debug_channel)->modes |= MODE_CHANOP;
315     } else {
316         conf.debug_channel = NULL;
317     }
318
319     str1 = database_get_data(node, "file", RECDB_QSTRING);
320     str2 = database_get_data(node, "file_reason", RECDB_QSTRING);
321     blacklist_load_file(str1, str2);
322
323     str1 = database_get_data(node, "gline_duration", RECDB_QSTRING);
324     if (str1 == NULL)
325         str1 = "1h";
326     conf.gline_duration = ParseInterval(str1);
327
328     subnode = database_get_data(node, "dnsbl", RECDB_OBJECT);
329     if (subnode) {
330         static const char *reason_prefix = "reason_";
331         static const unsigned int max_id = 255;
332         struct dnsbl_zone *zone;
333         dict_iterator_t it;
334         dict_iterator_t it2;
335         dict_t dnsbl;
336         unsigned int id;
337
338         for (it = dict_first(subnode); it; it = iter_next(it)) {
339             dnsbl = GET_RECORD_OBJECT((struct record_data*)iter_data(it));
340             if (!dnsbl)
341                 continue;
342
343             zone = malloc(sizeof(*zone) + strlen(iter_key(it)));
344             strcpy(zone->zone, iter_key(it));
345             zone->description = database_get_data(dnsbl, "description", RECDB_QSTRING);
346             zone->reason = database_get_data(dnsbl, "reason", RECDB_QSTRING);
347             str1 = database_get_data(dnsbl, "duration", RECDB_QSTRING);
348             zone->duration = str1 ? ParseInterval(str1) : 3600;
349             str1 = database_get_data(dnsbl, "mask", RECDB_QSTRING);
350             zone->mask = str1 ? strtoul(str1, NULL, 0) : ~0u;
351             str1 = database_get_data(dnsbl, "debug", RECDB_QSTRING);
352             zone->debug = str1 ? enabled_string(str1) : 0;
353             zone->reasons.used = 0;
354             zone->reasons.size = 0;
355             zone->reasons.list = NULL;
356             dict_insert(blacklist_zones, zone->zone, zone);
357
358             for (it2 = dict_first(dnsbl); it2; it2 = iter_next(it2)) {
359                 str1 = GET_RECORD_QSTRING((struct record_data*)(iter_data(it2)));
360                 if (!str1 || memcmp(iter_key(it2), reason_prefix, strlen(reason_prefix)))
361                     continue;
362                 id = strtoul(iter_key(it2) + strlen(reason_prefix), NULL, 0);
363                 if (id > max_id) {
364                     log_module(bl_log, LOG_ERROR, "Invalid code for DNSBL %s %s -- only %d responses supported.", iter_key(it), iter_key(it2), max_id);
365                     continue;
366                 }
367                 if (zone->reasons.size < id + 1) {
368                     zone->reasons.size = id + 1;
369                     zone->reasons.list = realloc(zone->reasons.list, zone->reasons.size * sizeof(zone->reasons.list[0]));
370                 }
371                 zone->reasons.list[id] = (char*)str1;
372                 if (zone->reasons.used < id + 1)
373                     zone->reasons.used = id + 1;
374             }
375         }
376     }
377 }
378
379 static void
380 blacklist_cleanup(void)
381 {
382     dict_delete(blacklist_zones);
383     dict_delete(blacklist_hosts);
384     dict_delete(blacklist_reasons);
385 }
386
387 int
388 blacklist_init(void)
389 {
390     bl_log = log_register_type("blacklist", "file:blacklist.log");
391     conf_register_reload(blacklist_conf_read);
392     reg_new_user_func(blacklist_check_user);
393     reg_exit_func(blacklist_cleanup);
394     return 1;
395 }
396
397 int
398 blacklist_finalize(void)
399 {
400     return 1;
401 }