Python dnslib.QTYPE Examples

The following are 13 code examples of dnslib.QTYPE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dnslib , or try the search function .
Example #1
Source File: subbrute.py    From AttackSurfaceMapper with GNU General Public License v3.0 5 votes vote down vote up
def query(self, hostname, query_type='ANY', name_server=False, use_tcp=False):
        ret = []
        response = None
        if name_server == False:
            name_server = self.get_ns()
        else:
            self.wildcards = {}
            self.failed_code = None
        self.last_resolver = name_server
        query = dnslib.DNSRecord.question(hostname, query_type.upper().strip())
        try:
            response_q = query.send(name_server, 53, use_tcp, timeout=30)
            if response_q:
                response = dnslib.DNSRecord.parse(response_q)
            else:
                raise IOError("Empty Response")
        except Exception as e:
            # IOErrors are all conditions that require a retry.
            raise IOError(str(e))
        if response:
            self.rcode = dnslib.RCODE[response.header.rcode]
            for r in response.rr:
                try:
                    rtype = str(dnslib.QTYPE[r.rtype])
                except:  # Server sent an unknown type:
                    rtype = str(r.rtype)
                # Fully qualified domains may cause problems for other tools that use subbrute's output.
                rhost = str(r.rname).rstrip(".")
                ret.append((rhost, rtype, str(r.rdata)))
            # What kind of response did we get?
            if self.rcode not in ['NOERROR', 'NXDOMAIN', 'SERVFAIL', 'REFUSED']:
                trace('!Odd error code:', self.rcode, hostname, query_type)
            # Is this a perm error?  We will have to retry to find out.
            if self.rcode in ['SERVFAIL', 'REFUSED', 'FORMERR', 'NOTIMP', 'NOTAUTH']:
                raise IOError('DNS Failure: ' + hostname + " - " + self.rcode)
            # Did we get an empty body and a non-error code?
            elif not len(ret) and self.rcode != "NXDOMAIN":
                raise IOError("DNS Error - " + self.rcode + " - for:" + hostname)
        return ret 
Example #2
Source File: Resolver.py    From Vaile with GNU General Public License v3.0 5 votes vote down vote up
def query(self, hostname, query_type = 'ANY', name_server = False, use_tcp = True):
        ret = []
        response = None
        if name_server == False:
            name_server = self.get_ns()
        else:
            self.wildcards = {}
            self.failed_code = None
        self.last_resolver = name_server
        query = dnslib.DNSRecord.question(hostname, query_type.upper().strip())
        try:
            response_q = query.send(name_server, 53, use_tcp)
            if response_q:
                response = dnslib.DNSRecord.parse(response_q)
            else:
                raise IOError("Empty Response")
        except Exception as e:
            #IOErrors are all conditions that require a retry.
            raise IOError(str(e))
        if response:
            self.rcode = dnslib.RCODE[response.header.rcode]
            for r in response.rr:
                try:
                    rtype = str(dnslib.QTYPE[r.rtype])
                except:#Server sent an unknown type:
                    rtype = str(r.rtype)
                #Fully qualified domains may cause problems for other tools that use subbrute's output.
                rhost = str(r.rname).rstrip(".")
                ret.append((rhost, rtype, str(r.rdata)))
            #What kind of response did we get?
            if self.rcode not in ['NOERROR', 'NXDOMAIN', 'SERVFAIL', 'REFUSED']:
                trace('!Odd error code:', self.rcode, hostname, query_type)
            #Is this a perm error?  We will have to retry to find out.
            if self.rcode in ['SERVFAIL', 'REFUSED', 'FORMERR', 'NOTIMP', 'NOTAUTH']:
                raise IOError('DNS Failure: ' + hostname + " - " + self.rcode)
            #Did we get an empty body and a non-error code?
            elif not len(ret) and self.rcode != "NXDOMAIN":
                raise IOError("DNS Error - " + self.rcode + " - for:" + hostname)
        return ret 
Example #3
Source File: dnsrebinding.py    From Saker with GNU General Public License v3.0 5 votes vote down vote up
def handle(self):
        request = dnslib.DNSRecord.parse(self.packet).reply()
        qname = str(request.q.qname)
        record, ttl, recordType = self.server.getRecord(qname)
        answer = dnslib.DNSRecord.question(qname)
        request.add_answer(
            dnslib.RR(
                qname,
                getattr(dnslib.QTYPE, recordType),
                rdata=getattr(dnslib, recordType)(record),
                ttl=ttl
            )
        )
        print('[%s] %s %s %s' % (time.time(), self.client_address, qname, record))
        self.wfile.write(request.pack()) 
