5267bf6908fbf4c575dc62212d431b11ba205039
[apps/pfixtools.git] / postlicyd / rbl.c
1 /******************************************************************************/
2 /*          pfixtools: a collection of postfix related tools                  */
3 /*          ~~~~~~~~~                                                         */
4 /*  ________________________________________________________________________  */
5 /*                                                                            */
6 /*  Redistribution and use in source and binary forms, with or without        */
7 /*  modification, are permitted provided that the following conditions        */
8 /*  are met:                                                                  */
9 /*                                                                            */
10 /*  1. Redistributions of source code must retain the above copyright         */
11 /*     notice, this list of conditions and the following disclaimer.          */
12 /*  2. Redistributions in binary form must reproduce the above copyright      */
13 /*     notice, this list of conditions and the following disclaimer in the    */
14 /*     documentation and/or other materials provided with the distribution.   */
15 /*  3. The names of its contributors may not be used to endorse or promote    */
16 /*     products derived from this software without specific prior written     */
17 /*     permission.                                                            */
18 /*                                                                            */
19 /*  THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND   */
20 /*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE     */
21 /*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR        */
22 /*  PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS    */
23 /*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR    */
24 /*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF      */
25 /*  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS  */
26 /*  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN   */
27 /*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)   */
28 /*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF    */
29 /*  THE POSSIBILITY OF SUCH DAMAGE.                                           */
30 /******************************************************************************/
31
32 /*
33  * Copyright © 2007 Pierre Habouzit
34  * Copyright © 2008 Florent Bruneau
35  */
36
37 #include <arpa/inet.h>
38 #include <netinet/in.h>
39 #include <sys/mman.h>
40
41 #include "common.h"
42 #include "rbl.h"
43 #include "str.h"
44 #include "file.h"
45 #include "array.h"
46
47 #define IPv4_BITS        5
48 #define IPv4_PREFIX(ip)  ((uint32_t)(ip) >> IPv4_BITS)
49 #define IPv4_SUFFIX(ip)  ((uint32_t)(ip) & ((1 << IPv4_BITS) - 1))
50 #define NODE(db, i)      ((db)->tree + (i))
51 #ifndef DEBUG
52 #define DEBUG(...)
53 #endif
54
55 /* Implementation */
56
57 enum {
58     BALANCED    = 0,
59     LEFT_HEAVY  = 1,
60     RIGHT_HEAVY = 2,
61 };
62
63 struct rbldb_t {
64     A(uint32_t) ips;
65     bool        locked;
66 };
67 ARRAY(rbldb_t)
68
69 static int get_o(const char *s, const char **out)
70 {
71     int res = 0;
72
73     if (*s < '0' || *s > '9')
74         return -1;
75
76     res = *s++ - '0';
77     if (*s < '0' || *s > '9')
78         goto ok;
79
80     res = res * 10 + *s++ - '0';
81     if (*s < '0' || *s > '9')
82         goto ok;
83
84     res = res * 10 + *s++ - '0';
85     if (!(*s < '0' || *s > '9') || res < 100)
86         return -1;
87
88   ok:
89     *out = s;
90     return res;
91 }
92
93 static int parse_ipv4(const char *s, const char **out, uint32_t *ip)
94 {
95     int o;
96
97     o = get_o(s, &s);
98     if ((o & ~0xff) || *s++ != '.')
99         return -1;
100     *ip = o << 24;
101
102     o = get_o(s, &s);
103     if ((o & ~0xff) || *s++ != '.')
104         return -1;
105     *ip |= o << 16;
106
107     o = get_o(s, &s);
108     if ((o & ~0xff) || *s++ != '.')
109         return -1;
110     *ip |= o << 8;
111
112     o = get_o(s, &s);
113     if (o & ~0xff)
114         return -1;
115     *ip |= o;
116
117     *out = s;
118     return 0;
119 }
120
121 rbldb_t *rbldb_create(const char *file, bool lock)
122 {
123     rbldb_t *db;
124     file_map_t map;
125     const char *p, *end;
126
127     if (!file_map_open(&map, file, false)) {
128         return NULL;
129     }
130
131     p   = map.map;
132     end = map.end;
133     while (end > p && end[-1] != '\n') {
134         --end;
135     }
136     if (end != map.end) {
137         syslog(LOG_WARNING, "file %s miss a final \\n, ignoring last line",
138                file);
139     }
140
141     db = p_new(rbldb_t, 1);
142     while (p < end) {
143         uint32_t ip;
144
145         while (*p == ' ' || *p == '\t' || *p == '\r')
146             p++;
147
148         if (parse_ipv4(p, &p, &ip) < 0) {
149             p = (char *)memchr(p, '\n', end - p) + 1;
150         } else {
151             array_add(db->ips, ip);
152         }
153     }
154     file_map_close(&map);
155
156     /* Lookup may perform serveral I/O, so avoid swap.
157      */
158     array_adjust(db->ips);
159     db->locked = lock && array_lock(db->ips);
160     if (lock && !db->locked) {
161         UNIXERR("mlock");
162     }
163
164     if (db->ips.len) {
165 #       define QSORT_TYPE uint32_t
166 #       define QSORT_BASE db->ips.data
167 #       define QSORT_NELT db->ips.len
168 #       define QSORT_LT(a,b) *a < *b
169 #       include "qsort.c"
170     }
171
172     syslog(LOG_INFO, "rbl %s loaded, %d IPs", file, db->ips.len);
173     return db;
174 }
175
176 static void rbldb_wipe(rbldb_t *db)
177 {
178     if (db->locked) {
179       array_unlock(db->ips);
180     }
181     array_wipe(db->ips);
182 }
183
184 void rbldb_delete(rbldb_t **db)
185 {
186     if (*db) {
187         rbldb_wipe(*db);
188         p_delete(&(*db));
189     }
190 }
191
192 uint32_t rbldb_stats(const rbldb_t *rbl)
193 {
194     return rbl->ips.len;
195 }
196
197 bool rbldb_ipv4_lookup(const rbldb_t *db, uint32_t ip)
198 {
199     int l = 0, r = db->ips.len;
200
201     while (l < r) {
202         int i = (r + l) / 2;
203
204         if (array_elt(db->ips, i) == ip)
205             return true;
206
207         if (ip < array_elt(db->ips, i)) {
208             r = i;
209         } else {
210             l = i + 1;
211         }
212     }
213     return false;
214 }
215
216
217 /* postlicyd filter declaration */
218
219 #include "filter.h"
220
221 typedef struct rbl_filter_t {
222     PA(rbldb_t) rbls;
223     A(int)      weights;
224
225     int32_t     hard_threshold;
226     int32_t     soft_threshold;
227 } rbl_filter_t;
228
229 static rbl_filter_t *rbl_filter_new(void)
230 {
231     return p_new(rbl_filter_t, 1);
232 }
233
234 static void rbl_filter_delete(rbl_filter_t **rbl)
235 {
236     if (*rbl) {
237         array_deep_wipe((*rbl)->rbls, rbldb_delete);
238         array_wipe((*rbl)->weights);
239         p_delete(rbl);
240     }
241 }
242
243
244 static bool rbl_filter_constructor(filter_t *filter)
245 {
246     rbl_filter_t *data = rbl_filter_new();
247
248 #define PARSE_CHECK(Expr, Str, ...)                                            \
249     if (!(Expr)) {                                                             \
250         syslog(LOG_ERR, Str, ##__VA_ARGS__);                                   \
251         rbl_filter_delete(&data);                                              \
252         return false;                                                          \
253     }
254
255     foreach (filter_params_t *param, filter->params) {
256         /* file parameter is:
257          *  [no]lock:weight:filename
258          *  valid options are:
259          *    - lock:   memlock the database in memory.
260          *    - nolock: don't memlock the database in memory [default].
261          *    - \d+:    a number describing the weight to give to the match
262          *              the given list [mandatory]
263          *  the file pointed by filename MUST be a valid ip list issued from
264          *  the rsync (or equivalent) service of a (r)bl.
265          */
266         if (strcmp(param->name, "file") == 0) {
267             bool lock = false;
268             int  weight = 0;
269             rbldb_t *rbl = NULL;
270             const char *current = param->value;
271             const char *p = m_strchrnul(param->value, ':');
272             char *next = NULL;
273             for (int i = 0 ; i < 3 ; ++i) {
274                 PARSE_CHECK(i == 2 || *p, 
275                             "file parameter must contains a locking state and a weight option");
276                 switch (i) {
277                   case 0:
278                     if ((p - current) == 4 && strncmp(current, "lock", 4) == 0) {
279                         lock = true;
280                     } else if ((p - current) == 6 && strncmp(current, "nolock", 6) == 0) {
281                         lock = false;
282                     } else {
283                         PARSE_CHECK(false, "illegal locking state %.*s",
284                                     p - current, current);
285                     }
286                     break;
287
288                   case 1:
289                     weight = strtol(current, &next, 10);
290                     PARSE_CHECK(next == p && weight >= 0 && weight <= 1024,
291                                 "illegal weight value %.*s",
292                                 (p - current), current);
293                     break;
294
295                   case 2:
296                     rbl = rbldb_create(current, lock);
297                     PARSE_CHECK(rbl != NULL,
298                                 "cannot load rbl db from %s", current);
299                     array_add(data->rbls, rbl);
300                     array_add(data->weights, weight);
301                     break;
302                 }
303                 current = p + 1;
304                 p = m_strchrnul(current, ':');
305             }
306
307         /* hard_threshold parameter is an integer.
308          *  If the matching score of a ip get a score gretter than this threshold,
309          *  the hook "hard_match" is called.
310          * hard_threshold = 0 means, that all matches are hard matches.
311          * default is 0;
312          */
313         } else if (strcmp(param->name, "hard_threshold") == 0) {
314             char *next;
315             data->hard_threshold = strtol(param->value, &next, 10);
316             PARSE_CHECK(*next, "invalid threshold value %s", param->value);
317
318         /* soft_threshold parameter is an integer.
319          *  if the matching score of an ip get a score getter than this threshold
320          *  and smaller or equal than the hard_threshold, the hook "soft_match"
321          *  is called.
322          * default is 0;
323          */
324         } else if (strcmp(param->name, "hard_threshold") == 0) {
325             char *next;
326             data->soft_threshold = strtol(param->value, &next, 10);
327             PARSE_CHECK(*next, "invalid threshold value %s", param->value);
328
329         } else {
330             syslog(LOG_INFO, "ignored parameter %s in rbl filter %s",
331                    filter->name, param->name);
332         }
333     }}
334
335     PARSE_CHECK(data->rbls.len, 
336                 "no file parameter in the filter %s", filter->name);
337     filter->data = data;
338     return true;
339 }
340
341 static void rbl_filter_destructor(filter_t *filter)
342 {
343     rbl_filter_t *data = filter->data;
344     rbl_filter_delete(&data);
345     filter->data = data;
346 }
347
348 static filter_result_t rbl_filter(const filter_t *filter, const query_t *query)
349 {
350     uint32_t ip;
351     int32_t sum = 0;
352     const char *end = NULL;
353     const rbl_filter_t *data = filter->data;
354
355     if (parse_ipv4(query->client_address, &end, &ip) != 0) {
356         syslog(LOG_WARNING, "invalid client address: %s, expected ipv4",
357                query->client_address);
358         return HTK_ERROR;
359     }
360     for (int i = 0 ; i < data->rbls.len ; ++i) {
361         const rbldb_t *rbl = array_elt(data->rbls, i);
362         int weight   = array_elt(data->weights, i);
363         if (rbldb_ipv4_lookup(rbl, ip)) {
364             sum += weight;
365         }
366     }
367     if (sum > data->hard_threshold) {
368         return HTK_HARD_MATCH;
369     } else if (sum > data->soft_threshold) {
370         return HTK_SOFT_MATCH;
371     } else {
372         return HTK_FAIL;
373     }
374 }
375
376 static int rbl_init(void)
377 {
378     filter_type_t type =  filter_register("rbl", rbl_filter_constructor,
379                                           rbl_filter_destructor, rbl_filter);
380     (void)filter_hook_register(type, "error");
381     (void)filter_hook_register(type, "fail");
382     (void)filter_hook_register(type, "hard_match");
383     (void)filter_hook_register(type, "soft_match");
384     return 0;
385 }
386 module_init(rbl_init);