~sirn/fanboi2

ref: 834edf0edc5dd633c0ecea16231b6ed2d728476d fanboi2/fanboi2/filters/dnsbl.py -rw-r--r-- 1.2 KiB
834edf0eKridsada Thanabulpong Massive cleanup in preparation for 0.30 (#25) 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import socket
from ipaddress import ip_interface, ip_network

from . import register_filter


@register_filter(name='dnsbl')
class DNSBL(object):
    """Utility class for checking IP address against DNSBL providers."""

    __default_settings__ = (
        'proxies.dnsbl.sorbs.net',
        'xbl.spamhaus.org',
    )

    def __init__(self, providers, services={}):
        if not providers:
            providers = tuple()
        self.providers = tuple(providers)

    def should_reject(self, payload):
        """Returns :type:`True` if the given IP address is listed in the
        DNSBL providers. Returns :type:`False` if not listed or no DNSBL
        providers present.

        :param payload: A filter payload.
        """
        for provider in self.providers:
            try:
                check = '.'.join(reversed(payload['ip_address'].split('.')))
                res = socket.gethostbyname("%s.%s." % (check, provider))
                ipaddr = ip_interface("%s/255.0.0.0" % (res,))
                if ipaddr.network == ip_network('127.0.0.0/8'):
                    return True
            except (socket.gaierror, ValueError):
                continue
        return False