send_pcap is sent from the client to the server

import os
import random
import socket
import IPy
import traceback
import time
import copy
from scapy.all import sendp, PcapReader, wrpcap
from scapy.layers.inet6 import IPv6
from decimal import Decimal


def get_linux_client_eth2_mac():
    """
    :return:
    """
    mac = os.popen("/usr/bin/ifconfig | grep 'HWaddr' | awk '{print $5}'").read()
    mac = mac.split('\n')[2]
    return mac


def split_tcp_stream(pcap, i, length):
    """
    :param pcap:
    :param i:
    :param length;
    :return:
    """
    temp = copy.deepcopy(pcap)
    pcap.time = Decimal(str(pcap.time)) + Decimal("0.000001")
    temp['Raw'].load = pcap['Raw'].load[i: i + length]
    temp['TCP'].seq = pcap['TCP'].seq
    pcap['TCP'].seq = pcap['TCP'].seq + len(temp['Raw'].load)
    return temp


def mod_pcap(pcap_path, new_pcap_path, src_ip_list, test_ip_mac_info, run_speed='0', dst_ip_list=None, ip_dict=None):
    """
    :return:
    """
    src_ip = ""
    dst_ip = ""
    address_dict = dict()
    dst_address_dict = dict()
    need_send_list = list()
    filename = os.path.basename(pcap_path)
    start_time = int(time.time())
    try:
        src = test_ip_mac_info["client_mac"]
        dst = test_ip_mac_info["server_mac"]
        last_packet_time = None
        with PcapReader(pcap_path) as reader:
            for pcap in reader:
                pcap.src = src
                pcap.dst = dst
                if pcap.haslayer("ARP"):
                    continue
                elif pcap.haslayer("IP"):
                    if str(pcap.dst) == "ff:ff:ff:ff:ff:ff" or type(pcap.payload) == IPv6:
                        continue
                    else:
                        if pcap.haslayer("TCP") and (socket.ntohs(pcap["TCP"].flags) & 0x0400):
                            continue
                        if pcap["IP"].id == 28753 or pcap["IP"].id == 28752:
                            continue
                        if ip_dict:
                            if address_dict.get(pcap["IP"].src) or dst_address_dict.get(pcap["IP"].src):
                                if address_dict.get(pcap["IP"].src):
                                    pcap["IP"].src = address_dict[pcap["IP"].src]
                                if dst_address_dict.get(pcap["IP"].src):
                                    pcap["IP"].src = dst_address_dict[pcap["IP"].src]
                            else:
                                if pcap["IP"].src in ip_dict["src_ips"]:
                                    address_dict[pcap["IP"].src] = src_ip_list.pop()
                                    pcap["IP"].src = address_dict[pcap["IP"].src]
                                elif pcap["IP"].src in ip_dict["dst_ips"]:
                                    dst_address_dict[pcap["IP"].src] = dst_ip_list.pop()
                                    pcap["IP"].src = dst_address_dict[pcap["IP"].src]
                            # dst_ip
                            if address_dict.get(pcap["IP"].dst) or dst_address_dict.get(pcap["IP"].dst):
                                if address_dict.get(pcap["IP"].dst):
                                    pcap["IP"].dst = address_dict[pcap["IP"].dst]
                                if dst_address_dict.get(pcap["IP"].dst):
                                    pcap["IP"].dst = dst_address_dict[pcap["IP"].dst]
                            else:
                                if pcap["IP"].dst in ip_dict["src_ips"]:
                                    address_dict[pcap["IP"].dst] = src_ip_list.pop()
                                    pcap["IP"].dst = address_dict[pcap["IP"].dst]
                                elif pcap["IP"].dst in ip_dict["dst_ips"]:
                                    dst_address_dict[pcap["IP"].dst] = dst_ip_list.pop()
                                    pcap["IP"].dst = dst_address_dict[pcap["IP"].dst]
                        else:
                            if address_dict.get(pcap["IP"].src) or address_dict.get(pcap["IP"].dst):
                                if address_dict.get(pcap["IP"].src):
                                    pcap["IP"].src = address_dict[pcap["IP"].src]
                                if address_dict.get(pcap["IP"].dst):
                                    pcap["IP"].dst = address_dict[pcap["IP"].dst]
                            elif (pcap.haslayer("TCP") and str(pcap["TCP"].flags).find("S") != -1) or \
                                    not pcap.haslayer("TCP"):
                                if not src_ip:
                                    src_ip = src_ip_list.pop()
                                address_dict[pcap["IP"].src] = src_ip
                                pcap["IP"].src = src_ip
                                if dst_ip_list:
                                    if not dst_ip:
                                        dst_ip = dst_ip_list.pop()
                                    address_dict[pcap["IP"].dst] = dst_ip
                                    pcap["IP"].dst = dst_ip
                            else:
                                continue

                        pcap["IP"].len = None
                        pcap["IP"].chksum = None
                        if pcap.haslayer("UDP"):
                            pcap["UDP"].chksum = None
                        if pcap.haslayer("TCP"):
                            pcap["TCP"].chksum = None
                        if run_speed == '1':
                            if not last_packet_time:
                                last_packet_time = pcap.time
                            time_wait = pcap.time - last_packet_time
                            last_packet_time = pcap.time
                            if time_wait < 0:
                                time_wait = 0
                            time.sleep(time_wait)

                        split_length = 1024
                        if pcap.haslayer("TCP") and pcap.haslayer("Raw") and len(pcap) > split_length:
                            for i in range(0, len(pcap["Raw"].load), split_length):
                                p = split_tcp_stream(pcap, i, split_length)
                                if run_speed == '1':
                                    sendp(p, iface=SRC_IF, verbose=False)
                                else:
                                    need_send_list.append(p)
                        else:
                            if run_speed == '1':
                                sendp(pcap, iface=SRC_IF, verbose=False)
                            else:
                                need_send_list.append(pcap)
        if run_speed != '1':
            start_time = int(time.time())
            wrpcap(new_pcap_path, need_send_list)
            sendp(need_send_list, iface=SRC_IF, verbose=False)
            del need_send_list
        end_time = int(time.time())
        if ip_dict:
            src_ips = list(address_dict.values())
            dst_ips = list(dst_address_dict.values())
            return True, {"filename": filename, "pcap_path": pcap_path, "ip": src_ips, "dst_ip": dst_ips,
                          "start_pcap_time": start_time, "end_pcap_time": end_time}
        if dst_ip:
            return True, {"filename": filename, "pcap_path": pcap_path, "ip": src_ip, "dst_ip": dst_ip,
                          "start_pcap_time": start_time, "end_pcap_time": end_time}
        else:
            return True, {"filename": filename, "pcap_path": pcap_path, "ip": src_ip, "dst_ip": dst_ip,
                          "start_pcap_time": start_time, "end_pcap_time": end_time}
    except Exception:
        return False, "mod_pcap_src error: {}".format(traceback.format_exc())


