Add support for rbl by dns resolution.
[apps/pfixtools.git] / postlicyd / iplist.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 "iplist.h"
43 #include "str.h"
44 #include "file.h"
45 #include "array.h"
46 #include "rbl.h"
47
48 #define IPv4_BITS        5
49 #define IPv4_PREFIX(ip)  ((uint32_t)(ip) >> IPv4_BITS)
50 #define IPv4_SUFFIX(ip)  ((uint32_t)(ip) & ((1 << IPv4_BITS) - 1))
51 #define NODE(db, i)      ((db)->tree + (i))
52 #ifndef DEBUG
53 #define DEBUG(...)
54 #endif
55
56 /* Implementation */
57
58 enum {
59     BALANCED    = 0,
60     LEFT_HEAVY  = 1,
61     RIGHT_HEAVY = 2,
62 };
63
64 struct rbldb_t {
65     A(uint32_t) ips;
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         warn("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     if (lock && !array_lock(db->ips)) {
160         UNIXERR("mlock");
161     }
162
163     if (db->ips.len) {
164 #       define QSORT_TYPE uint32_t
165 #       define QSORT_BASE db->ips.data
166 #       define QSORT_NELT db->ips.len
167 #       define QSORT_LT(a,b) *a < *b
168 #       include "qsort.c"
169     }
170
171     info("rbl %s loaded, %d IPs", file, db->ips.len);
172     return db;
173 }
174
175 static void rbldb_wipe(rbldb_t *db)
176 {
177     array_wipe(db->ips);
178 }
179
180 void rbldb_delete(rbldb_t **db)
181 {
182     if (*db) {
183         rbldb_wipe(*db);
184         p_delete(&(*db));
185     }
186 }
187
188 uint32_t rbldb_stats(const rbldb_t *rbl)
189 {
190     return rbl->ips.len;
191 }
192
193 bool rbldb_ipv4_lookup(const rbldb_t *db, uint32_t ip)
194 {
195     int l = 0, r = db->ips.len;
196
197     while (l < r) {
198         int i = (r + l) / 2;
199
200         if (array_elt(db->ips, i) == ip)
201             return true;
202
203         if (ip < array_elt(db->ips, i)) {
204             r = i;
205         } else {
206             l = i + 1;
207         }
208     }
209     return false;
210 }
211
212
213 /* postlicyd filter declaration */
214
215 #include "filter.h"
216
217 typedef struct rbl_filter_t {
218     PA(rbldb_t) rbls;
219     A(int)      weights;
220     A(char)     hosts;
221     A(int)      host_offsets;
222     A(int)      host_weights;
223
224     int32_t     hard_threshold;
225     int32_t     soft_threshold;
226 } rbl_filter_t;
227
228 static rbl_filter_t *rbl_filter_new(void)
229 {
230     return p_new(rbl_filter_t, 1);
231 }
232
233 static void rbl_filter_delete(rbl_filter_t **rbl)
234 {
235     if (*rbl) {
236         array_deep_wipe((*rbl)->rbls, rbldb_delete);
237         array_wipe((*rbl)->weights);
238         array_wipe((*rbl)->hosts);
239         array_wipe((*rbl)->host_offsets);
240         array_wipe((*rbl)->host_weights);
241         p_delete(rbl);
242     }
243 }
244
245
246 static bool rbl_filter_constructor(filter_t *filter)
247 {
248     rbl_filter_t *data = rbl_filter_new();
249
250 #define PARSE_CHECK(Expr, Str, ...)                                            \
251     if (!(Expr)) {                                                             \
252         err(Str, ##__VA_ARGS__);                                               \
253         rbl_filter_delete(&data);                                              \
254         return false;                                                          \
255     }
256
257     data->hard_threshold = 1;
258     data->soft_threshold = 1;
259     foreach (filter_param_t *param, filter->params) {
260         switch (param->type) {
261           /* file parameter is:
262            *  [no]lock:weight:filename
263            *  valid options are:
264            *    - lock:   memlock the database in memory.
265            *    - nolock: don't memlock the database in memory [default].
266            *    - \d+:    a number describing the weight to give to the match
267            *              the given list [mandatory]
268            *  the file pointed by filename MUST be a valid ip list issued from
269            *  the rsync (or equivalent) service of a (r)bl.
270            */
271           case ATK_FILE: {
272             bool lock = false;
273             int  weight = 0;
274             rbldb_t *rbl = NULL;
275             const char *current = param->value;
276             const char *p = m_strchrnul(param->value, ':');
277             char *next = NULL;
278             for (int i = 0 ; i < 3 ; ++i) {
279                 PARSE_CHECK(i == 2 || *p,
280                             "file parameter must contains a locking state "
281                             "and a weight option");
282                 switch (i) {
283                   case 0:
284                     if ((p - current) == 4 && strncmp(current, "lock", 4) == 0) {
285                         lock = true;
286                     } else if ((p - current) == 6
287                                && strncmp(current, "nolock", 6) == 0) {
288                         lock = false;
289                     } else {
290                         PARSE_CHECK(false, "illegal locking state %.*s",
291                                     p - current, current);
292                     }
293                     break;
294
295                   case 1:
296                     weight = strtol(current, &next, 10);
297                     PARSE_CHECK(next == p && weight >= 0 && weight <= 1024,
298                                 "illegal weight value %.*s",
299                                 (p - current), current);
300                     break;
301
302                   case 2:
303                     rbl = rbldb_create(current, lock);
304                     PARSE_CHECK(rbl != NULL,
305                                 "cannot load rbl db from %s", current);
306                     array_add(data->rbls, rbl);
307                     array_add(data->weights, weight);
308                     break;
309                 }
310                 if (i != 2) {
311                     current = p + 1;
312                     p = m_strchrnul(current, ':');
313                 }
314             }
315           } break;
316
317           /* host parameter.
318            *  weight:hostname.
319            * define a RBL to use through DNS resolution.
320            */
321           case ATK_HOST: {
322             int  weight = 0;
323             const char *current = param->value;
324             const char *p = m_strchrnul(param->value, ':');
325             char *next = NULL;
326             for (int i = 0 ; i < 2 ; ++i) {
327                 PARSE_CHECK(i == 1 || *p,
328                             "host parameter must contains a weight option");
329                 switch (i) {
330                   case 0:
331                     weight = strtol(current, &next, 10);
332                     PARSE_CHECK(next == p && weight >= 0 && weight <= 1024,
333                                 "illegal weight value %.*s",
334                                 (p - current), current);
335                     break;
336
337                   case 1:
338                     array_add(data->host_offsets, array_len(data->hosts));
339                     array_append(data->hosts, current, strlen(current) + 1);
340                     array_add(data->host_weights, weight);
341                     break;
342                 }
343                 if (i != 1) {
344                     current = p + 1;
345                     p = m_strchrnul(current, ':');
346                 }
347             }
348           } break;
349
350           /* hard_threshold parameter is an integer.
351            *  If the matching score is greater or equal than this threshold,
352            *  the hook "hard_match" is called.
353            * hard_threshold = 1 means, that all matches are hard matches.
354            * default is 1;
355            */
356           FILTER_PARAM_PARSE_INT(HARD_THRESHOLD, data->hard_threshold);
357
358           /* soft_threshold parameter is an integer.
359            *  if the matching score is greater or equal than this threshold
360            *  and smaller or equal than the hard_threshold, the hook "soft_match"
361            *  is called.
362            * default is 1;
363            */
364           FILTER_PARAM_PARSE_INT(SOFT_THRESHOLD, data->soft_threshold);
365
366           default: break;
367         }
368     }}
369
370     PARSE_CHECK(data->rbls.len, 
371                 "no file parameter in the filter %s", filter->name);
372     filter->data = data;
373     return true;
374 }
375
376 static void rbl_filter_destructor(filter_t *filter)
377 {
378     rbl_filter_t *data = filter->data;
379     rbl_filter_delete(&data);
380     filter->data = data;
381 }
382
383 static filter_result_t rbl_filter(const filter_t *filter, const query_t *query)
384 {
385     uint32_t ip;
386     int32_t sum = 0;
387     const char *end = NULL;
388     const rbl_filter_t *data = filter->data;
389     bool  error = true;
390
391     if (parse_ipv4(query->client_address, &end, &ip) != 0) {
392         warn("invalid client address: %s, expected ipv4",
393              query->client_address);
394         return HTK_ERROR;
395     }
396     for (uint32_t i = 0 ; i < data->rbls.len ; ++i) {
397         const rbldb_t *rbl = array_elt(data->rbls, i);
398         int weight   = array_elt(data->weights, i);
399         if (rbldb_ipv4_lookup(rbl, ip)) {
400             sum += weight;
401             if (sum >= data->hard_threshold) {
402                 return HTK_HARD_MATCH;
403             }
404         }
405         error = false;
406     }
407     for (uint32_t i = 0 ; i < data->host_offsets.len ; ++i) {
408         const char *rbl = array_ptr(data->hosts, array_elt(data->host_offsets, i));
409         int weight      = array_elt(data->host_weights, i);
410         switch (rbl_check(rbl, ip)) {
411           case RBL_FOUND:
412             error = false;
413             sum += weight;
414             if (sum >= data->hard_threshold) {
415                 return HTK_HARD_MATCH;
416             }
417             break;
418           case RBL_NOTFOUND:
419             error = false;
420             break;
421           case RBL_ERROR:
422             warn("rbl %s unavailable", rbl);
423             break;
424         }
425     }
426     if (error) {
427         err("filter %s: all the rbl returned an error", filter->name);
428         return HTK_ERROR;
429     }
430     if (sum >= data->hard_threshold) {
431         return HTK_HARD_MATCH;
432     } else if (sum >= data->soft_threshold) {
433         return HTK_SOFT_MATCH;
434     } else {
435         return HTK_FAIL;
436     }
437 }
438
439 static int rbl_init(void)
440 {
441     filter_type_t type =  filter_register("iplist", rbl_filter_constructor,
442                                           rbl_filter_destructor, rbl_filter);
443     /* Hooks.
444      */
445     (void)filter_hook_register(type, "abort");
446     (void)filter_hook_register(type, "error");
447     (void)filter_hook_register(type, "fail");
448     (void)filter_hook_register(type, "hard_match");
449     (void)filter_hook_register(type, "soft_match");
450
451     /* Parameters.
452      */
453     (void)filter_param_register(type, "file");
454     (void)filter_param_register(type, "host");
455     (void)filter_param_register(type, "hard_threshold");
456     (void)filter_param_register(type, "soft_threshold");
457     return 0;
458 }
459 module_init(rbl_init);