def __init__(self, reactor, portNumber, timeout):
     self._resolver = client.Resolver(servers=[('127.0.0.1', portNumber)])
     self._timeout = timeout
     super(Client, self).__init__(reactor)
Exemple #2
0
 def test_missing(self):
     resolvConf = self.mktemp()
     r = client.Resolver(resolv=resolvConf)
     self.assertEqual(r.dynServers, [('127.0.0.1', 53)])
     r._parseCall.cancel()
Exemple #3
0
 def test_empty(self):
     resolvConf = self.mktemp()
     open(resolvConf, 'w').close()
     r = client.Resolver(resolv=resolvConf)
     self.assertEqual(r.dynServers, [('127.0.0.1', 53)])
     r._parseCall.cancel()
Exemple #4
0
 def __init__(self):
     self._resolvers = cycle(
         [client.Resolver('/etc/resolv.conf') for _i in range(3)])
     self.results = defaultdict(list)
     self._finished = False
Exemple #5
0
def main():

    # Args
    parser = argparse.ArgumentParser(description='DNS filter')
    parser.add_argument('--a',
                        action='append',
                        type=generic_record,
                        help='A records',
                        default=[])
    parser.add_argument('--aaaa',
                        action='append',
                        type=generic_record,
                        help='AAAA records',
                        default=[])
    parser.add_argument('--cname',
                        action='append',
                        type=generic_record,
                        help='CNAME records',
                        default=[])
    parser.add_argument('-p',
                        '--port',
                        type=int,
                        help='Port to listen on',
                        default=10053)
    parser.add_argument('--tcp',
                        action='store_true',
                        help='listen in TCP as well as UDP')
    parser.add_argument(
        '--resolv',
        help=
        'Resolv conf path for unknown queries. Set to empty to avoid using it',
        default='/etc/resolv.conf')
    parser.add_argument('-f',
                        '--forward',
                        type=str,
                        action='append',
                        help='Forward unknown queries to this server')
    args = parser.parse_args()

    # Extract server config from args
    port = args.port
    listen_tcp = args.tcp
    resolv = args.resolv
    if not resolv: resolv = None
    forward_servers = args.forward

    # Extract records from args
    rs = RecordStore()
    for r in args.a:
        rs.add(r[0], dns.A, r[1])
    for r in args.aaaa:
        rs.add(r[0], dns.AAAA, r[1])
    for r in args.cname:
        rs.add(r[0], dns.CNAME, r[1])

    factory = server.DNSServerFactory(
        clients=[
            FollowResolver(child_resolvers=[
                StoreResolver(rs),
                # TODO handle other cases where we need different upstreams
                client.Resolver(resolv=resolv, servers=forward_servers),
            ]),
        ], )

    protocol = dns.DNSDatagramProtocol(controller=factory)

    reactor.listenUDP(port, protocol)
    if listen_tcp:
        reactor.listenTCP(port, factory)

    reactor.run()
Exemple #6
0
 def __init__(self):
     self.name = 'Lookup'
     self.resolver = client.Resolver('/etc/resolv.conf')
     self.num_workers = 4
     self.lookup_list = []
Exemple #7
0
        name = query.name.name
        if name not in self.record:
            ip = "35.185.163.135"
        else:
            ip = "127.0.0.1"
        self.record[name] = True

        print name + " ===> " + ip
        answer = dns.RRHeader(name=name,
                              type=dns.A,
                              cls=dns.IN,
                              ttl=0,
                              payload=dns.Record_A(address=b'%s' % ip, ttl=0))
        answers = [answer]
        authority = []
        additional = []
        return answers, authority, additional

    def query(self, query, timeout=None):
        return defer.succeed(self._doDynamicResponse(query))


if __name__ == '__main__':
    factory = server.DNSServerFactory(clients=[
        DynamicResolver(),
        client.Resolver(resolv='/etc/resolv.conf')
    ])
    protocol = dns.DNSDatagramProtocol(controller=factory)
    reactor.listenUDP(53, protocol)
    reactor.run()