Example #4
Source File: dnslog.py    From Scanver with Apache License 2.0 5 votes vote down vote up
def __init__(self, zone, glob=False):
        self.zone = [(rr.rname, QTYPE[rr.rtype], rr) for rr in RR.fromZone(zone)]
        self.glob = glob
        self.eq = 'matchGlob' if glob else '__eq__' 
Example #5
Source File: dnslog.py    From Scanver with Apache License 2.0 5 votes vote down vote up
def resolve(self, request, handler):
        """
            Respond to DNS request - parameters are request packet & handler.
            Method is expected to return DNS response
        """
        reply = request.reply()
        qname = request.q.qname
        qtype = QTYPE[request.q.qtype]
        for name, rtype, rr in self.zone:
            # Check if label & type match
            if getattr(qname, self.eq)(name) and (
                    qtype == rtype or qtype == 'ANY' or rtype == 'CNAME'):
                # If we have a glob match fix reply label
                if self.glob:
                    a = copy.copy(rr)
                    a.rname = qname
                    reply.add_answer(a)
                else:
                    reply.add_answer(rr)
                # Check for A/AAAA records associated with reply and
                # add in additional section
                if rtype in ['CNAME', 'NS', 'MX', 'PTR']:
                    for a_name, a_rtype, a_rr in self.zone:
                        if a_name == rr.rdata.label and a_rtype in ['A', 'AAAA']:
                            reply.add_ar(a_rr)
        if not reply.rr:
            reply.header.rcode = RCODE.NXDOMAIN
        return reply 
Example #6
Source File: server.py    From dnslib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def log_request(self,handler,request):
        print("%sRequest: [%s:%d] (%s) / '%s' (%s)" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    request.q.qname,
                    QTYPE[request.q.qtype]))
        self.log_data(request) 
Example #7
Source File: server.py    From dnslib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def log_reply(self,handler,reply):
        if reply.header.rcode == RCODE.NOERROR:
            print("%sReply: [%s:%d] (%s) / '%s' (%s) / RRs: %s" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    reply.q.qname,
                    QTYPE[reply.q.qtype],
                    ",".join([QTYPE[a.rtype] for a in reply.rr])))
        else:
            print("%sReply: [%s:%d] (%s) / '%s' (%s) / %s" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    reply.q.qname,
                    QTYPE[reply.q.qtype],
                    RCODE[reply.header.rcode]))
        self.log_data(reply) 
Example #8
Source File: server.py    From dnslib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def log_truncated(self,handler,reply):
        print("%sTruncated Reply: [%s:%d] (%s) / '%s' (%s) / RRs: %s" % (
                    self.log_prefix(handler),
                    handler.client_address[0],
                    handler.client_address[1],
                    handler.protocol,
                    reply.q.qname,
                    QTYPE[reply.q.qtype],
                    ",".join([QTYPE[a.rtype] for a in reply.rr])))
        self.log_data(reply) 
Example #9
Source File: zoneresolver.py    From dnslib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self,zone,glob=False):
        """
            Initialise resolver from zone file.
            Stores RRs as a list of (label,type,rr) tuples
            If 'glob' is True use glob match against zone file
        """
        self.zone = [(rr.rname,QTYPE[rr.rtype],rr) for rr in RR.fromZone(zone)]
        self.glob = glob
        self.eq = 'matchGlob' if glob else '__eq__' 
Example #10
Source File: zoneresolver.py    From dnslib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def resolve(self,request,handler):
        """
            Respond to DNS request - parameters are request packet & handler.
            Method is expected to return DNS response
        """
        reply = request.reply()
        qname = request.q.qname
        qtype = QTYPE[request.q.qtype]
        for name,rtype,rr in self.zone:
            # Check if label & type match
            if getattr(qname,self.eq)(name) and (qtype == rtype or
                                                 qtype == 'ANY' or
                                                 rtype == 'CNAME'):
                # If we have a glob match fix reply label
                if self.glob:
                    a = copy.copy(rr)
                    a.rname = qname
                    reply.add_answer(a)
                else:
                    reply.add_answer(rr)
                # Check for A/AAAA records associated with reply and
                # add in additional section
                if rtype in ['CNAME','NS','MX','PTR']:
                    for a_name,a_rtype,a_rr in self.zone:
                        if a_name == rr.rdata.label and a_rtype in ['A','AAAA']:
                            reply.add_ar(a_rr)
        if not reply.rr:
            reply.header.rcode = RCODE.NXDOMAIN
        return reply 