def get_ips_by_random(mask=25):
  
    ip1 = random.randint(40, 100)
    ip2 = random.randint(1, 253)
    ip3 = random.randint(1, 253)
    ip = "{}.{}.{}.0".format(ip1, ip2, ip3)
    networks = IPy.IP("{}/{}".format(ip, mask))
    ip_list = list()
    for ip in networks:
       ip_list.append(str(ip))
    random.shuffle(ip_list)
    return ip_list


def get_ips_by_random1(mask=25):
    """
    inside
    :param mask:
    :return:
    """
    # ip1 = random.randint(1, 253)
    ip1 = 10

    ip2 = random.randint(1, 253)
    ip3 = random.randint(1, 253)
    ip = "{}.{}.{}.0".format(ip1, ip2, ip3)
    networks = IPy.IP("{}/{}".format(ip, mask))
    ip_list = list()
    for ip in networks:
        ip_list.append(str(ip))
    random.shuffle(ip_list)
    return ip_list


if __name__ == '__main__':
    SRC_IF = "eth0"
    DST_IF = "ens18"
    src_list = [get_ips_by_random()[0] for _ in range(1000)]
    dst_list = get_ips_by_random1() + get_ips_by_random1() + get_ips_by_random1() + get_ips_by_random1()
    test_mac_info = {
        "client_ip": "10.128.144.153", "client_mac": "fe:fc:fe:4b:56:7a",
        "server_ip": "10.128.144.152", "server_mac": "fe:fc:fe:78:15:41",
    }
    f = open('result.txt', 'w')
    pcap_path = "./a/"
    for i in os.listdir(pcap_path):
        result = mod_pcap(
            os.path.join(pcap_path, i),
            os.path.join(pcap_path, "tmp_" + i),
            src_list,
            test_mac_info,
            dst_ip_list=dst_list
        )
        print(result)
        f.write(str(result) + "\n")
    f.close()
    os.system('rm {}*'.format(os.path.join(pcap_path, "tmp_")))

Guess you like

Origin blog.csdn.net/qq_39306128/article/details/131937928