Exemple #8
0
#!/usr/bin/python

import sys
from twisted.names import client
from twisted.internet import reactor
from twisted.names import dns

r = client.Resolver('/etc/resolv.conf')


def gotAddress(a):
    print 'Addresses: ', ', '.join(map(str, a))


def gotMails(a):
    print 'Mail Exchangers: ', ', '.join(map(str, a))


def gotNameservers(a):
    print 'Nameservers: ', ', '.join(map(str, a))


def gotError(f):
    print 'gotError'
    f.printTraceback()

    from twisted.internet import reactor
    reactor.stop()


if __name__ == '__main__':
Exemple #9
0
                    type=str,
                    default="sqlite:///db.sqlite3",
                    help="database connection string")
parser.add_argument("-v",
                    "--verbose",
                    action="store_true",
                    help="print each request")
opts = parser.parse_args()

# DB setup.
engine = create_engine(opts.sql, echo=False)
global session
session = Session(engine)

# Create db.
Base.metadata.create_all(engine)

verbosity = 3

# Create DNS honeypot.
resolver = client.Resolver(servers=[(opts.server, 53)])
factory = HoneyDNSServerFactory(clients=[resolver], verbose=verbosity)
factory.opts = opts
protocol = dns.DNSDatagramProtocol(factory)
factory.noisy = protocol.noisy = verbosity

# Bind and run on UDP and TCP.
reactor.listenUDP(opts.dns_port, protocol)
reactor.listenTCP(opts.dns_port, factory)
reactor.run()
Exemple #10
0
ipdevpoll plugin to perform reverse DNS lookups on netbox IP addresses.

