示例#1
0
    def to_text(self, origin=None, relativize=True, **kw):
        """Convert the message to text.

        The *origin*, *relativize*, and any other keyword
        arguments are passed to the RRset ``to_wire()`` method.

        Returns a ``text``.
        """

        s = StringIO()
        s.write('id %d\n' % self.id)
        s.write('opcode %s\n' %
                dns.opcode.to_text(dns.opcode.from_flags(self.flags)))
        rc = dns.rcode.from_flags(self.flags, self.ednsflags)
        s.write('rcode %s\n' % dns.rcode.to_text(rc))
        s.write('flags %s\n' % dns.flags.to_text(self.flags))
        if self.edns >= 0:
            s.write('edns %s\n' % self.edns)
            if self.ednsflags != 0:
                s.write('eflags %s\n' %
                        dns.flags.edns_to_text(self.ednsflags))
            s.write('payload %d\n' % self.payload)
        for opt in self.options:
            s.write('option %s\n' % opt.to_text())
        is_update = dns.opcode.is_update(self.flags)
        if is_update:
            s.write(';ZONE\n')
        else:
            s.write(';QUESTION\n')
        for rrset in self.question:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write('\n')
        if is_update:
            s.write(';PREREQ\n')
        else:
            s.write(';ANSWER\n')
        for rrset in self.answer:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write('\n')
        if is_update:
            s.write(';UPDATE\n')
        else:
            s.write(';AUTHORITY\n')
        for rrset in self.authority:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write('\n')
        s.write(';ADDITIONAL\n')
        for rrset in self.additional:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write('\n')
        #
        # We strip off the final \n so the caller can print the result without
        # doing weird things to get around eccentricities in Python print
        # formatting
        #
        return s.getvalue()[:-1]
示例#2
0
    def to_text(self, origin=None, relativize=True, **kw):
        """Convert the message to text.

        The *origin*, *relativize*, and any other keyword
        arguments are passed to the RRset ``to_wire()`` method.

        Returns a ``text``.
        """

        s = StringIO()
        s.write('id %d\n' % self.id)
        s.write('opcode %s\n' %
                dns.opcode.to_text(dns.opcode.from_flags(self.flags)))
        rc = dns.rcode.from_flags(self.flags, self.ednsflags)
        s.write('rcode %s\n' % dns.rcode.to_text(rc))
        s.write('flags %s\n' % dns.flags.to_text(self.flags))
        if self.edns >= 0:
            s.write('edns %s\n' % self.edns)
            if self.ednsflags != 0:
                s.write('eflags %s\n' %
                        dns.flags.edns_to_text(self.ednsflags))
            s.write('payload %d\n' % self.payload)
        for opt in self.options:
            s.write('option %s\n' % opt.to_text())
        is_update = dns.opcode.is_update(self.flags)
        if is_update:
            s.write(';ZONE\n')
        else:
            s.write(';QUESTION\n')
        for rrset in self.question:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write('\n')
        if is_update:
            s.write(';PREREQ\n')
        else:
            s.write(';ANSWER\n')
        for rrset in self.answer:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write('\n')
        if is_update:
            s.write(';UPDATE\n')
        else:
            s.write(';AUTHORITY\n')
        for rrset in self.authority:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write('\n')
        s.write(';ADDITIONAL\n')
        for rrset in self.additional:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write('\n')
        #
        # We strip off the final \n so the caller can print the result without
        # doing weird things to get around eccentricities in Python print
        # formatting
        #
        return s.getvalue()[:-1]
示例#3
0
    def to_text(self, origin=None, relativize=True, **kw):
        """Convert the message to text.

        The I{origin}, I{relativize}, and any other keyword
        arguments are passed to the rrset to_wire() method.

        @rtype: string
        """

        s = StringIO()
        s.write(u"id %d\n" % self.id)
        s.write(u"opcode %s\n" % dns.opcode.to_text(dns.opcode.from_flags(self.flags)))
        rc = dns.rcode.from_flags(self.flags, self.ednsflags)
        s.write(u"rcode %s\n" % dns.rcode.to_text(rc))
        s.write(u"flags %s\n" % dns.flags.to_text(self.flags))
        if self.edns >= 0:
            s.write(u"edns %s\n" % self.edns)
            if self.ednsflags != 0:
                s.write(u"eflags %s\n" % dns.flags.edns_to_text(self.ednsflags))
            s.write(u"payload %d\n" % self.payload)
        for opt in self.options:
            s.write(u"option %s\n" % opt.to_text())
        is_update = dns.opcode.is_update(self.flags)
        if is_update:
            s.write(u";ZONE\n")
        else:
            s.write(u";QUESTION\n")
        for rrset in self.question:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write(u"\n")
        if is_update:
            s.write(u";PREREQ\n")
        else:
            s.write(u";ANSWER\n")
        for rrset in self.answer:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write(u"\n")
        if is_update:
            s.write(u";UPDATE\n")
        else:
            s.write(u";AUTHORITY\n")
        for rrset in self.authority:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write(u"\n")
        s.write(u";ADDITIONAL\n")
        for rrset in self.additional:
            s.write(rrset.to_text(origin, relativize, **kw))
            s.write(u"\n")
        #
        # We strip off the final \n so the caller can print the result without
        # doing weird things to get around eccentricities in Python print
        # formatting
        #
        return s.getvalue()[:-1]
