Add rbldns parameter to iplist as an alias for 'file'.
[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(uint16_t) ips[1 << 16];
65 };
66 ARRAY(rbldb_t)
67
68 static int get_o(const char *s, const char **out)
69 {
70     int res = 0;
71
72     if (*s < '0' || *s > '9')
73         return -1;
74
75     res = *s++ - '0';
76     if (*s < '0' || *s > '9')
77         goto ok;
78
79     res = res * 10 + *s++ - '0';
80     if (*s < '0' || *s > '9')
81         goto ok;
82
83     res = res * 10 + *s++ - '0';
84     if (!(*s < '0' || *s > '9') || res < 100)
85         return -1;
86
87   ok:
88     *out = s;
89     return res;
90 }
91
92 static int parse_ipv4(const char *s, const char **out, uint32_t *ip)
93 {
94     int o;
95
96     o = get_o(s, &s);
97     if ((o & ~0xff) || *s++ != '.')
98         return -1;
99     *ip = o << 24;
100
101     o = get_o(s, &s);
102     if ((o & ~0xff) || *s++ != '.')
103         return -1;
104     *ip |= o << 16;
105
106     o = get_o(s, &s);
107     if ((o & ~0xff) || *s++ != '.')
108         return -1;
109     *ip |= o << 8;
110
111     o = get_o(s, &s);
112     if (o & ~0xff)
113         return -1;
114     *ip |= o;
115
116     *out = s;
117     return 0;
118 }
119
120 rbldb_t *rbldb_create(const char *file, bool lock)
121 {
122     rbldb_t *db;
123     file_map_t map;
124     const char *p, *end;
125     uint32_t ips = 0;
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 >> 16], ip & 0xffff);
152             ++ips;
153         }
154     }
155     file_map_close(&map);
156
157     /* Lookup may perform serveral I/O, so avoid swap.
158      */
159     for (int i = 0 ; i < 1 << 16 ; ++i) {
160         array_adjust(db->ips[i]);
161         if (lock && !array_lock(db->ips[i])) {
162             UNIXERR("mlock");
163         }
164         if (db->ips[i].len) {
165 #       define QSORT_TYPE uint16_t
166 #       define QSORT_BASE db->ips[i].data
167 #       define QSORT_NELT db->ips[i].len
168 #       define QSORT_LT(a,b) *a < *b
169 #       include "qsort.c"
170         }
171     }
172
173     info("rbl %s loaded, %d IPs", file, ips);
174     return db;
175 }
176
177 static void rbldb_wipe(rbldb_t *db)
178 {
179     for (int i = 0 ; i < 1 << 16 ; ++i) {
180         array_wipe(db->ips[i]);
181     }
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     uint32_t ips = 0;
195     for (int i = 0 ; i < 1 << 16 ; ++i) {
196         ips += array_len(rbl->ips[i]);
197     }
198     return ips;
199 }
200
201 bool rbldb_ipv4_lookup(const rbldb_t *db, uint32_t ip)
202 {
203     const uint16_t hip = ip >> 16;
204     const uint16_t lip = ip & 0xffff;
205     int l = 0, r = db->ips[hip].len;
206
207     while (l < r) {
208         int i = (r + l) / 2;
209
210         if (array_elt(db->ips[hip], i) == lip)
211             return true;
212
213         if (lip < array_elt(db->ips[hip], i)) {
214             r = i;
215         } else {
216             l = i + 1;
217         }
218     }
219     return false;
220 }
221
222
223 /* postlicyd filter declaration */
224
225 #include "filter.h"
226
227 typedef struct rbl_filter_t {
228     PA(rbldb_t) rbls;
229     A(int)      weights;
230
231     int32_t     hard_threshold;
232     int32_t     soft_threshold;
233 } rbl_filter_t;
234
235 static rbl_filter_t *rbl_filter_new(void)
236 {
237     return p_new(rbl_filter_t, 1);
238 }
239
240 static void rbl_filter_delete(rbl_filter_t **rbl)
241 {
242     if (*rbl) {
243         array_deep_wipe((*rbl)->rbls, rbldb_delete);
244         array_wipe((*rbl)->weights);
245         p_delete(rbl);
246     }
247 }
248
249
250 static bool rbl_filter_constructor(filter_t *filter)
251 {
252     rbl_filter_t *data = rbl_filter_new();
253
254 #define PARSE_CHECK(Expr, Str, ...)                                            \
255     if (!(Expr)) {                                                             \
256         err(Str, ##__VA_ARGS__);                                               \
257         rbl_filter_delete(&data);                                              \
258         return false;                                                          \
259     }
260
261     data->hard_threshold = 1;
262     data->soft_threshold = 1;
263     foreach (filter_param_t *param, filter->params) {
264         switch (param->type) {
265           /* file parameter is:
266            *  [no]lock:weight:filename
267            *  valid options are:
268            *    - lock:   memlock the database in memory.
269            *    - nolock: don't memlock the database in memory [default].
270            *    - \d+:    a number describing the weight to give to the match
271            *              the given list [mandatory]
272            *  the file pointed by filename MUST be a valid ip list issued from
273            *  the rsync (or equivalent) service of a (r)bl.
274            */
275           case ATK_FILE: case ATK_RBLDNS: {
276             bool lock = false;
277             int  weight = 0;
278             rbldb_t *rbl = NULL;
279             const char *current = param->value;
280             const char *p = m_strchrnul(param->value, ':');
281             char *next = NULL;
282             for (int i = 0 ; i < 3 ; ++i) {
283                 PARSE_CHECK(i == 2 || *p,
284                             "file parameter must contains a locking state "
285                             "and a weight option");
286                 switch (i) {
287                   case 0:
288                     if ((p - current) == 4 && strncmp(current, "lock", 4) == 0) {
289                         lock = true;
290                     } else if ((p - current) == 6
291                                && strncmp(current, "nolock", 6) == 0) {
292                         lock = false;
293                     } else {
294                         PARSE_CHECK(false, "illegal locking state %.*s",
295                                     p - current, current);
296                     }
297                     break;
298
299                   case 1:
300                     weight = strtol(current, &next, 10);
301                     PARSE_CHECK(next == p && weight >= 0 && weight <= 1024,
302                                 "illegal weight value %.*s",
303                                 (p - current), current);
304                     break;
305
306                   case 2:
307                     rbl = rbldb_create(current, lock);
308                     PARSE_CHECK(rbl != NULL,
309                                 "cannot load rbl db from %s", current);
310                     array_add(data->rbls, rbl);
311                     array_add(data->weights, weight);
312                     break;
313                 }
314                 if (i != 2) {
315                     current = p + 1;
316                     p = m_strchrnul(current, ':');
317                 }
318             }
319           } break;
320
321           /* hard_threshold parameter is an integer.
322            *  If the matching score is greater or equal than this threshold,
323            *  the hook "hard_match" is called.
324            * hard_threshold = 1 means, that all matches are hard matches.
325            * default is 1;
326            */
327           FILTER_PARAM_PARSE_INT(HARD_THRESHOLD, data->hard_threshold);
328
329           /* soft_threshold parameter is an integer.
330            *  if the matching score is greater or equal than this threshold
331            *  and smaller or equal than the hard_threshold, the hook "soft_match"
332            *  is called.
333            * default is 1;
334            */
335           FILTER_PARAM_PARSE_INT(SOFT_THRESHOLD, data->soft_threshold);
336
337           default: break;
338         }
339     }}
340
341     PARSE_CHECK(data->rbls.len, 
342                 "no file parameter in the filter %s", filter->name);
343     filter->data = data;
344     return true;
345 }
346
347 static void rbl_filter_destructor(filter_t *filter)
348 {
349     rbl_filter_t *data = filter->data;
350     rbl_filter_delete(&data);
351     filter->data = data;
352 }
353
354 static filter_result_t rbl_filter(const filter_t *filter, const query_t *query)
355 {
356     uint32_t ip;
357     int32_t sum = 0;
358     const char *end = NULL;
359     const rbl_filter_t *data = filter->data;
360
361     if (parse_ipv4(query->client_address, &end, &ip) != 0) {
362         warn("invalid client address: %s, expected ipv4",
363              query->client_address);
364         return HTK_ERROR;
365     }
366     for (uint32_t i = 0 ; i < data->rbls.len ; ++i) {
367         const rbldb_t *rbl = array_elt(data->rbls, i);
368         int weight   = array_elt(data->weights, i);
369         if (rbldb_ipv4_lookup(rbl, ip)) {
370             sum += weight;
371         }
372     }
373     if (sum >= data->hard_threshold) {
374         return HTK_HARD_MATCH;
375     } else if (sum >= data->soft_threshold) {
376         return HTK_SOFT_MATCH;
377     } else {
378         return HTK_FAIL;
379     }
380 }
381
382 static int rbl_init(void)
383 {
384     filter_type_t type =  filter_register("iplist", rbl_filter_constructor,
385                                           rbl_filter_destructor, rbl_filter);
386     /* Hooks.
387      */
388     (void)filter_hook_register(type, "abort");
389     (void)filter_hook_register(type, "error");
390     (void)filter_hook_register(type, "fail");
391     (void)filter_hook_register(type, "hard_match");
392     (void)filter_hook_register(type, "soft_match");
393
394     /* Parameters.
395      */
396     (void)filter_param_register(type, "file");
397     (void)filter_param_register(type, "rbldns");
398     (void)filter_param_register(type, "hard_threshold");
399     (void)filter_param_register(type, "soft_threshold");
400     return 0;
401 }
402 module_init(rbl_init);