1/* $NetBSD$ */ 2 3/*++ 4/* NAME 5/* postscreen_dnsbl 3 6/* SUMMARY 7/* postscreen DNSBL support 8/* SYNOPSIS 9/* #include <postscreen.h> 10/* 11/* void psc_dnsbl_init(void) 12/* 13/* int psc_dnsbl_request(client_addr, callback, context) 14/* char *client_addr; 15/* void (*callback)(int, char *); 16/* char *context; 17/* 18/* int psc_dnsbl_retrieve(client_addr, dnsbl_name, dnsbl_index) 19/* char *client_addr; 20/* const char **dnsbl_name; 21/* int dnsbl_index; 22/* DESCRIPTION 23/* This module implements preliminary support for DNSBL lookups. 24/* Multiple requests for the same information are handled with 25/* reference counts. 26/* 27/* psc_dnsbl_init() initializes this module, and must be called 28/* once before any of the other functions in this module. 29/* 30/* psc_dnsbl_request() requests a blocklist score for the 31/* specified client IP address and increments the reference 32/* count. The request completes in the background. The client 33/* IP address must be in inet_ntop(3) output format. The 34/* callback argument specifies a function that is called when 35/* the requested result is available. The context is passed 36/* on to the callback function. The callback should ignore its 37/* first argument (it exists for compatibility with Postfix 38/* generic event infrastructure). 39/* The result value is the index for the psc_dnsbl_retrieve() 40/* call. 41/* 42/* psc_dnsbl_retrieve() retrieves the result score requested with 43/* psc_dnsbl_request() and decrements the reference count. It 44/* is an error to retrieve a score without requesting it first. 45/* LICENSE 46/* .ad 47/* .fi 48/* The Secure Mailer license must be distributed with this software. 49/* AUTHOR(S) 50/* Wietse Venema 51/* IBM T.J. Watson Research 52/* P.O. Box 704 53/* Yorktown Heights, NY 10598, USA 54/*--*/ 55 56/* System library. */ 57 58#include <sys_defs.h> 59#include <sys/socket.h> /* AF_INET */ 60#include <netinet/in.h> /* inet_pton() */ 61#include <arpa/inet.h> /* inet_pton() */ 62#include <stdio.h> /* sscanf */ 63 64/* Utility library. */ 65 66#include <msg.h> 67#include <mymalloc.h> 68#include <argv.h> 69#include <htable.h> 70#include <events.h> 71#include <vstream.h> 72#include <connect.h> 73#include <split_at.h> 74#include <valid_hostname.h> 75#include <ip_match.h> 76#include <myaddrinfo.h> 77#include <stringops.h> 78 79/* Global library. */ 80 81#include <mail_params.h> 82#include <mail_proto.h> 83 84/* Application-specific. */ 85 86#include <postscreen.h> 87 88 /* 89 * Talking to the DNSBLOG service. 90 */ 91#define DNSBLOG_TIMEOUT 10 92static char *psc_dnsbl_service; 93 94 /* 95 * Per-DNSBL filters and weights. 96 * 97 * The postscreen_dnsbl_sites parameter specifies zero or more DNSBL domains. 98 * We provide multiple access methods, one for quick iteration when sending 99 * queries to all DNSBL servers, and one for quick location when receiving a 100 * reply from one DNSBL server. 101 * 102 * Each DNSBL domain can be specified more than once, each time with a 103 * different (filter, weight) pair. We group (filter, weight) pairs in a 104 * linked list under their DNSBL domain name. The list head has a reference 105 * to a "safe name" for the DNSBL, in case the name includes a password. 106 */ 107static HTABLE *dnsbl_site_cache; /* indexed by DNSBNL domain */ 108static HTABLE_INFO **dnsbl_site_list; /* flattened cache */ 109 110typedef struct { 111 const char *safe_dnsbl; /* from postscreen_dnsbl_reply_map */ 112 struct PSC_DNSBL_SITE *first; /* list of (filter, weight) tuples */ 113} PSC_DNSBL_HEAD; 114 115typedef struct PSC_DNSBL_SITE { 116 char *filter; /* printable filter (default: null) */ 117 char *byte_codes; /* encoded filter (default: null) */ 118 int weight; /* reply weight (default: 1) */ 119 struct PSC_DNSBL_SITE *next; /* linked list */ 120} PSC_DNSBL_SITE; 121 122 /* 123 * Per-client DNSBL scores. 124 * 125 * Some SMTP clients make parallel connections. This can trigger parallel 126 * blocklist score requests when the pre-handshake delays of the connections 127 * overlap. 128 * 129 * We combine requests for the same score under the client IP address in a 130 * single reference-counted entry. The reference count goes up with each 131 * request for a score, and it goes down with each score retrieval. Each 132 * score has one or more requestors that need to be notified when the result 133 * is ready, so that postscreen can terminate a pre-handshake delay when all 134 * pre-handshake tests are completed. 135 */ 136static HTABLE *dnsbl_score_cache; /* indexed by client address */ 137 138typedef struct { 139 void (*callback) (int, char *); /* generic call-back routine */ 140 char *context; /* generic call-back argument */ 141} PSC_CALL_BACK_ENTRY; 142 143typedef struct { 144 const char *dnsbl; /* one contributing DNSBL */ 145 int total; /* combined blocklist score */ 146 int refcount; /* score reference count */ 147 int pending_lookups; /* nr of DNS requests in flight */ 148 int request_id; /* duplicate suppression */ 149 /* Call-back table support. */ 150 int index; /* next table index */ 151 int limit; /* last valid index */ 152 PSC_CALL_BACK_ENTRY table[1]; /* actually a bunch */ 153} PSC_DNSBL_SCORE; 154 155#define PSC_CALL_BACK_INIT(sp) do { \ 156 (sp)->limit = 0; \ 157 (sp)->index = 0; \ 158 } while (0) 159 160#define PSC_CALL_BACK_INDEX_OF_LAST(sp) ((sp)->index - 1) 161 162#define PSC_CALL_BACK_CANCEL(sp, idx) do { \ 163 PSC_CALL_BACK_ENTRY *_cb_; \ 164 if ((idx) < 0 || (idx) >= (sp)->index) \ 165 msg_panic("%s: index %d must be >= 0 and < %d", \ 166 myname, (idx), (sp)->index); \ 167 _cb_ = (sp)->table + (idx); \ 168 event_cancel_timer(_cb_->callback, _cb_->context); \ 169 _cb_->callback = 0; \ 170 _cb_->context = 0; \ 171 } while (0) 172 173#define PSC_CALL_BACK_EXTEND(hp, sp) do { \ 174 if ((sp)->index >= (sp)->limit) { \ 175 int _count_ = ((sp)->limit ? (sp)->limit * 2 : 5); \ 176 (hp)->value = myrealloc((char *) (sp), sizeof(*(sp)) + \ 177 _count_ * sizeof((sp)->table)); \ 178 (sp) = (PSC_DNSBL_SCORE *) (hp)->value; \ 179 (sp)->limit = _count_; \ 180 } \ 181 } while (0) 182 183#define PSC_CALL_BACK_ENTER(sp, fn, ctx) do { \ 184 PSC_CALL_BACK_ENTRY *_cb_ = (sp)->table + (sp)->index++; \ 185 _cb_->callback = (fn); \ 186 _cb_->context = (ctx); \ 187 } while (0) 188 189#define PSC_CALL_BACK_NOTIFY(sp, ev) do { \ 190 PSC_CALL_BACK_ENTRY *_cb_; \ 191 for (_cb_ = (sp)->table; _cb_ < (sp)->table + (sp)->index; _cb_++) \ 192 if (_cb_->callback != 0) \ 193 _cb_->callback((ev), _cb_->context); \ 194 } while (0) 195 196#define PSC_NULL_EVENT (0) 197 198 /* 199 * Per-request state. 200 * 201 * This implementation stores the client IP address and DNSBL domain in the 202 * DNSBLOG query/reply stream. This simplifies code, and allows the DNSBLOG 203 * server to produce more informative logging. 204 */ 205static VSTRING *reply_client; /* client address in DNSBLOG reply */ 206static VSTRING *reply_dnsbl; /* domain in DNSBLOG reply */ 207static VSTRING *reply_addr; /* adress list in DNSBLOG reply */ 208 209/* psc_dnsbl_add_site - add DNSBL site information */ 210 211static void psc_dnsbl_add_site(const char *site) 212{ 213 const char *myname = "psc_dnsbl_add_site"; 214 char *saved_site = mystrdup(site); 215 VSTRING *byte_codes = 0; 216 PSC_DNSBL_HEAD *head; 217 PSC_DNSBL_SITE *new_site; 218 char junk; 219 const char *weight_text; 220 char *pattern_text; 221 int weight; 222 HTABLE_INFO *ht; 223 char *parse_err; 224 225 /* 226 * Parse the required DNSBL domain name, the optional reply filter and 227 * the optional reply weight factor. 228 */ 229#define DO_GRIPE 1 230 231 /* Negative weight means whitelist. */ 232 if ((weight_text = split_at(saved_site, '*')) != 0) { 233 if (sscanf(weight_text, "%d%c", &weight, &junk) != 1) 234 msg_fatal("bad DNSBL weight factor \"%s\" in \"%s\"", 235 weight_text, site); 236 } else { 237 weight = 1; 238 } 239 /* Reply filter. */ 240 if ((pattern_text = split_at(saved_site, '=')) != 0) { 241 byte_codes = vstring_alloc(100); 242 if ((parse_err = ip_match_parse(byte_codes, pattern_text)) != 0) 243 msg_fatal("bad DNSBL filter syntax: %s", parse_err); 244 } 245 if (valid_hostname(saved_site, DO_GRIPE) == 0) 246 msg_fatal("bad DNSBL domain name \"%s\" in \"%s\"", 247 saved_site, site); 248 249 if (msg_verbose > 1) 250 msg_info("%s: \"%s\" -> domain=\"%s\" pattern=\"%s\" weight=%d", 251 myname, site, saved_site, pattern_text ? pattern_text : 252 "null", weight); 253 254 /* 255 * Look up or create the (filter, weight) list head for this DNSBL domain 256 * name. 257 */ 258 if ((head = (PSC_DNSBL_HEAD *) 259 htable_find(dnsbl_site_cache, saved_site)) == 0) { 260 head = (PSC_DNSBL_HEAD *) mymalloc(sizeof(*head)); 261 ht = htable_enter(dnsbl_site_cache, saved_site, (char *) head); 262 /* Translate the DNSBL name into a safe name if available. */ 263 if (psc_dnsbl_reply == 0 264 || (head->safe_dnsbl = dict_get(psc_dnsbl_reply, saved_site)) == 0) 265 head->safe_dnsbl = ht->key; 266 head->first = 0; 267 } 268 269 /* 270 * Append the new (filter, weight) node to the list for this DNSBL domain 271 * name. 272 */ 273 new_site = (PSC_DNSBL_SITE *) mymalloc(sizeof(*new_site)); 274 new_site->filter = (pattern_text ? mystrdup(pattern_text) : 0); 275 new_site->byte_codes = (byte_codes ? ip_match_save(byte_codes) : 0); 276 new_site->weight = weight; 277 new_site->next = head->first; 278 head->first = new_site; 279 280 myfree(saved_site); 281 if (byte_codes) 282 vstring_free(byte_codes); 283} 284 285/* psc_dnsbl_match - match DNSBL reply filter */ 286 287static int psc_dnsbl_match(const char *filter, ARGV *reply) 288{ 289 char addr_buf[MAI_HOSTADDR_STRSIZE]; 290 char **cpp; 291 292 /* 293 * Run the replies through the pattern-matching engine. 294 */ 295 for (cpp = reply->argv; *cpp != 0; cpp++) { 296 if (inet_pton(AF_INET, *cpp, addr_buf) != 1) 297 msg_warn("address conversion error for %s -- ignoring this reply", 298 *cpp); 299 if (ip_match_execute(filter, addr_buf)) 300 return (1); 301 } 302 return (0); 303} 304 305/* psc_dnsbl_retrieve - retrieve blocklist score, decrement reference count */ 306 307int psc_dnsbl_retrieve(const char *client_addr, const char **dnsbl_name, 308 int dnsbl_index) 309{ 310 const char *myname = "psc_dnsbl_retrieve"; 311 PSC_DNSBL_SCORE *score; 312 int result_score; 313 314 /* 315 * Sanity check. 316 */ 317 if ((score = (PSC_DNSBL_SCORE *) 318 htable_find(dnsbl_score_cache, client_addr)) == 0) 319 msg_panic("%s: no blocklist score for %s", myname, client_addr); 320 321 /* 322 * Disable callbacks. 323 */ 324 PSC_CALL_BACK_CANCEL(score, dnsbl_index); 325 326 /* 327 * Reads are destructive. 328 */ 329 result_score = score->total; 330 *dnsbl_name = score->dnsbl; 331 score->refcount -= 1; 332 if (score->refcount < 1) { 333 if (msg_verbose > 1) 334 msg_info("%s: delete blocklist score for %s", myname, client_addr); 335 htable_delete(dnsbl_score_cache, client_addr, myfree); 336 } 337 return (result_score); 338} 339 340/* psc_dnsbl_receive - receive DNSBL reply, update blocklist score */ 341 342static void psc_dnsbl_receive(int event, char *context) 343{ 344 const char *myname = "psc_dnsbl_receive"; 345 VSTREAM *stream = (VSTREAM *) context; 346 PSC_DNSBL_SCORE *score; 347 PSC_DNSBL_HEAD *head; 348 PSC_DNSBL_SITE *site; 349 ARGV *reply_argv; 350 int request_id; 351 352 PSC_CLEAR_EVENT_REQUEST(vstream_fileno(stream), psc_dnsbl_receive, context); 353 354 /* 355 * Receive the DNSBL lookup result. 356 * 357 * This is preliminary code to explore the field. Later, DNSBL lookup will 358 * be handled by an UDP-based DNS client that is built directly into some 359 * Postfix daemon. 360 * 361 * Don't bother looking up the blocklist score when the client IP address is 362 * not listed at the DNSBL. 363 * 364 * Don't panic when the blocklist score no longer exists. It may be deleted 365 * when the client triggers a "drop" action after pregreet, when the 366 * client does not pregreet and the DNSBL reply arrives late, or when the 367 * client triggers a "drop" action after hanging up. 368 */ 369 if (event == EVENT_READ 370 && attr_scan(stream, 371 ATTR_FLAG_STRICT, 372 ATTR_TYPE_STR, MAIL_ATTR_RBL_DOMAIN, reply_dnsbl, 373 ATTR_TYPE_STR, MAIL_ATTR_ACT_CLIENT_ADDR, reply_client, 374 ATTR_TYPE_INT, MAIL_ATTR_LABEL, &request_id, 375 ATTR_TYPE_STR, MAIL_ATTR_RBL_ADDR, reply_addr, 376 ATTR_TYPE_END) == 4 377 && (score = (PSC_DNSBL_SCORE *) 378 htable_find(dnsbl_score_cache, STR(reply_client))) != 0 379 && score->request_id == request_id) { 380 381 /* 382 * Run this response past all applicable DNSBL filters and update the 383 * blocklist score for this client IP address. 384 * 385 * Don't panic when the DNSBL domain name is not found. The DNSBLOG 386 * server may be messed up. 387 */ 388 if (msg_verbose > 1) 389 msg_info("%s: client=\"%s\" score=%d domain=\"%s\" reply=\"%s\"", 390 myname, STR(reply_client), score->total, 391 STR(reply_dnsbl), STR(reply_addr)); 392 if (*STR(reply_addr) != 0) { 393 head = (PSC_DNSBL_HEAD *) 394 htable_find(dnsbl_site_cache, STR(reply_dnsbl)); 395 site = (head ? head->first : (PSC_DNSBL_SITE *) 0); 396 for (reply_argv = 0; site != 0; site = site->next) { 397 if (site->byte_codes == 0 398 || psc_dnsbl_match(site->byte_codes, reply_argv ? reply_argv : 399 (reply_argv = argv_split(STR(reply_addr), " ")))) { 400 if (score->dnsbl == 0) 401 score->dnsbl = head->safe_dnsbl; 402 score->total += site->weight; 403 if (msg_verbose > 1) 404 msg_info("%s: filter=\"%s\" weight=%d score=%d", 405 myname, site->filter ? site->filter : "null", 406 site->weight, score->total); 407 } 408 } 409 if (reply_argv != 0) 410 argv_free(reply_argv); 411 } 412 413 /* 414 * Notify the requestor(s) that the result is ready to be picked up. 415 * If this call isn't made, clients have to sit out the entire 416 * pre-handshake delay. 417 */ 418 score->pending_lookups -= 1; 419 if (score->pending_lookups == 0) 420 PSC_CALL_BACK_NOTIFY(score, PSC_NULL_EVENT); 421 } 422 /* Here, score may be a null pointer. */ 423 vstream_fclose(stream); 424} 425 426/* psc_dnsbl_request - send dnsbl query, increment reference count */ 427 428int psc_dnsbl_request(const char *client_addr, 429 void (*callback) (int, char *), 430 char *context) 431{ 432 const char *myname = "psc_dnsbl_request"; 433 int fd; 434 VSTREAM *stream; 435 HTABLE_INFO **ht; 436 PSC_DNSBL_SCORE *score; 437 HTABLE_INFO *hash_node; 438 static int request_count; 439 440 /* 441 * Some spambots make several connections at nearly the same time, 442 * causing their pregreet delays to overlap. Such connections can share 443 * the efforts of DNSBL lookup. 444 * 445 * We store a reference-counted DNSBL score under its client IP address. We 446 * increment the reference count with each score request, and decrement 447 * the reference count with each score retrieval. 448 * 449 * Do not notify the requestor NOW when the DNS replies are already in. 450 * Reason: we must not make a backwards call while we are still in the 451 * middle of executing the corresponding forward call. Instead we create 452 * a zero-delay timer request and call the notification function from 453 * there. 454 * 455 * psc_dnsbl_request() could instead return a result value to indicate that 456 * the DNSBL score is already available, but that would complicate the 457 * caller with two different notification code paths: one asynchronous 458 * code path via the callback invocation, and one synchronous code path 459 * via the psc_dnsbl_request() result value. That would be a source of 460 * future bugs. 461 */ 462 if ((hash_node = htable_locate(dnsbl_score_cache, client_addr)) != 0) { 463 score = (PSC_DNSBL_SCORE *) hash_node->value; 464 score->refcount += 1; 465 PSC_CALL_BACK_EXTEND(hash_node, score); 466 PSC_CALL_BACK_ENTER(score, callback, context); 467 if (msg_verbose > 1) 468 msg_info("%s: reuse blocklist score for %s refcount=%d pending=%d", 469 myname, client_addr, score->refcount, 470 score->pending_lookups); 471 if (score->pending_lookups == 0) 472 event_request_timer(callback, context, EVENT_NULL_DELAY); 473 return (PSC_CALL_BACK_INDEX_OF_LAST(score)); 474 } 475 if (msg_verbose > 1) 476 msg_info("%s: create blocklist score for %s", myname, client_addr); 477 score = (PSC_DNSBL_SCORE *) mymalloc(sizeof(*score)); 478 score->request_id = request_count++; 479 score->dnsbl = 0; 480 score->total = 0; 481 score->refcount = 1; 482 score->pending_lookups = 0; 483 PSC_CALL_BACK_INIT(score); 484 PSC_CALL_BACK_ENTER(score, callback, context); 485 (void) htable_enter(dnsbl_score_cache, client_addr, (char *) score); 486 487 /* 488 * Send a query to all DNSBL servers. Later, DNSBL lookup will be done 489 * with an UDP-based DNS client that is built directly into Postfix code. 490 * We therefore do not optimize the maximum out of this temporary 491 * implementation. 492 */ 493 for (ht = dnsbl_site_list; *ht; ht++) { 494 if ((fd = LOCAL_CONNECT(psc_dnsbl_service, NON_BLOCKING, 1)) < 0) { 495 msg_warn("%s: connect to %s service: %m", 496 myname, psc_dnsbl_service); 497 continue; 498 } 499 stream = vstream_fdopen(fd, O_RDWR); 500 attr_print(stream, ATTR_FLAG_NONE, 501 ATTR_TYPE_STR, MAIL_ATTR_RBL_DOMAIN, ht[0]->key, 502 ATTR_TYPE_STR, MAIL_ATTR_ACT_CLIENT_ADDR, client_addr, 503 ATTR_TYPE_INT, MAIL_ATTR_LABEL, score->request_id, 504 ATTR_TYPE_END); 505 if (vstream_fflush(stream) != 0) { 506 msg_warn("%s: error sending to %s service: %m", 507 myname, psc_dnsbl_service); 508 vstream_fclose(stream); 509 continue; 510 } 511 PSC_READ_EVENT_REQUEST(vstream_fileno(stream), psc_dnsbl_receive, 512 (char *) stream, DNSBLOG_TIMEOUT); 513 score->pending_lookups += 1; 514 } 515 return (PSC_CALL_BACK_INDEX_OF_LAST(score)); 516} 517 518/* psc_dnsbl_init - initialize */ 519 520void psc_dnsbl_init(void) 521{ 522 const char *myname = "psc_dnsbl_init"; 523 ARGV *dnsbl_site = argv_split(var_psc_dnsbl_sites, ", \t\r\n"); 524 char **cpp; 525 526 /* 527 * Sanity check. 528 */ 529 if (dnsbl_site_cache != 0) 530 msg_panic("%s: called more than once", myname); 531 532 /* 533 * pre-compute the DNSBLOG socket name. 534 */ 535 psc_dnsbl_service = concatenate(MAIL_CLASS_PRIVATE, "/", 536 var_dnsblog_service, (char *) 0); 537 538 /* 539 * Prepare for quick iteration when sending out queries to all DNSBL 540 * servers, and for quick lookup when a reply arrives from a specific 541 * DNSBL server. 542 */ 543 dnsbl_site_cache = htable_create(13); 544 for (cpp = dnsbl_site->argv; *cpp; cpp++) 545 psc_dnsbl_add_site(*cpp); 546 argv_free(dnsbl_site); 547 dnsbl_site_list = htable_list(dnsbl_site_cache); 548 549 /* 550 * The per-client blocklist score. 551 */ 552 dnsbl_score_cache = htable_create(13); 553 554 /* 555 * Space for ad-hoc DNSBLOG server request/reply parameters. 556 */ 557 reply_client = vstring_alloc(100); 558 reply_dnsbl = vstring_alloc(100); 559 reply_addr = vstring_alloc(100); 560} 561