示例#4
0
    def to_text(self,  origin=None, relativize=True, **kw):
        """Convert the message to text.

        The I{origin}, I{relativize}, and any other keyword
        arguments are passed to the rrset to_wire() method.

        @rtype: string
        """

        s = cStringIO.StringIO()
        print >> s, 'id %d' % self.id
        print >> s, 'opcode %s' % \
              dns.opcode.to_text(dns.opcode.from_flags(self.flags))
        rc = dns.rcode.from_flags(self.flags, self.ednsflags)
        print >> s, 'rcode %s' % dns.rcode.to_text(rc)
        print >> s, 'flags %s' % dns.flags.to_text(self.flags)
        if self.edns >= 0:
            print >> s, 'edns %s' % self.edns
            if self.ednsflags != 0:
                print >> s, 'eflags %s' % \
                      dns.flags.edns_to_text(self.ednsflags)
            print >> s, 'payload', self.payload
        is_update = dns.opcode.is_update(self.flags)
        if is_update:
            print >> s, ';ZONE'
        else:
            print >> s, ';QUESTION'
        for rrset in self.question:
            print >> s, rrset.to_text(origin, relativize, **kw)
        if is_update:
            print >> s, ';PREREQ'
        else:
            print >> s, ';ANSWER'
        for rrset in self.answer:
            print >> s, rrset.to_text(origin, relativize, **kw)
        if is_update:
            print >> s, ';UPDATE'
        else:
            print >> s, ';AUTHORITY'
        for rrset in self.authority:
            print >> s, rrset.to_text(origin, relativize, **kw)
        print >> s, ';ADDITIONAL'
        for rrset in self.additional:
            print >> s, rrset.to_text(origin, relativize, **kw)
        if edns >= 0:
            print >> s, ';EDNS OPTIONS'
            for option in self.options:
                print >> s, option.to_text()
        #
        # We strip off the final \n so the caller can print the result without
        # doing weird things to get around eccentricities in Python print
        # formatting
        #
        return s.getvalue()[:-1]
示例#5
0
    def to_text(self, origin=None, relativize=True, **kw):
        """Convert the message to text.

        The I{origin}, I{relativize}, and any other keyword
        arguments are passed to the rrset to_wire() method.

        @rtype: string
        """

        s = io.StringIO()
        print('id %d' % self.id, file=s)
        print('opcode %s' % \
              dns.opcode.to_text(dns.opcode.from_flags(self.flags)),
              file = s)
        rc = dns.rcode.from_flags(self.flags, self.ednsflags)
        print('rcode %s' % dns.rcode.to_text(rc), file=s)
        print('flags %s' % dns.flags.to_text(self.flags), file=s)
        if self.edns >= 0:
            print('edns %s' % self.edns, file=s)
            if self.ednsflags != 0:
                print('eflags %s' % \
                      dns.flags.edns_to_text(self.ednsflags), file = s)
            print('payload', self.payload, file=s)
        is_update = dns.opcode.is_update(self.flags)
        if is_update:
            print(';ZONE', file=s)
        else:
            print(';QUESTION', file=s)
        for rrset in self.question:
            print(rrset.to_text(origin, relativize, **kw), file=s)
        if is_update:
            print(';PREREQ', file=s)
        else:
            print(';ANSWER', file=s)
        for rrset in self.answer:
            print(rrset.to_text(origin, relativize, **kw), file=s)
        if is_update:
            print(';UPDATE', file=s)
        else:
            print(';AUTHORITY', file=s)
        for rrset in self.authority:
            print(rrset.to_text(origin, relativize, **kw), file=s)
        print(';ADDITIONAL', file=s)
        for rrset in self.additional:
            print(rrset.to_text(origin, relativize, **kw), file=s)
        #
        # We strip off the final \n so the caller can print the result without
        # doing weird things to get around eccentricities in Python print
        # formatting
        #
        return s.getvalue()[:-1]
