Greylist filter.
[apps/pfixtools.git] / postlicyd / greylist.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  */
35
36 #include <tcbdb.h>
37
38 #include "common.h"
39 #include "str.h"
40
41
42 typedef struct greylist_config_t {
43     unsigned lookup_by_host : 1;
44     int delay;
45     int retry_window;
46     int client_awl;
47
48     TCBDB *awl_db;
49     TCBDB *obj_db;
50 } greylist_config_t;
51
52 #define GREYLIST_INIT { .lookup_by_host = false,       \
53                         .delay = 300,                  \
54                         .retry_window = 2 * 24 * 2600, \
55                         .client_awl = 5,               \
56                         .awl_db = NULL,                \
57                         .obj_db = NULL }
58
59 struct awl_entry {
60     int32_t count;
61     time_t  last;
62 };
63
64 struct obj_entry {
65     time_t first;
66     time_t last;
67 };
68
69
70 static bool greylist_initialize(greylist_config_t *config,
71                                 const char *directory, const char *prefix)
72 {
73     char path[PATH_MAX];
74
75     if (config->client_awl) {
76         snprintf(path, sizeof(path), "%s/%swhitelist.db", directory, prefix);
77         config->awl_db = tcbdbnew();
78         if (!tcbdbopen(config->awl_db, path, BDBOWRITER | BDBOCREAT)) {
79             tcbdbdel(config->awl_db);
80             config->awl_db = NULL;
81         }
82         return false;
83     }
84
85     snprintf(path, sizeof(path), "%s/%sgreylist.db", directory, prefix);
86     config->obj_db = tcbdbnew();
87     if (!tcbdbopen(config->obj_db, path, BDBOWRITER | BDBOCREAT)) {
88         tcbdbdel(config->obj_db);
89         config->obj_db = NULL;
90         if (config->awl_db) {
91             tcbdbdel(config->awl_db);
92             config->awl_db = NULL;
93         }
94         return false;
95     }
96
97     return true;
98 }
99
100 static void greylist_shutdown(greylist_config_t *config)
101 {
102     if (config->awl_db) {
103         tcbdbsync(config->awl_db);
104         tcbdbdel(config->awl_db);
105         config->awl_db = NULL;
106     }
107     if (config->obj_db) {
108         tcbdbsync(config->obj_db);
109         tcbdbdel(config->obj_db);
110         config->obj_db = NULL;
111     }
112 }
113
114 static const char *sender_normalize(const char *sender, char *buf, int len)
115 {
116     const char *at = strchr(sender, '@');
117     int rpos = 0, wpos = 0, userlen;
118
119     if (!at)
120         return sender;
121
122     /* strip extension used for VERP or alike */
123     userlen = ((char *)memchr(sender, '+', at - sender) ?: at) - sender;
124
125     while (rpos < userlen) {
126         int count = 0;
127
128         while (isdigit(sender[rpos + count]) && rpos + count < userlen)
129             count++;
130         if (count && !isalnum(sender[rpos + count])) {
131             /* replace \<\d+\> with '#' */
132             wpos += m_strputc(buf + wpos, len - wpos, '#');
133             rpos += count;
134             count = 0;
135         }
136         while (isalnum(sender[rpos + count]) && rpos + count < userlen)
137             count++;
138         while (!isalnum(sender[rpos + count]) && rpos + count < userlen)
139             count++;
140         wpos += m_strncpy(buf + wpos, len - wpos, sender + rpos, count);
141         rpos += count;
142     }
143
144     wpos += m_strputc(buf + wpos, len - wpos, '#');
145     wpos += m_strcpy(buf + wpos, len - wpos, at + 1);
146     return buf;
147 }
148
149 static const char *c_net(const greylist_config_t *config,
150                          const char *c_addr, const char *c_name,
151                          char *cnet, int cnetlen)
152 {
153     char ip2[4], ip3[4];
154     const char *dot, *p;
155
156     if (config->lookup_by_host)
157         return c_addr;
158
159     if (!(dot = strchr(c_addr, '.')))
160         return c_addr;
161     if (!(dot = strchr(dot + 1, '.')))
162         return c_addr;
163
164     p = ++dot;
165     if (!(dot = strchr(dot, '.')) || dot - p > 3)
166         return c_addr;
167     m_strncpy(ip2, sizeof(ip2), p, dot - p);
168
169     p = ++dot;
170     if (!(dot = strchr(dot, '.')) || dot - p > 3)
171         return c_addr;
172     m_strncpy(ip3, sizeof(ip3), p, dot - p);
173
174     /* skip if contains the last two ip numbers in the hostname,
175        we assume it's a pool of dialup of a provider */
176     if (strstr(c_name, ip2) && strstr(c_name, ip3))
177         return c_addr;
178
179     m_strncpy(cnet, cnetlen, c_addr, dot - c_addr);
180     return cnet;
181 }
182
183 static bool try_greylist(const greylist_config_t *config,
184                          const char *sender, const char *c_addr,
185                          const char *c_name, const char *rcpt)
186 {
187 #define INCR_AWL                                              \
188     aent.count++;                                             \
189     aent.last = now;                                          \
190     tcbdbput(config->awl_db, c_addr, c_addrlen, &aent,        \
191              sizeof(aent));
192
193     char sbuf[BUFSIZ], cnet[64], key[BUFSIZ];
194     const void *res;
195
196     time_t now = time(NULL);
197     struct obj_entry oent = { now, now };
198     struct awl_entry aent = { 0, 0 };
199
200     int len, klen, c_addrlen = strlen(c_addr);
201
202     /* Auto whitelist clients.
203      */
204     if (config->client_awl) {
205         res = tcbdbget3(config->awl_db, c_addr, c_addrlen, &len);
206         if (res && len == sizeof(aent)) {
207             memcpy(&aent, res, len);
208         }
209
210         /* Whitelist if count is enough.
211          */
212         if (aent.count > config->client_awl) {
213             if (now < aent.last + 3600) {
214                 INCR_AWL
215             }
216
217             /* OK.
218              */
219             return true;
220         }
221     }
222
223     /* Lookup.
224      */
225     klen = snprintf(key, sizeof(key), "%s/%s/%s",
226                     c_net(config, c_addr, c_name, cnet, sizeof(cnet)),
227                     sender_normalize(sender, sbuf, sizeof(sbuf)), rcpt);
228     klen = MIN(klen, ssizeof(key) - 1);
229
230     res = tcbdbget3(config->obj_db, key, klen, &len);
231     if (res && len == sizeof(oent)) {
232         memcpy(&oent, res, len);
233     }
234
235     /* Discard stored first-seen if it is the first retrial and
236      * it is beyong the retry window.
237      */
238     if (oent.last - oent.first < config->delay
239         &&  now - oent.first > config->retry_window) {
240         oent.first = now;
241     }
242
243     /* Update.
244      */
245     oent.last = now;
246     tcbdbput(config->obj_db, key, klen, &oent, sizeof(oent));
247
248     /* Auto whitelist clients:
249      *  algorithm:
250      *    - on successful entry in the greylist db of a triplet:
251      *        - client not whitelisted yet ? -> increase count
252      *                                       -> withelist if count > limit
253      *        - client whitelisted already ? -> update last-seen timestamp.
254      */
255     if (oent.first + config->delay < now) {
256         if (config->client_awl) {
257             INCR_AWL
258         }
259
260         /* OK
261          */
262         return true;
263     }
264
265     /* DUNNO
266      */
267     return false;
268 }
269
270
271 /* postlicyd filter declaration */
272
273 #include "filter.h"
274
275 static greylist_config_t *greylist_config_new(void)
276 {
277     const greylist_config_t g = GREYLIST_INIT;
278     greylist_config_t *config = p_new(greylist_config_t, 1);
279     *config = g;
280     return config;
281 }
282
283 static void greylist_config_delete(greylist_config_t **config)
284 {
285     if (*config) {
286         greylist_shutdown(*config);
287         p_delete(config);
288     }
289 }
290
291 static bool greylist_filter_constructor(filter_t *filter)
292 {
293     const char* path   = NULL;
294     const char* prefix = NULL;
295     greylist_config_t *config = greylist_config_new();
296
297 #define PARSE_CHECK(Expr, Str, ...)                                            \
298     if (!(Expr)) {                                                             \
299         syslog(LOG_ERR, Str, ##__VA_ARGS__);                                   \
300         greylist_config_delete(&config);                                       \
301         return false;                                                          \
302     }
303
304     foreach (filter_param_t *param, filter->params) {
305         switch (param->type) {
306           case ATK_PATH:
307             path = param->value;
308             break;
309
310           case ATK_PREFIX:
311             prefix = param->value;
312             break;
313
314           case ATK_LOOKUP_BY_HOST:
315             config->lookup_by_host = (atoi(param->value) != 0);
316             break;
317
318           case ATK_RETRY_WINDOW:
319             config->retry_window = atoi(param->value);
320             break;
321
322           case ATK_CLIENT_AWL:
323             config->client_awl = atoi(param->value);
324             break;
325
326           default: break;
327         }
328     }}
329
330     PARSE_CHECK(path, "path to greylist db not given");
331     PARSE_CHECK(greylist_initialize(config, path, prefix ? prefix : ""),
332                 "can not load greylist database");
333
334     filter->data = config;
335     return true;
336 }
337
338 static void greylist_filter_destructor(filter_t *filter)
339 {
340     greylist_config_t *data = filter->data;
341     greylist_config_delete(&data);
342     filter->data = data;
343 }
344
345 static filter_result_t greylist_filter(const filter_t *filter,
346                                        const query_t *query)
347 {
348     const greylist_config_t *config = filter->data;
349     return try_greylist(config, query->sender, query->client_address,
350                         query->client_name, query->recipient) ?
351            HTK_MATCH : HTK_FAIL;
352 }
353
354 static int greylist_init(void)
355 {
356     filter_type_t type =  filter_register("greylist", greylist_filter_constructor,
357                                           greylist_filter_destructor,
358                                           greylist_filter);
359     /* Hooks.
360      */
361     (void)filter_hook_register(type, "error");
362     (void)filter_hook_register(type, "fail");
363     (void)filter_hook_register(type, "match");
364
365     /* Parameters.
366      */
367     (void)filter_param_register(type, "lookup_by_host");
368     (void)filter_param_register(type, "delay");
369     (void)filter_param_register(type, "retry_window");
370     (void)filter_param_register(type, "client_awl");
371     (void)filter_param_register(type, "path");
372     (void)filter_param_register(type, "prefix");
373     return 0;
374 }
375 module_init(greylist_init)