1 /******************************************************************************/
2 /* pfixtools: a collection of postfix related tools */
4 /* ________________________________________________________________________ */
6 /* Redistribution and use in source and binary forms, with or without */
7 /* modification, are permitted provided that the following conditions */
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 */
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 /******************************************************************************/
33 * Copyright © 2007 Pierre Habouzit
42 typedef struct greylist_config_t {
43 unsigned lookup_by_host : 1;
53 #define GREYLIST_INIT { .lookup_by_host = false, \
55 .retry_window = 2 * 24 * 3600, \
57 .max_age = 35 * 3600, \
71 static inline bool greylist_check_awlentry(const greylist_config_t *config,
72 struct awl_entry *aent, time_t now)
74 return !(config->max_age > 0 && now - aent->last > config->max_age);
77 static inline bool greylist_check_object(const greylist_config_t *config,
78 const struct obj_entry *oent, time_t now)
80 return !((config->max_age > 0 && now - oent->last > config->max_age)
81 || (oent->last - oent->first < config->delay
82 && now - oent->last > config->retry_window));
85 typedef bool (*db_entry_checker_t)(const greylist_config_t *, const void *, time_t);
87 static TCBDB *greylist_db_get(const greylist_config_t *config,
88 const char *path, bool cleanup,
89 size_t entry_len, db_entry_checker_t check)
91 TCBDB *awl_db, *tmp_db;
92 time_t now = time(NULL);
94 /* Rebuild a new database after removing too old entries.
96 if (cleanup && config->max_age > 0) {
97 uint32_t old_count = 0;
98 uint32_t new_count = 0;
100 bool trashable = false;
101 char tmppath[PATH_MAX];
102 snprintf(tmppath, PATH_MAX, "%s.tmp", path);
104 syslog(LOG_INFO, "database cleanup started");
106 if (tcbdbopen(awl_db, path, BDBOREADER)) {
108 if (tcbdbopen(tmp_db, tmppath, BDBOWRITER | BDBOCREAT | BDBOTRUNC)) {
109 BDBCUR *cur = tcbdbcurnew(awl_db);
114 if (tcbdbcurfirst(cur)) {
119 (void)tcbdbcurrec(cur, key, value);
121 if ((size_t)tcxstrsize(value) == entry_len
122 && check(config, tcxstrptr(value), now)) {
123 tcbdbput(tmp_db, tcxstrptr(key), tcxstrsize(key),
124 tcxstrptr(value), entry_len);
128 } while (tcbdbcurnext(cur));
135 syslog(LOG_ERR, "cannot run database cleanup: can't open destination database: %s",
136 tcbdberrmsg(tcbdbecode(awl_db)));
140 int ecode = tcbdbecode(awl_db);
141 syslog(LOG_ERR, "can not open database: %s", tcbdberrmsg(ecode));
142 trashable = ecode != TCENOPERM && ecode != TCEOPEN && ecode != TCENOFILE && ecode != TCESUCCESS;
146 /** Cleanup successful, replace the old database with the new one.
149 syslog(LOG_INFO, "database cleanup finished: database was corrupted, create a new one");
151 } else if (replace) {
152 syslog(LOG_INFO, "database cleanup finished: before %u entries, after %d entries",
153 old_count, new_count);
155 if (rename(tmppath, path) != 0) {
160 syslog(LOG_INFO, "database cleanup finished: nothing to do, %u entries", new_count);
164 /* Effectively open the database.
167 if (!tcbdbopen(awl_db, path, BDBOWRITER | BDBOCREAT)) {
168 syslog(LOG_ERR, "can not open database: %s", tcbdberrmsg(tcbdbecode(awl_db)));
176 static bool greylist_initialize(greylist_config_t *config,
177 const char *directory, const char *prefix)
181 if (config->client_awl) {
182 snprintf(path, sizeof(path), "%s/%swhitelist.db", directory, prefix);
183 syslog(LOG_INFO, "loading auto-whitelist database");
184 config->awl_db = greylist_db_get(config, path, true,
185 sizeof(struct awl_entry),
186 (db_entry_checker_t)(greylist_check_awlentry));
187 if (config->awl_db == NULL) {
192 snprintf(path, sizeof(path), "%s/%sgreylist.db", directory, prefix);
193 syslog(LOG_INFO, "loading greylist database");
194 config->obj_db = greylist_db_get(config, path, true,
195 sizeof(struct obj_entry),
196 (db_entry_checker_t)(greylist_check_object));
197 if (config->obj_db == NULL) {
198 if (config->awl_db) {
199 tcbdbdel(config->awl_db);
200 config->awl_db = NULL;
208 static void greylist_shutdown(greylist_config_t *config)
210 if (config->awl_db) {
211 tcbdbsync(config->awl_db);
212 tcbdbdel(config->awl_db);
213 config->awl_db = NULL;
215 if (config->obj_db) {
216 tcbdbsync(config->obj_db);
217 tcbdbdel(config->obj_db);
218 config->obj_db = NULL;
222 static const char *sender_normalize(const char *sender, char *buf, int len)
224 const char *at = strchr(sender, '@');
225 int rpos = 0, wpos = 0, userlen;
230 /* strip extension used for VERP or alike */
231 userlen = ((char *)memchr(sender, '+', at - sender) ?: at) - sender;
233 while (rpos < userlen) {
236 while (isdigit(sender[rpos + count]) && rpos + count < userlen)
238 if (count && !isalnum(sender[rpos + count])) {
239 /* replace \<\d+\> with '#' */
240 wpos += m_strputc(buf + wpos, len - wpos, '#');
244 while (isalnum(sender[rpos + count]) && rpos + count < userlen)
246 while (!isalnum(sender[rpos + count]) && rpos + count < userlen)
248 wpos += m_strncpy(buf + wpos, len - wpos, sender + rpos, count);
252 wpos += m_strputc(buf + wpos, len - wpos, '#');
253 wpos += m_strcpy(buf + wpos, len - wpos, at + 1);
257 static const char *c_net(const greylist_config_t *config,
258 const char *c_addr, const char *c_name,
259 char *cnet, int cnetlen)
264 if (config->lookup_by_host)
267 if (!(dot = strchr(c_addr, '.')))
269 if (!(dot = strchr(dot + 1, '.')))
273 if (!(dot = strchr(dot, '.')) || dot - p > 3)
275 m_strncpy(ip2, sizeof(ip2), p, dot - p);
278 if (!(dot = strchr(dot, '.')) || dot - p > 3)
280 m_strncpy(ip3, sizeof(ip3), p, dot - p);
282 /* skip if contains the last two ip numbers in the hostname,
283 we assume it's a pool of dialup of a provider */
284 if (strstr(c_name, ip2) && strstr(c_name, ip3))
287 m_strncpy(cnet, cnetlen, c_addr, dot - c_addr);
292 static bool try_greylist(const greylist_config_t *config,
293 const char *sender, const char *c_addr,
294 const char *c_name, const char *rcpt)
299 tcbdbput(config->awl_db, c_addr, c_addrlen, &aent, \
302 char sbuf[BUFSIZ], cnet[64], key[BUFSIZ];
305 time_t now = time(NULL);
306 struct obj_entry oent = { now, now };
307 struct awl_entry aent = { 0, 0 };
309 int len, klen, c_addrlen = strlen(c_addr);
311 /* Auto whitelist clients.
313 if (config->client_awl) {
314 res = tcbdbget3(config->awl_db, c_addr, c_addrlen, &len);
315 if (res && len == sizeof(aent)) {
316 memcpy(&aent, res, len);
319 if (!greylist_check_awlentry(config, &aent, now)) {
324 /* Whitelist if count is enough.
326 if (aent.count >= config->client_awl) {
327 if (now < aent.last + 3600) {
333 //syslog(LOG_INFO, "client whitelisted");
340 klen = snprintf(key, sizeof(key), "%s/%s/%s",
341 c_net(config, c_addr, c_name, cnet, sizeof(cnet)),
342 sender_normalize(sender, sbuf, sizeof(sbuf)), rcpt);
343 klen = MIN(klen, ssizeof(key) - 1);
345 res = tcbdbget3(config->obj_db, key, klen, &len);
346 if (res && len == sizeof(oent)) {
347 memcpy(&oent, res, len);
348 greylist_check_object(config, &oent, now);
351 /* Discard stored first-seen if it is the first retrial and
352 * it is beyong the retry window and too old entries.
354 if (!greylist_check_object(config, &oent, now)) {
361 tcbdbput(config->obj_db, key, klen, &oent, sizeof(oent));
363 /* Auto whitelist clients:
365 * - on successful entry in the greylist db of a triplet:
366 * - client not whitelisted yet ? -> increase count
367 * -> withelist if count > limit
368 * - client whitelisted already ? -> update last-seen timestamp.
370 if (oent.first + config->delay < now) {
371 if (config->client_awl) {
377 //syslog(LOG_INFO, "client whitelisted");
383 //syslog(LOG_INFO, "client greylisted");
388 /* postlicyd filter declaration */
392 static greylist_config_t *greylist_config_new(void)
394 const greylist_config_t g = GREYLIST_INIT;
395 greylist_config_t *config = p_new(greylist_config_t, 1);
400 static void greylist_config_delete(greylist_config_t **config)
403 greylist_shutdown(*config);
408 static bool greylist_filter_constructor(filter_t *filter)
410 const char* path = NULL;
411 const char* prefix = NULL;
412 greylist_config_t *config = greylist_config_new();
414 #define PARSE_CHECK(Expr, Str, ...) \
416 syslog(LOG_ERR, Str, ##__VA_ARGS__); \
417 greylist_config_delete(&config); \
421 foreach (filter_param_t *param, filter->params) {
422 switch (param->type) {
423 FILTER_PARAM_PARSE_STRING(PATH, path);
424 FILTER_PARAM_PARSE_STRING(PREFIX, prefix);
425 FILTER_PARAM_PARSE_BOOLEAN(LOOKUP_BY_HOST, config->lookup_by_host);
426 FILTER_PARAM_PARSE_INT(RETRY_WINDOW, config->retry_window);
427 FILTER_PARAM_PARSE_INT(CLIENT_AWL, config->client_awl);
428 FILTER_PARAM_PARSE_INT(DELAY, config->delay);
429 FILTER_PARAM_PARSE_INT(MAX_AGE, config->max_age);
435 PARSE_CHECK(path, "path to greylist db not given");
436 PARSE_CHECK(greylist_initialize(config, path, prefix ? prefix : ""),
437 "can not load greylist database");
439 filter->data = config;
443 static void greylist_filter_destructor(filter_t *filter)
445 greylist_config_t *data = filter->data;
446 greylist_config_delete(&data);
450 static filter_result_t greylist_filter(const filter_t *filter,
451 const query_t *query)
453 const greylist_config_t *config = filter->data;
454 if (query->state != SMTP_RCPT) {
455 syslog(LOG_WARNING, "greylisting only works as smtpd_recipient_restrictions");
459 return try_greylist(config, query->sender, query->client_address,
460 query->client_name, query->recipient) ?
461 HTK_WHITELIST : HTK_GREYLIST;
464 static int greylist_init(void)
466 filter_type_t type = filter_register("greylist", greylist_filter_constructor,
467 greylist_filter_destructor,
471 (void)filter_hook_register(type, "abort");
472 (void)filter_hook_register(type, "error");
473 (void)filter_hook_register(type, "greylist");
474 (void)filter_hook_register(type, "whitelist");
478 (void)filter_param_register(type, "lookup_by_host");
479 (void)filter_param_register(type, "delay");
480 (void)filter_param_register(type, "retry_window");
481 (void)filter_param_register(type, "client_awl");
482 (void)filter_param_register(type, "max_age");
483 (void)filter_param_register(type, "path");
484 (void)filter_param_register(type, "prefix");
487 module_init(greylist_init)