示例#6
0
    def to_text(self, origin=None, relativize=True, **kw):
        """Convert the message to text.

        The *origin*, *relativize*, and any other keyword
        arguments are passed to the RRset ``to_wire()`` method.

        Returns a ``str``.
        """

        s = io.StringIO()
        s.write('id %d\n' % self.id)
        s.write('opcode %s\n' %
                dns.opcode.to_text(dns.opcode.from_flags(self.flags)))
        rc = dns.rcode.from_flags(self.flags, self.ednsflags)
        s.write('rcode %s\n' % dns.rcode.to_text(rc))
        s.write('flags %s\n' % dns.flags.to_text(self.flags))
        if self.edns >= 0:
            s.write('edns %s\n' % self.edns)
            if self.ednsflags != 0:
                s.write('eflags %s\n' % dns.flags.edns_to_text(self.ednsflags))
            s.write('payload %d\n' % self.payload)
        for opt in self.options:
            s.write('option %s\n' % opt.to_text())
        for (name, which) in self._section_enum.__members__.items():
            s.write(f';{name}\n')
            for rrset in self.section_from_number(which):
                s.write(rrset.to_text(origin, relativize, **kw))
                s.write('\n')
        #
        # We strip off the final \n so the caller can print the result without
        # doing weird things to get around eccentricities in Python print
        # formatting
        #
        return s.getvalue()[:-1]
示例#7
0
文件: dig.py 项目: cawka/py-ndns
    def onResult (result, msg):
        if args.no_output:
            needrun = False
            loop.stop ()
            return

        if not args.quiet:
            out.write (";; Got data packet [%s]\n" % result.name)
            out.write (";;       signed by [%s]\n" % result.signedInfo.keyLocator.keyName)
            out.write ("\n")
            out.write ("%s\n" % msg.to_text ())
        else:
            for rrset in msg.answer:
                out.write ("%s\n" % rrset.to_text ())

        needrun = False
        loop.stop ()
示例#8
0
    def onResult(result, msg):
        if args.no_output:
            needrun = False
            loop.stop()
            return

        if not args.quiet:
            out.write(";; Got data packet [%s]\n" % result.name)
            out.write(";;       signed by [%s]\n" %
                      result.signedInfo.keyLocator.keyName)
            out.write("\n")
            out.write("%s\n" % msg.to_text())
        else:
            for rrset in msg.answer:
                out.write("%s\n" % rrset.to_text())

        needrun = False
        loop.stop()
def get_additional_zone(r):
    for rrset in r.authority:
        str = rrset.to_text()
        zone = str[0:str.index(".")]
        return zone
def get_answer(message, nsaddr, qtype, DS, zone):
    response = dns.query.udp(message, nsaddr)
    additional_ip_list = get_additional_ip_list(response)

    if response.answer:
        '''Print out the IP address and query info.'''
        A_RRsig = get_A_RRsig(response)
        dnskeyResponse = acquireDNSKEYres(zone, nsaddr)

        if dnskeyResponse.answer:
            dnskeySet = get_dnskeySet(dnskeyResponse)
            dnskeyRRsig = get_dnskeyRRsig(dnskeyResponse)
            childKsk = get_ksk_tobevalidated(dnskeySet)
            hashed_childKsk = dns.dnssec.make_ds(dns.name.from_text(zone),
                                                 childKsk, 'SHA256')
            try:
                hashed_childKsk == DS
                print("DNSKEY KSK Validation Success")
            except dns.dns.dnssec.ValidationFailure:
                print("DNSKEY KSK verification failed")
                return
        else:
            for rrset in response.answer:
                if rrset.rdtype == dns.rdatatype.from_text(qtype):
                    timeUse = time.time() - timeBegin
                    print(rrset.to_text())
                    print('\nQuery Time:', int(timeUse * 1000), 'msec')
                    print('When:', time.asctime(time.localtime(time.time())))
                    print('\nMSG SIZE  rcvd:',
                          len(rrset.to_text().encode('utf-8')))

    else:
        '''If not touch the end of the query pass, then Make validations and iterate zones'''
        #Condition 1 : At very beginning, verify the root zone
        if nsaddr == rootIP[0]:
            keys = {dns.name.from_text("."): rootKsk}
            dnskeyResponse = acquireDNSKEYres('.', nsaddr)
            dnskeySet = get_dnskeySet(dnskeyResponse)
            dnskeyRRsig = get_dnskeyRRsig(dnskeyResponse)

            try:
                dns.dnssec.validate(dnskeySet, dnskeyRRsig, keys)
                print("DNSKEY Validation Success")
            except dns.dnssec.ValidationFailure:
                print("DNSKEY verification failed")

            #Verify DS record
            DSname = get_DSname(response)
            DSset = get_DSset(response)
            DSRRsig = get_DSRRsig(response)
            zsk = get_zsk(dnskeySet)
            keys = {dns.name.from_text("."): zsk}

            try:
                dns.dnssec.validate(DSset, DSRRsig, keys)
                print("DSpubksk Validation Success!")
            except dns.dnssec.ValidationFailure:
                print("DSpubksk verification failed")
                return

            #update puksk to be self-zone's DS record
            DS = get_DS(response)
            zone = get_additional_zone(response)

        #Condition 2: not a root zone
        else:
            #(1)Varify the DNSKEY ksk first
            dnskeyResponse = acquireDNSKEYres(zone, nsaddr)
            dnskeySet = get_dnskeySet(dnskeyResponse)
            dnskeyRRsig = get_dnskeyRRsig(dnskeyResponse)

            childKsk = get_ksk_tobevalidated(dnskeySet)
            hashed_childKsk = dns.dnssec.make_ds(dns.name.from_text(zone),
                                                 childKsk, 'SHA256')

            try:
                hashed_childKsk == DS
                print("DNSKEY KSK Validation Success")
            except dns.dns.dnssec.ValidationFailure:
                print("DNSKEY KSK verification failed")
                return

            #(2)Verify DS record
            DSname = get_DSname(response)
            DSset = get_DSset(response)
            DSRRsig = get_DSRRsig(response)
            zsk = get_zsk(dnskeySet)
            keys = {dns.name.from_text(zone): zsk}

            try:
                dns.dnssec.validate(DSset, DSRRsig, keys)
                print("DSpubksk Validation Success")
            except dns.dnssec.ValidationFailure:
                print("DSpubksk verification failed")
                return

            #Get self-zone's DS record and next zone's zone name
            DS = get_DS(response)
            zone = get_additional_zone(response)

        #elif additional_ip_list:
        nsaddr = additional_ip_list[0]
        get_answer(message, nsaddr, qtype, DS, zone)
