Example #1
0
    def _test_packet(self, expected, index):
        packet = DnsPacket.from_bytes(DnsPacketTest.packets[index])

        self.assertEqual(packet.id, expected.id)
        self.assertEqual(packet.has_error, expected.has_error)
        self.assertEqual(packet.is_authoritative, expected.is_authoritative)
        self.assertEqual(packet.is_recursion_desired,
                         expected.is_recursion_desired)
        self.assertEqual(packet.is_recursion_available,
                         expected.is_recursion_available)
        self.assertEqual(packet.is_response, expected.is_response)
        self.assertEqual(packet.is_truncated, expected.is_truncated)
        self.assertEqual(packet.opcode, expected.opcode)
        self.assertEqual(packet.question, expected.question)
        self.assertEqual(packet.answers, expected.answers)
Example #2
0
 def on_connection(self, sock, data, addr):
     try:
         print('>> Data received')
         packet = DnsPacket.from_bytes(data)
         name, query_type = packet.question
         print('>> Question: ', query_type, name)
         cache_key = int(query_type), name
         if cache_key in self.cache:
             print('>> Found fresh record in cache')
             sock.sendto(self.cache[cache_key], addr)
         else:
             print('>> No fresh record in cache')
             origin_packet = self.forward_question(packet)
             if not origin_packet.answers:
                 print('>> Origin has no answers')
                 return
             min_ttl = min(origin_packet.answers, key=lambda x: x[2])[2]
             self.cache.add(cache_key, bytes(origin_packet), min_ttl)
             sock.sendto(bytes(origin_packet), addr)
         print('>> Answered')
     except:
         print('>> Error with packet: {}\n{}'.format(
             repr(data), format_exc()))
Example #3
0
 def forward_question(self, packet):
     sock = socket(AF_INET, SOCK_DGRAM)
     sock.settimeout(12)
     sock.sendto(bytes(packet), self.origin)
     data, addr = sock.recvfrom(4096)
     return DnsPacket.from_bytes(data)
Example #4
0
 def test_serialize(self):
     for packet in DnsPacketTest.packets:
         parsed = DnsPacket.from_bytes(packet)
         serialized = bytes(parsed)
         self.assertEqual(serialized, packet)
Example #5
0
 def test_serialize_ptr_question(self):
     packet = DnsPacketTest.packets[0]
     parsed = DnsPacket.from_bytes(packet)
     serialized = bytes(parsed)
     self.assertEqual(len(serialized), len(packet))
     self.assertEqual(serialized, packet)