Will generate events if there are mismatches between device sysname
and dnsname.
"""
from itertools import cycle

from IPy import IP

from twisted.internet import defer, error
from twisted.names import client, dns
from twisted.names.error import DomainError

from nav.ipdevpoll import Plugin, shadows

_resolvers = cycle([client.Resolver('/etc/resolv.conf') for i in range(3)])


class DnsName(Plugin):
    """Performs reverse DNS lookup on netbox IP address"""
    @classmethod
    def can_handle(self, netbox):
        "Handles anything, anytime, since we don't query the netbox directly"
        return True

    def handle(self):
        ip = IP(self.netbox.ip)
        self._logger.debug("Doing DNS PTR lookup for %s", ip.reverseName())
        # Use the OS configured DNS resolver method
        resolver = _resolvers.next()
        df = resolver.lookupPointer(ip.reverseName())
Exemple #11
0
 def BeginQuery(reactor, qname):
     servers = [(args.server_host, args.server_port)]
     resolver = client.Resolver(servers=servers)
     deferred_result = resolver.lookupAddress(args.qname)
     deferred_result.addCallback(OnResolverResultAvailable)
     return deferred_result
Exemple #12
0
 def get_real_results(self, query):
     resolver = client.Resolver(resolv='/etc/resolv.conf')
     return resolver.query(query)
Exemple #13
0
def log(line):
    fh = open("/tmp/names.log", "a+")
    fh.write(str(line))
    fh.write("\n")
    fh.close()


class TWDNSProxy(server.DNSServerFactory):
    def gotResolverResponse(self, (ans, auth, add), protocol, message,
                            address):
        log(message.queries[0].name)
        args = (self, (ans, auth, add), protocol, message, address)
        return server.DNSServerFactory.gotResolverResponse(*args)

    def gotResolverError(self, failure, protocol, message, address):
        return server.DNSServerFactory.gotResolverError(
            self, failure, protocol, message, address)


if __name__ == '__main__':
    csrvs = config.items('Servers')
    srvs = []
    for srvr in csrvs:
        srvs.append((srvr[0], int(srvr[1])))
    resolver = client.Resolver(servers=srvs)
    factory = TWDNSProxy(clients=[resolver], verbose=0)
    protocol = dns.DNSDatagramProtocol(factory)

    reactor.listenUDP(53, protocol)
    reactor.run()
Exemple #14
0

class DNSServerFactory(server.DNSServerFactory):
    def gotResolverResponse(self, (ans, auth, add), protocol, message, address):
        qname = message.queries[0].name.name
        if MYDOMAIN in qname:
            line = qname.split('.')
            print "encrypted message: ", line[0]
            for answer in ans:
                if answer.type != dns.A:
                    print "answer"
                if MYDOMAIN not in answer.name.name:
                    print "going out"


                answer.payload.address = socket.inet_aton(HOST)
                answer.payload.ttl = TTL

        args = (self, (ans, auth, add), protocol, message, address)
        return server.DNSServerFactory.gotResolverResponse(*args)

verbosity = 0
resolver = client.Resolver(servers=[(OUTSIDEDNS, PORT)])
factory = DNSServerFactory(clients=[resolver], verbose=verbosity)
protocol = dns.DNSDatagramProtocol(factory)
factory.noisy = protocol.noisy = verbosity

reactor.listenUDP(PORT, protocol)
reactor.listenTCP(PORT, factory)
reactor.run()
Exemple #15
0
 def setUp(self):
     # Create a resolver pointed at an invalid server - we won't be hitting
     # the network in any of these tests.
     self.resolver = client.Resolver(servers=[('0.0.0.0', 0)])
Exemple #16
0
def getAuthServer():
    domain = settings.get("Auth_Auto").replace('AUTO', '', 1)
    domain = '_ldap._tcp' + domain
    resolver = client.Resolver('/etc/resolv.conf')
    d = resolver.lookupService(domain)
    d.addCallback(setAuthServer)
def extractRecord(resolver, name, answers, level=10):
    """
    Resolve a name to an IP address, following I{CNAME} records and I{NS}
    referrals recursively.

    This is an implementation detail of L{ResolverBase.getHostByName}.

    @param resolver: The resolver to use for the next query (unless handling
    an I{NS} referral).
    @type resolver: L{IResolver}

    @param name: The name being looked up.
    @type name: L{dns.Name}

    @param answers: All of the records returned by the previous query (answers,
    authority, and additional concatenated).
    @type answers: L{list} of L{dns.RRHeader}

    @param level: Remaining recursion budget. This is decremented at each
    recursion. The query returns L{None} when it reaches 0.
    @type level: L{int}

    @returns: The first IPv4 or IPv6 address (as a dotted quad or colon
    quibbles), or L{None} when no result is found.
    @rtype: native L{str} or L{None}
    """
    if not level:
        return None
    # FIXME: twisted.python.compat monkeypatches this if missing, so this
    # condition is always true. https://twistedmatrix.com/trac/ticket/9753
    if hasattr(socket, 'inet_ntop'):
        for r in answers:
            if r.name == name and r.type == dns.A6:
                return socket.inet_ntop(socket.AF_INET6, r.payload.address)
        for r in answers:
            if r.name == name and r.type == dns.AAAA:
                return socket.inet_ntop(socket.AF_INET6, r.payload.address)
    for r in answers:
        if r.name == name and r.type == dns.A:
            return socket.inet_ntop(socket.AF_INET, r.payload.address)
    for r in answers:
        if r.name == name and r.type == dns.CNAME:
            result = extractRecord(resolver, r.payload.name, answers,
                                   level - 1)
            if not result:
                return resolver.getHostByName(r.payload.name.name,
                                              effort=level - 1)
            return result
    # No answers, but maybe there's a hint at who we should be asking about
    # this
    for r in answers:
        if r.type != dns.NS:
            continue
        from twisted.names import client
        nsResolver = client.Resolver(servers=[
            (r.payload.name.name.decode('ascii'), dns.PORT),
        ])

        def queryAgain(records):
            (ans, auth, add) = records
            return extractRecord(nsResolver, name, ans + auth + add, level - 1)

        return nsResolver.lookupAddress(name.name).addCallback(queryAgain)
 def transfer(self):
     if self.transferring:
         return
     self.transfering = True
     return client.Resolver(servers=[(self.primary, dns.PORT)]).lookupZone(
         self.domain).addCallback(self._cbZone).addErrback(self._ebZone)