def checkMPTCPSupportViaRST(port, target, timeout, localIP, MpCapAlreadyPassed=False): MpCapPassed = MpCapAlreadyPassed #TODO: Abstract this out more elegantly so i dont repeat code from elsewhere if not MpCapPassed: pkt = makeMPCapableSyn(localIP, port, target) response = sr1(pkt, timeout=timeout) if response and getMpOption(pkt.getlayer("TCP")) is not None: MpCapPassed = True if MpCapPassed: pkt = makeJoinSyn(localIP, port, target) response = sr1(pkt, timeout=timeout) #TODO: Add checks for other types of response (such as ICMP) #TODO: Make this clearer #Check for the flag with a mask print response.getlayer("TCP").flags if (0x04 & response.getlayer("TCP").flags) == 0x04: print "RST Test indicates MPTCP support" return True else: print "RST Test indicates host doesn't understand MPTCP" return False
def isup(self): arp_req = ARP(psrc=self.src, pdst=self.dst) arp_res = sr1(arp_req, timeout=1) if not (arp_res is None): return True icmp_req = IP(src=self.src, dst=self.dst) / ICMP() icmp_res = sr1(icmp_req, timeout=1) if not (icmp_res is None): return True tcp_req = IP(src=self.src, dst=self.dst) / TCP(dport=80) tcp_res = sr1(tcp_req, timeout=1) if not (tcp_res is None): return True tcp_req = IP(src=self.src, dst=self.dst) / TCP(dport=443) tcp_res = sr1(tcp_req, timeout=1) if not (tcp_res is None): return True udp_req = IP(src=self.src, dst=self.dst) / UDP(dport=53) udp_res = sr1(udp_req, timeout=1) if not (udp_res is None): return True return False
def send_packet(self): choose_way = self.choose_way.currentIndex() if choose_way == 0: send(self.forged_packet) elif choose_way == 1: sendp(self.forged_packet) elif choose_way == 2: sr(self.forged_packet) elif choose_way == 2: sr1(self.forged_packet) elif choose_way == 3: srloop(self.forged_packet)
def ping(self): for x in range(self.qua): result = sr1(self.pkt, timeout=1, verbose=False) if result: print(self.ip, '可达!') else: print(self.ip, '不可达!')
def _port_ping(self, hosts: Queue, interface: str, results: set): self.logger.debug("{}: Starting TCP SYN ping thread.".format(threading.current_thread().name)) while True: ip = hosts.get() # type: IPAddress ip_str = str(ip) # Send SYN with random Src Port for each Dst port for dstPort in self.portstoscan: srcPort = random.randint(1025, 65534) resp = sr1(IP(dst=ip_str) / TCP(sport=srcPort, dport=dstPort, flags=ScapyTCPFlag.SYN), timeout=1, verbose=False, iface=interface) if resp and resp.haslayer(TCP): if resp[TCP].flags == (TCPFlag.SYN | TCPFlag.ACK) or resp[TCP].flags == (TCPFlag.RST | TCPFlag.ACK): # Send Reset packet (RST) send(IP(dst=ip_str) / TCP(sport=srcPort, dport=dstPort, flags=ScapyTCPFlag.RST), iface=interface, verbose=False) # We know the port is closed or opened (we got a response), so we deduce that the host exists node = NetworkNode() node.ip = ip node.mac = EUI(resp.src) node.host = resolve_ip(resp[IP].src) results.add(node) self.logger.debug( "Found a live host by pinging port {port_nbr}: {live_host}.".format(port_nbr=dstPort, live_host=str(node))) # We don't need to test the other ports. We know the host exists. break hosts.task_done()
def icmpv6_ns(host, ifname): # 请求特定IPv6地址的MAC地址 ll_mac = get_mac_address(ifname) # 获取本机接口MAC地址 # 构建icmpv6_ns数据包 # -----------IPv6头部 - ----------- # Next Header: 0x3A(ICMPv6) # 原地址: Link Local address # 目的地址: Solicited node multicast address # # ----------ICMPv6头部 - --------- # ICMPv6 Type: 135 # ICMPv6 Code: 0(NS) # 目标地址: 2001:1::129 # # ----Source Link-Layer Address - --- # 源地址: 本地MAC地址 packet = IPv6(src=mac_to_ipv6_linklocal(ll_mac), dst=Solicited_node_multicast_address(host)) / \ ICMPv6ND_NS(tgt=host) / ICMPv6NDOptSrcLLAddr(lladdr=ll_mac) # packet.show() # 发送数据包 result = sr1(packet, timeout=2, verbose=False) # 提取返回的MAC地址 # result.show() return result.getlayer( "ICMPv6 Neighbor Discovery Option - Destination Link-Layer Address" ).fields['lladdr']
def scan(conn, host, nm, icmp): # TODO: geolocation script --script ip-geolocation-geoplugin pack = IP(dst=host) / icmp conn.processedIps.insert({"_id": int(netaddr.IPAddress(host))}) try: reply = sr1(pack, timeout=TIMEOUT, verbose=False) if reply is not None: try: nm.scan(host, arguments=args) if host in nm.all_hosts(): if nm[host].state() == 'up': jsonRes = json.dumps(nm[host]) conn.ipsBanners.insert({"info": jsonRes}) except KeyError as e: print str(e) except ValueError as e: print str(e) except TypeError as e: print str(e) except AttributeError as e: print str(e) except: print "Unexpected error:", sys.exc_info()[0] gc.collect() del reply except: print "Ping error:", sys.exc_info()[0] gc.collect() del pack
def passive(dst): """ +------------------+ | OS TTL Values | +---------+--------+ | OS | IP TTL | +---------+--------+ | Linux | 64 | +---------+--------+ | Windows | 128 | +---------+--------+ | | | +---------+--------+ | | | +---------+--------+ """ ip_packet = IP(dst=dst)/ICMP() packet_resp = sr1(ip_packet, timeout=4) if packet_resp is None: print('[!] Request timeout') return 'timeout' resp_ttl = packet_resp.getlayer(IP).ttl if resp_ttl <= 64: print(f'[+] Remote OS is Linux - TTL {resp_ttl}') return 'linux' elif resp_ttl <= 128: print(f'[+] Remote OS is Windows - TTL {resp_ttl}') return 'windows' else: print(f'[+] Remote OS is other or protected - TTL {resp_ttl}') return 'other'
def trace_route(hostname): ip = str(socket.gethostbyname(hostname)) print(hostname) print("IP ", ip) header = '{:<2} {:<12} {:<18} {:<15} {:<14} {:<13} {:<10} {:<12} {:<14}' \ .format('', '', "IP", "CITY", "STATE", "ZIP", "LAT", "LON", "COUNTRY") print('\n', header) for i in range(1, 28): reply = sr1(IP(dst=sys.argv[1], ttl=i) / ICMP(id=os.getpid()), verbose=0) if reply is None: print("No Reply") break elif reply.src == ip: params = ip_lookup(reply.src) if not ipaddress.ip_address( reply.src) else "PRIV IP" print('\n', "We're here!", '\n', end=' ', flush=True) print_results(i, reply.src, params) break elif ipaddress.ip_address(reply.src).is_private: priv = "PRIV IP" print_results(i, reply.src, priv) else: params = ip_lookup(reply.src) print_results(i, reply.src, params)
def ping(target_ip): package = IP(dst=target_ip) / ICMP() / random_str_byte() result = sr1(package, timeout=3, verbose=False) if result: return target_ip, SUCCESS else: return target_ip, FAILURE
def main(argv): user_target = get_target(argv[0]) print(str(user_target)) string_list = format_target(user_target) #Build a recon csv workbook #""" Future feature recon_wb = openpyxl.Workbook() sheet = recon_wb.get_sheet_by_name('Sheet') sheet['A1'].value = 'Target' sheet['B1'].value = str(argv[0]) sheet['A2'].value = 'All addresses' sheet['C2'].value = 'Active addresses' sheet['B2'].value = 'Unresponsive addresses' #""" #loop through generated list of target IPs #""" for index, packet in enumerate(string_list, start = 0): #input packet dest in 'All addreses column' sheet.cell(row = (index + 3), column = 1, value = str(packet.dst)) delay = random.random() sleep(delay) ping_packet = (IP(dst=packet.dst)/ICMP()) ans = sr1(ping_packet, timeout = 4, verbose=0) if not (ans is None): print(ans.src + " is online.") print(str(ans.src)) sheet.cell(row = (index + 3), column = 3, value = str(ans.src)) string_list.remove(packet) else: print("Timeout waiting for %s " %packet.dst) sheet.cell(row = (index + 3), column = 2, value = str(packet.dst)) recon_wb.save(filename = 'test_workbook.xls')
def start_tracing(self): try: while self.__ttl_counter < TTL_MAX: pkt = self.__generate_next_packet() ans = sr1(pkt, verbose=False, timeout=TIMEOUT) if ans is None: print( f'{self.__ttl_counter}: Reply timed out!\nMoving on to next client' ) continue rtt = "Not Applicable" if hasattr(ans[ICMP], 'load'): rtt = round((time.time() - float(ans[ICMP].load)) * 1000, 4) print(f'{self.__ttl_counter}: {ans[0].src} | RTT: {rtt}') # Terminating if we reach destination if ans[ICMP].type == 0: print(f"Destination Reached!") break except KeyboardInterrupt: pass
def ping_one(dst, id_ping, seq_ping, ttl_ping): send_time = time.time() time_in_bytes = struct.pack('>d', send_time) # 把发出的时间,写入ICMP数据部分 # 构建ICMP Echo数据包 ping_one_reply = sr1(IP(dst=dst, ttl=ttl_ping) / ICMP(id=id_ping, seq=seq_ping) /\ time_in_bytes, timeout=2, verbose=False) try: if ping_one_reply.getlayer(ICMP).type == 0 and ping_one_reply.getlayer( ICMP).code == 0 and ping_one_reply.getlayer( ICMP).id == id_ping: # 确认type,code和id是否匹配 # 提取源IP,序列号,TTL,计算数据长度 reply_source_ip = ping_one_reply.getlayer(IP).src reply_seq = ping_one_reply.getlayer(ICMP).seq reply_ttl = ping_one_reply.getlayer(IP).ttl reply_data_length = len(ping_one_reply.getlayer(Raw).load) + len( ping_one_reply.getlayer(Padding).load) + 8 # 提取返回数据,转换为时间,并与当前时间计算时间差 reply_data = ping_one_reply.getlayer(Raw).load receive_time = time.time() echo_request_sendtime = struct.unpack('>d', reply_data) time_to_pass_ms = (receive_time - echo_request_sendtime[0]) * 1000 # 返回数据长度, 源IP地址,序列号,TTL和用时 return reply_data_length, reply_source_ip, reply_seq, reply_ttl, time_to_pass_ms except Exception as e: if re.match('.*NoneType.*', str(e)): return None
def udp_scan(port, ip): print("Running UDP scan...") port = int(port) result = sr1(IP(dst=ip) / UDP(sport=RandShort(), dport=port), verbose=0, timeout=3) if result and result.haslayer(UDP): return True return False
def mytraceroute(destination, timeout): for i in range(1, 31): pkt = IP(dst=destination, ttl=i) / UDP(dport=33434) reply = sr1(pkt, verbose=0, timeout=timeout) if reply is not None: ip_addr = reply.src if IPy.IP(ip_addr).iptype() != "PRIVATE": obj = IPWhois(ip_addr) results = obj.lookup() #pp(results) if results.get('nets', None): print(ip_addr, ' : ', results.get('asn', '_'), '/', results['nets'][0].get('name', '_'), '/', results.get('asn_country_code', '_'), '/', results['nets'][0].get('description', '_')) else: print(ip_addr, ' : ', results.get('asn', '_'), '/', results.get('asn_country_code', '_')) else: print(ip_addr) if reply.type == 3: print("Destination reached") break else: print("***")
def ping(ip): ping_pkt = IP(dst=ip) / ICMP() ping_result = sr1(ping_pkt, timeout=2, verbose=False) if ping_result: return ip, 1 else: return ip, 0
def arp_request(dst, ifname): hwsrc = GET_MAC_netifaces.get_mac_address(ifname) psrc = GET_IP_netifaces.get_ip_address(ifname) try: arp_pkt = sr1(ARP(op=1, hwsrc=hwsrc, psrc=psrc, pdst=dst), timeout=5, verbose=False) return dst, arp_pkt.getlayer(ARP).fields['hwsrc'] except AttributeError: return dst, None
def tcp_task(): #随机产生一个1-65535的IP的id位 ip_id=randint(1,65535) data = "m"*1400 # 一个最大传输单元(MTU)为1500字节,减去ip头20字节,再减去tcp头20字节,最大可传输数据为1460字节 pkt = IP(dst='192.168.214.129', id=ip_id) / TCP(dport=8080, flags="S")/data.encode(encoding="utf-8") # 发送包,超时时间为1秒,如果对端没有响应,则返回None,有响应则返回响应包 res = sr1(pkt, timeout=1, verbose=False) return res
def calcScapy(self, mtu): payload = b'p' * mtu pkt = IP(dst='www.baidu.com', flags='DF') / ICMP() / payload answer = sr1(pkt, timeout=2, verbose=False) if answer and answer[ICMP].code == 0 and answer[ICMP].type == 0: if self.mtu < mtu: self.mtu = mtu self.mtuList.append(mtu)
def ping(self, ttl): request = IP(dst=self.dst, id=randint(0, 0xffff), ttl=ttl) / ICMP() reply = sr1(request, retry=3, timeout=2.0, verbose=0) hop = Hop(self, request, reply) print(hop) self.hops.append(hop) return hop.icmp()
def filter_port(ip, port): closed_port = check_closed(ip) s = sr1(IP(dst=str(ip)) / TCP(dport=port, flags='S'), timeout=2, verbose=0) try: if s != 'SA': try: if s[0][1].seq == 0: pass except: s = sr1(IP(dst=ip) / TCP(dport=closed_port, flags='S'), timeout=2, verbose=0) if s == None: return None else: return True except: pass
def check_if_host_is_up(ip): try: print("Setting up ping for IP " + ip + ".") ping = sr1(IP(dst=ip) / ICMP(), timeout=10, iface="eth0", verbose=False) print("Ping successful! Beginning scan...") except Exception as e: print("Couldn't ping! Exiting...") print("The error: " + str(e)) traceback.print_exc() sys.exit(1)
def run(self): """ This function sends the Password data """ for password in self.user_data: time.sleep(10) answer: Union[Union[PacketList, List[Any]], Any] = sr1( IP(dst=self.dns_server_ip) / UDP(dport=self.dns_port) / DNS(rd=1, qd=DNSQR(qname=password)), verbose=0)
def run(self): req = IP(src=self.src, dst=self.dst) / TCP(dport=self.dport) res = sr1(req, timeout=3) if res is not None: if str(res[TCP].flags) == "SA": self.isopen = PortStatus.OPEN else: self.isopen = PortStatus.CLOSE else: self.isopen = PortStatus.TIMEOUT
def _send_ntp_client_request(self, dst='pool.ntp.org', ntp=NTP()) -> Packet: pck = IP(dst=dst) / UDP() / ntp if self.debug: pck.show() pck = sr1(pck) if self.debug: pck.show() return pck
def active_host(ipaddr: str) -> bool: """Ping a target host using the specified IPv4 address. Return true if target responds to our ICMP probe""" packet = IP(dst=ipaddr) / ICMP() response = sr1(packet, timeout=5, verbose=0) if response: return True else: return False
def joinScan(targetIPList, portList, localIP, reuseRandoms=False, timeout=None): #TODO: Add return details #TODO: Decide where this fits in the workflow, after an open TCP port maybe? #TODO: Decide how we want to handle the return values from this raise NotImplementedError #The option to reuse random numbers for "increased speed" if reuseRandoms: sourceAddr = localIP sport = randintb(16) initSeq = randintb(32) if timeout is None: timeout = 5 for targetIP in targetIPList: for port in portList: #First send a packet and see if we get a TCP response pkt = makeMPCapableSyn(localIP, port, targetIP) response = sr1(pkt, timeout=timeout) if response is not None: #if we do then send an invalid MPTCP join and see if we get a RST pkt = makeJoinSyn(sourceAddr, port, targetIP) response2 = sr1(pkt, timeout=timeout) #If we get a RST then we know this host supports MPTCP if response2 is None: print "Target supports MPTCP but is being shifty" #If we get a normal TCP reply we know it doesn't else: mpopt = getMpOption(pkt.getlayer("TCP")) if mpopt is None: print "We have a normal TCP packet here" else: print "This header contains the following MPTCP options:", for mpo in mpopt: print mpo.name #If we get an MPACK then the host is HORRIBLY broken somehow else: #If we don't then this is just a vanilla TCP print "The host seems down?"
def ping(): #随机产生一个1-65535的IP的id位 ip_id=randint(1,65535) #随机产生一个1-65535的icmp的id位 icmp_id=randint(1,65535) #随机产生一个1-65535的icmp的序列号 icmp_seq=randint(1,65535) pkt = IP(dst='192.168.214.129', ttl=64, id=ip_id) / ICMP(id=icmp_id, seq=icmp_seq) # 发送包,超时时间为1秒,如果对端没有响应,则返回None,有响应则返回响应包 res = sr1(pkt, timeout=1, verbose=False) return res
def udp_scan(ip, port): try: packet = IP(dst=ip)/UDP(dorp=int(port),sport=randint(1,65535)) result = sr1(packet,timeout=5,verbose=0) time.sleep(0.1) if result is None: print("IP" + ip + str(port) + ":开放") except: print("扫描失败") '''if (str(type(result))) == "<class 'NoneType'>":
def udp_task(): #随机产生一个1-65535的IP的id位 ip_id = randint(1, 65535) #随机产生一个1-65535的icmp的id位 icmp_id = randint(1, 65535) #随机产生一个1-65535的icmp的序列号 icmp_seq = randint(1, 65535) pkt = IP(dst='192.168.214.129') / UDP(dport="53") # 发送包,超时时间为1秒,如果对端没有响应,则返回None,有响应则返回响应包 res = sr1(pkt, timeout=1, verbose=False) / b"hello" # res = sr1(pkt, timeout=1, verbose=False) return res
def defaultScan(targetIPList,portList,localIP=None,checkHostUp=True,reuseRandoms=False,timeout=None): #The option to reuse random numbers for "increased speed" if reuseRandoms: sourcAddr = localIP sport = randintb(16) initSeq = randintb(32) if timeout is None: timeout=5 #Form of results # results = {"targetIP": # [{"porta","ResponseType"}, # {"porta","ResponseType"}, # {"porta","ResponseType"} # ] # } results = {} for targetIP in targetIPList: print "Testing:", targetIP, localIP = localIP if localIP else get_local_ip_address(targetIP) gatewayIP = Route().route(str(targetIP))[2] if checkHostUp and gatewayIP == '0.0.0.0': print "... on local network...", arpadd = getmacbyip(str(targetIP)) if arpadd == None: print " not got MAC, skipping" continue if arpadd == "ff:ff:ff:ff:ff:ff": print "This appears to be localhost?" else: print " at ARP:", arpadd else: print "Via", gatewayIP, " Not on local network" for port in portList: pkt = makeMPCapableSyn(localIP,port,targetIP) response=sr1(pkt,timeout=timeout) if response is None: pass #print "No pkt received from ", targetIP,":", port else: processedResponse = processResponsePacketSimple(response,targetIP,localIP,port,timeout) if targetIP in results: if processedResponse is not None: results[targetIP].append(processedResponse) else: if processedResponse is not None: results[targetIP] = [processedResponse] #if True or port % 100 == 0: # print "\n\tChecking port: ", port return results
def send(self, message: str): crafted_domain = f"{Domain.encode(message)}.{self.domain}" packet = Packet.build_query( {"dst": self.dns_server, "dns": {"qname": crafted_domain}}, self.domain, ) answer = sr1(packet.packet, verbose=self.verb, timeout=1) if answer.haslayer(ICMP) or answer.haslayer(IPerror): logger.debug(answer.show()) logger.critical("Unreachable host or filtered port") return None return answer[DNS] if answer is not None else None
def exploit(): """ Establish an HTTP conenction and send a malicious HTTP request. """ os.system('iptables -A OUTPUT -p tcp --tcp-flags RST RST -s 172.16.1.1 -j DROP') src_port = random.randint(1024, 65535) ip_pkt = IP(src=src_ip, dst=dst_ip) tcp_pkt = TCP(dport=8080, sport=src_port, \ seq=random.randint(0, 100000), flags='S') syn_ack = sr1(ip_pkt / tcp_pkt) tcp_pkt = TCP(dport=8080, sport=src_port, \ seq=syn_ack[TCP].ack, ack=(syn_ack[TCP].seq + 1), flags='A') send(ip_pkt / tcp_pkt) http_msg = "GET /file.exe HTTP/1.1\r\nContent-Length: " \ + str(len(msg)) + "\r\n\r\n" + msg sr1(ip_pkt / tcp_pkt / http_msg, timeout=30) exit()
def joinScan(targetIPList,portList,localIP,reuseRandoms=False,timeout=None): #TODO: Add return details #TODO: Decide where this fits in the workflow, after an open TCP port maybe? #TODO: Decide how we want to handle the return values from this raise NotImplementedError #The option to reuse random numbers for "increased speed" if reuseRandoms: sourceAddr = localIP sport = randintb(16) initSeq = randintb(32) if timeout is None: timeout=5 for targetIP in targetIPList: for port in portList: #First send a packet and see if we get a TCP response pkt = makeMPCapableSyn(localIP,port,targetIP) response=sr1(pkt,timeout=timeout) if response is not None: #if we do then send an invalid MPTCP join and see if we get a RST pkt = makeJoinSyn(sourceAddr, port, targetIP) response2=sr1(pkt,timeout=timeout) #If we get a RST then we know this host supports MPTCP if response2 is None: print "Target supports MPTCP but is being shifty" #If we get a normal TCP reply we know it doesn't else: mpopt = getMpOption(pkt.getlayer("TCP")) if mpopt is None: print "We have a normal TCP packet here" else: print "This header contains the following MPTCP options:", for mpo in mpopt: print mpo.name #If we get an MPACK then the host is HORRIBLY broken somehow else: #If we don't then this is just a vanilla TCP print "The host seems down?"
def checkMPTCPSupportViaRST(port,target,timeout,localIP,MpCapAlreadyPassed=False): MpCapPassed = MpCapAlreadyPassed #TODO: Abstract this out more elegantly so i dont repeat code from elsewhere if not MpCapPassed: pkt = makeMPCapableSyn(localIP, port, target) response=sr1(pkt,timeout=timeout) if response and getMpOption(pkt.getlayer("TCP")) is not None: MpCapPassed = True if MpCapPassed: pkt = makeJoinSyn(localIP, port, target) response=sr1(pkt,timeout=timeout) #TODO: Add checks for other types of response (such as ICMP) #TODO: Make this clearer #Check for the flag with a mask print response.getlayer("TCP").flags if (0x04 & response.getlayer("TCP").flags) == 0x04: print "RST Test indicates MPTCP support" return True else: print "RST Test indicates host doesn't understand MPTCP" return False
def fragleak2(target, timeout=0.4, onlyasc=0): found={} try: while 1: p = sr1(IP(dst=target, options="\x00"*40, proto=200)/"XXXXYYYYYYYYYYYY",timeout=timeout,verbose=0) if not p: continue if Padding in p: leak = p[Padding].load if leak not in found: found[leak]=None linehexdump(leak,onlyasc=onlyasc) except: pass
def _ping(self, hosts: Queue, interface: str, results: set): self.logger.debug("{}: Starting ICMP ping thread.".format(threading.current_thread().name)) while True: ip = hosts.get() # type: IPAddress ip_str = str(ip) res = sr1(IP(dst=ip_str) / ICMP(), iface=interface, timeout=0.1, verbose=False) if res: node = NetworkNode() node.ip = ip node.mac = EUI(res.src) node.host = resolve_ip(res[IP].src) results.add(node) hosts.task_done()
def snmpwalk(dst, oid="1", community="public"): try: while True: r = sr1(IP(dst=dst) / UDP(sport=RandShort()) / SNMP(community=community, PDU=SNMPnext(varbindlist=[SNMPvarbind(oid=oid)])), timeout=2, chainCC=1, verbose=0, retry=2) # noqa: E501 if r is None: print("No answers") break if ICMP in r: print(repr(r)) break print("%-40s: %r" % (r[SNMPvarbind].oid.val, r[SNMPvarbind].value)) oid = r[SNMPvarbind].oid except KeyboardInterrupt: pass
def dyndns_del(nameserver, name, type="ALL", ttl=10): """Send a DNS delete message to a nameserver for "name" dyndns_del(nameserver, name, type="ANY", ttl=10) -> result code (0=ok) example: dyndns_del("ns1.toto.com", "dyn.toto.com") RFC2136 """ zone = name[name.find(".")+1:] r=sr1(IP(dst=nameserver)/UDP()/DNS(opcode=5, qd=[DNSQR(qname=zone, qtype="SOA")], ns=[DNSRR(rrname=name, type=type, rclass="ANY", ttl=0, rdata="")]), verbose=0, timeout=5) if r and r.haslayer(DNS): return r.getlayer(DNS).rcode else: return -1
def dyndns_add(nameserver, name, rdata, type="A", ttl=10): """Send a DNS add message to a nameserver for "name" to have a new "rdata" dyndns_add(nameserver, name, rdata, type="A", ttl=10) -> result code (0=ok) example: dyndns_add("ns1.toto.com", "dyn.toto.com", "127.0.0.1") RFC2136 """ zone = name[name.find(".")+1:] r=sr1(IP(dst=nameserver)/UDP()/DNS(opcode=5, qd=[DNSQR(qname=zone, qtype="SOA")], ns=[DNSRR(rrname=name, type="A", ttl=ttl, rdata=rdata)]), verbose=0, timeout=5) if r and r.haslayer(DNS): return r.getlayer(DNS).rcode else: return -1
''' Sample script to send a DNS query ''' import scapy from scapy.sendrecv import sendp, sniff, sr1 from scapy.all import IP, UDP, DNS, DNSQR google_DNS_service = '8.8.8.8' name_to_find = "fmi.unibuc.ro" network_layer = IP(dst = google_DNS_service) transport_layer = UDP(dport = 53) dns = DNS(rd = 1) dns_query = DNSQR(qname = name_to_find) dns.qd = dns_query pachet = network_layer / transport_layer / dns # send and recieve one packet answer = sr1(pachet) print answer[DNS].summary()