Don't check users on bursting servers against blacklists.
[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 added during burst should not be checked. */
170     if (user->uplink->burst)
171         return 0;
172
173     /* Users with bogus IPs are probably service bots. */
174     if (!irc_in_addr_is_valid(user->ip))
175         return 0;
176
177     /* Check local file-based blacklist. */
178     irc_ntop(ip, sizeof(ip), &user->ip);
179     reason = dict_find(blacklist_hosts, host = ip, NULL);
180     if (reason == NULL) {
181         reason = dict_find(blacklist_hosts, host = user->hostname, NULL);
182     }
183     if (reason != NULL) {
184         char *target;
185         target = alloca(strlen(host) + 3);
186         target[0] = '*';
187         target[1] = '@';
188         strcpy(target + 2, host);
189         gline_add(self->name, target, conf.gline_duration, reason, now, now, 1);
190     }
191
192     /* Figure out the base part of a DNS blacklist hostname. */
193     if (irc_in_addr_is_ipv4(user->ip)) {
194         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]);
195     } else if (irc_in_addr_is_ipv6(user->ip)) {
196         for (ii = 0; ii < 16; ++ii) {
197             dnsbl_target[ii * 4 + 0] = hexdigits[user->ip.in6_8[15 - ii] & 15];
198             dnsbl_target[ii * 4 + 1] = '.';
199             dnsbl_target[ii * 4 + 2] = hexdigits[user->ip.in6_8[15 - ii] >> 4];
200             dnsbl_target[ii * 4 + 3] = '.';
201         }
202         dnsbl_len = 48;
203     } else {
204         return 0;
205     }
206
207     /* Start a lookup for the appropriate hostname in each DNSBL. */
208     for (it = dict_first(blacklist_zones); it; it = iter_next(it)) {
209         struct dnsbl_data *data;
210         struct sar_request *req;
211         const char *zone;
212
213         zone = iter_key(it);
214         safestrncpy(dnsbl_target + dnsbl_len, zone, sizeof(dnsbl_target) - dnsbl_len);
215         req = sar_request_simple(sizeof(*data) + strlen(zone), dnsbl_hit, NULL, dnsbl_target, REQ_QTYPE_ALL, NULL);
216         if (req) {
217             data = (struct dnsbl_data*)(req + 1);
218             strcpy(data->client_ip, ip);
219             strcpy(data->zone_name, zone);
220         }
221     }
222     return 0;
223 }
224
225 static void
226 blacklist_load_file(const char *filename, const char *default_reason)
227 {
228     FILE *file;
229     const char *reason;
230     char *mapped_reason;
231     char *sep;
232     size_t len;
233     char linebuf[MAXLEN];
234
235     if (!filename)
236         return;
237     if (!default_reason)
238         default_reason = "client is blacklisted";
239     file = fopen(filename, "r");
240     if (!file) {
241         log_module(bl_log, LOG_ERROR, "Unable to open %s for reading: %s", filename, strerror(errno));
242         return;
243     }
244     log_module(bl_log, LOG_DEBUG, "Loading blacklist from %s.", filename);
245     while (fgets(linebuf, sizeof(linebuf), file)) {
246         /* Trim whitespace from end of line. */
247         len = strlen(linebuf);
248         while (isspace(linebuf[len-1]))
249             linebuf[--len] = '\0';
250
251         /* Figure out which reason string we should use. */
252         reason = default_reason;
253         sep = strchr(linebuf, ' ');
254         if (sep) {
255             *sep++ = '\0';
256             while (isspace(*sep))
257                 sep++;
258             if (*sep != '\0')
259                 reason = sep;
260         }
261
262         /* See if the reason string is already known. */
263         mapped_reason = dict_find(blacklist_reasons, reason, NULL);
264         if (!mapped_reason) {
265             mapped_reason = strdup(reason);
266             dict_insert(blacklist_reasons, mapped_reason, (char*)mapped_reason);
267         }
268
269         /* Store the blacklist entry. */
270         dict_insert(blacklist_hosts, strdup(linebuf), mapped_reason);
271     }
272     fclose(file);
273 }
274
275 static void
276 dnsbl_zone_free(void *pointer)
277 {
278     struct dnsbl_zone *zone;
279     zone = pointer;
280     free(zone->reasons.list);
281     free(zone);
282 }
283
284 static void
285 blacklist_conf_read(void)
286 {
287     dict_t node;
288     dict_t subnode;
289     const char *str1;
290     const char *str2;
291
292     dict_delete(blacklist_zones);
293     blacklist_zones = dict_new();
294     dict_set_free_data(blacklist_zones, dnsbl_zone_free);
295
296     dict_delete(blacklist_hosts);
297     blacklist_hosts = dict_new();
298     dict_set_free_keys(blacklist_hosts, free);
299
300     dict_delete(blacklist_reasons);
301     blacklist_reasons = dict_new();
302     dict_set_free_keys(blacklist_reasons, free);
303
304     node = conf_get_data("modules/blacklist", RECDB_OBJECT);
305     if (node == NULL)
306         return;
307
308     str1 = database_get_data(node, "debug_bot", RECDB_QSTRING);
309     if (str1)
310         conf.debug_bot = GetUserH(str1);
311
312     str1 = database_get_data(node, "debug_channel", RECDB_QSTRING);
313     if (conf.debug_bot && str1) {
314         str2 = database_get_data(node, "debug_channel_modes", RECDB_QSTRING);
315         if (!str2)
316             str2 = "+tinms";
317         conf.debug_channel = AddChannel(str1, now, str2, NULL);
318         AddChannelUser(conf.debug_bot, conf.debug_channel)->modes |= MODE_CHANOP;
319     } else {
320         conf.debug_channel = NULL;
321     }
322
323     str1 = database_get_data(node, "file", RECDB_QSTRING);
324     str2 = database_get_data(node, "file_reason", RECDB_QSTRING);
325     blacklist_load_file(str1, str2);
326
327     str1 = database_get_data(node, "gline_duration", RECDB_QSTRING);
328     if (str1 == NULL)
329         str1 = "1h";
330     conf.gline_duration = ParseInterval(str1);
331
332     subnode = database_get_data(node, "dnsbl", RECDB_OBJECT);
333     if (subnode) {
334         static const char *reason_prefix = "reason_";
335         static const unsigned int max_id = 255;
336         struct dnsbl_zone *zone;
337         dict_iterator_t it;
338         dict_iterator_t it2;
339         dict_t dnsbl;
340         unsigned int id;
341
342         for (it = dict_first(subnode); it; it = iter_next(it)) {
343             dnsbl = GET_RECORD_OBJECT((struct record_data*)iter_data(it));
344             if (!dnsbl)
345                 continue;
346
347             zone = malloc(sizeof(*zone) + strlen(iter_key(it)));
348             strcpy(zone->zone, iter_key(it));
349             zone->description = database_get_data(dnsbl, "description", RECDB_QSTRING);
350             zone->reason = database_get_data(dnsbl, "reason", RECDB_QSTRING);
351             str1 = database_get_data(dnsbl, "duration", RECDB_QSTRING);
352             zone->duration = str1 ? ParseInterval(str1) : 3600;
353             str1 = database_get_data(dnsbl, "mask", RECDB_QSTRING);
354             zone->mask = str1 ? strtoul(str1, NULL, 0) : ~0u;
355             str1 = database_get_data(dnsbl, "debug", RECDB_QSTRING);
356             zone->debug = str1 ? enabled_string(str1) : 0;
357             zone->reasons.used = 0;
358             zone->reasons.size = 0;
359             zone->reasons.list = NULL;
360             dict_insert(blacklist_zones, zone->zone, zone);
361
362             for (it2 = dict_first(dnsbl); it2; it2 = iter_next(it2)) {
363                 str1 = GET_RECORD_QSTRING((struct record_data*)(iter_data(it2)));
364                 if (!str1 || memcmp(iter_key(it2), reason_prefix, strlen(reason_prefix)))
365                     continue;
366                 id = strtoul(iter_key(it2) + strlen(reason_prefix), NULL, 0);
367                 if (id > max_id) {
368                     log_module(bl_log, LOG_ERROR, "Invalid code for DNSBL %s %s -- only %d responses supported.", iter_key(it), iter_key(it2), max_id);
369                     continue;
370                 }
371                 if (zone->reasons.size < id + 1) {
372                     zone->reasons.size = id + 1;
373                     zone->reasons.list = realloc(zone->reasons.list, zone->reasons.size * sizeof(zone->reasons.list[0]));
374                 }
375                 zone->reasons.list[id] = (char*)str1;
376                 if (zone->reasons.used < id + 1)
377                     zone->reasons.used = id + 1;
378             }
379         }
380     }
381 }
382
383 static void
384 blacklist_cleanup(void)
385 {
386     dict_delete(blacklist_zones);
387     dict_delete(blacklist_hosts);
388     dict_delete(blacklist_reasons);
389 }
390
391 int
392 blacklist_init(void)
393 {
394     bl_log = log_register_type("blacklist", "file:blacklist.log");
395     conf_register_reload(blacklist_conf_read);
396     reg_new_user_func(blacklist_check_user);
397     reg_exit_func(blacklist_cleanup);
398     return 1;
399 }
400
401 int
402 blacklist_finalize(void)
403 {
404     return 1;
405 }