Example #11
Source File: intercept.py    From dnslib with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def resolve(self,request,handler):
        matched = False
        reply = request.reply()
        qname = request.q.qname
        qtype = QTYPE[request.q.qtype]
        # Try to resolve locally unless on skip list
        if not any([qname.matchGlob(s) for s in self.skip]):
            for name,rtype,rr in self.zone:
                if qname.matchGlob(name):
                    if qtype in (rtype,'ANY','CNAME'):
                        a = copy.copy(rr)
                        a.rname = qname
                        reply.add_answer(a)
                    matched = True
        # Check for NXDOMAIN
        if any([qname.matchGlob(s) for s in self.nxdomain]):
            reply.header.rcode = getattr(RCODE,'NXDOMAIN')
            return reply
        if matched and self.all_qtypes:
            return reply
        # Otherwise proxy, first checking forwards, then to upstream.
        upstream, upstream_port = self.address,self.port
        if not any([qname.matchGlob(s) for s in self.skip]):
            for name, ip, port in self.forward:
                if qname.matchGlob(name):
                    upstream, upstream_port = ip, port
        if not reply.rr:
            try:
                if handler.protocol == 'udp':
                    proxy_r = request.send(upstream,upstream_port,
                                    timeout=self.timeout)
                else:
                    proxy_r = request.send(upstream,upstream_port,
                                    tcp=True,timeout=self.timeout)
                reply = DNSRecord.parse(proxy_r)
            except socket.timeout:
                reply.header.rcode = getattr(RCODE,'SERVFAIL')

        return reply 
Example #12
Source File: lookup.py    From MINI-DNS-Server with MIT License 5 votes vote down vote up
def multiaddr(self):
        items = []
        for rr in self.record.rr:
            addr = Address(
                domain=self.domain.strip("."),
                ip=str(rr.rdata).strip("."),
                rtype=dnslib.QTYPE[rr.rtype],
                rclass=dnslib.CLASS[rr.rclass],
                ttl=rr.ttl,
                counter=time.time() + rr.ttl,
                dns_name=self.bdns.name
            )
            items.append(addr)
        return MultiAddress(items) 
Example #13
Source File: __init__.py    From Py-DNS-over-HTTPS-Proxy with GNU General Public License v3.0 4 votes vote down vote up
def resolve(self, request, handler):
        hostname = str(request.q.qname)
        ltype = request.q.qtype
        headers = {"Host": "dns.google.com"}

        try:
            if CACHE[hostname]['dt'] > datetime.datetime.now() - datetime.timedelta(minutes=30):
                print("Cache Hit: %s" % hostname)
                answer = CACHE[hostname][ltype]
            else:
                print("Cache Expired: %s" % hostname)
                del CACHE[hostname]
                raise Exception("Cache Expired")
        except:
            lookup_resp = requests.get('%sname=%s&type=%s' % (GOOGLE_DNS_URL,
                                                          hostname,
                                                          ltype),
                                   headers=headers,
                                   verify=False)

            if PINNED_CERT != lookup_resp.peercert:
                print(lookup_resp.peercert)
                if EXIT_ON_MITM:
                    print ("ERROR: REMOTE SSL CERT DID NOT MATCH EXPECTED (PINNED) "
                           "SSL CERT, EXITING IN CASE OF MAN IN THE MIDDLE ATTACK")
                    my_pid = os.getpid()
                    os.kill(my_pid, signal.SIGINT)
                else:
                    print ("WARNING: REMOTE SSL CERT DID NOT MATCH EXPECTED (PINNED) "
                           "SSL CERT. NOT EXITING, BECAUSE YOU SAID SO IN YOUR CONFIG")


            if lookup_resp.status_code == 200:
                try:
                    print("Cache Miss: %s" % hostname)
                    answer = json.loads(lookup_resp.text)['Answer']
                    CACHE[hostname] = {ltype: answer, "dt": datetime.datetime.now()}
                except:
                    answer = []
            else:
                answer = []

        reply = request.reply()
        for record in answer:
            rtype = QTYPE[record['type']]
            zone = "%s %s %s %s" % (str(record['name']),
                                    record['TTL'],
                                    rtype,
                                    str(record['data']))
            reply.add_answer(*RR.fromZone(zone))

        return reply