示例#11
0
def make_auth_query(address, request, isudp=True):
    """ Returns a multi-line string of all sorted RRsets from:
         - question section: case-preserved complete RR
         - answer, authority section:
               lowercased, each RR consists of owner name
               rdtype and rdata but not class or ttl
    """
    max_retry = 2 # 2 means 3 attempts in total
    retry = 0
    # default result if an invalid response received
    result = err_invalid

    while (retry < max_retry):
        try:
            if isudp:
                proto = "udp"
                response = dns.query.udp(request, address, timeout=timeout)
            else:
                proto = "tcp"
                response = dns.query.tcp(request, address, timeout=timeout)
            rrsetlist = []
            # RRsets within answer, authority section are sorted as not all server
            # respond RRset in same order (e.g. NSEC3). In addition, we sort
            # each RR within an RRset as server typically randomize them.
            if response.question:
                for rrset in response.question:
                    # question section is always case-sensitive
                    rrsetlist.append(rrset.to_text())

            if response.answer:
                for rrset in response.answer:
                    rrlist = []
                    for rr in rrset:
                        if casesensitive:
                            rrlist.append(rrset.name.to_text() + " "
                                + dns.rdatatype.to_text(rrset.rdtype) + " "
                                + rr.to_text())
                        else:
                            rrlist.append(rrset.name.to_text().lower() + " "
                                + dns.rdatatype.to_text(rrset.rdtype).lower() + " "
                                + rr.to_text().lower())
                    rrsetlist.append("\n".join(sorted(rrlist)))

            if response.authority:
                for rrset in response.authority:
                    rrlist = []
                    for rr in rrset:
                        if casesensitive:
                            rrlist.append(rrset.name.to_text() + " "
                                + dns.rdatatype.to_text(rrset.rdtype) + " "
                                + rr.to_text())
                        else:
                            rrlist.append(rrset.name.to_text().lower() + " "
                                + dns.rdatatype.to_text(rrset.rdtype).lower() + " "
                                + rr.to_text().lower())
                    rrsetlist.append("\n".join(sorted(rrlist)))

            if response.answer or response.authority:
                # break query while-loop as we got a response
                retry = max_retry
                result = "\n".join(sorted(rrsetlist))

        except dns.exception.Timeout as e:
            retry += 1
            result = err_timeout
            logging.debug("error for dns query to " + address + " (" + proto + "): " + str(e))
        except (BrokenPipeError, ConnectionResetError) as e:
            retry += 1
            result = err_timeout
            logging.debug("error for dns query to " + address + " (" + proto + "): " + str(e))
        except Exception as e:
            retry += 1
            logging.debug("error for dns query to " + address + " (" + proto + "): " + str(e))

    return result