summaryrefslogtreecommitdiff
path: root/unordered_tcp_player.py
blob: abe93ee2c79bb59d6d05cd96f023d6359fef3d75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# -*- coding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import configparser
import subprocess
import random
from scapy.all import *
from scapy.contrib.mpls import *
from scapy.layers.inet import IP, TCP
from datetime import datetime

class UnorderedTcpPlayer:
    def send_unordered_tcp_traffic(self, traffic_data, script_type, debug_flag):
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), str(datetime.now().microsecond)[:3], "Begin to send tcp out of order traffic for effect verification.", flush=True)
        try:
            pcap = traffic_data["pcap_name"] + ".pcap"
            parse = configparser.ConfigParser()
            parse_dir = os.path.join("configuration_file.ini")
            parse.read(parse_dir, encoding="utf-8")
            packet_generator_path = parse.get("traffic_playback", "traffic_playback_workpath")
            intf = parse.get("tcpreplay", "intf")
            client_ip = parse.get("tcpreplay", "intf_1")
            server_ip = parse.get("tcpreplay", "intf_2")
            # client_ip = "192.64.{}.{}".format(random.randint(1, 254), random.randint(1, 254))
            # server_ip = "192.64.{}.{}".format(random.randint(1, 254), random.randint(1, 254))
            client_port = random.randint(1000, 60000)
            
            pcap_root_path = packet_generator_path + "/traffic_pcap/"
            pcap_path = packet_generator_path + "/traffic_pcap/" + pcap
            pkts = rdpcap(pcap_path)
            first_client_ip = pkts[0][Ether][IP].src

            new_pkts_list, new_pkts_list_sum = [], []
            current_time = time.time()
            sum_time = 5
            pkts_temp = copy.deepcopy(pkts)
            unit_time = sum_time / len(pkts_temp)
            pkt_count = 1
            for pkt in pkts_temp:
                pkt_count = pkt_count + 1
                if pkt[IP].src == first_client_ip:
                    pkt[IP].src = client_ip
                    pkt[IP].dst = server_ip
                    pkt[TCP].sport = client_port
                else:
                    pkt[IP].src = server_ip
                    pkt[IP].dst = client_ip
                    pkt[TCP].dport = client_port
                current_time += unit_time
                pkt.time = current_time
                new_pkts_list.append(pkt)
            new_pkts_list_sum.extend(copy.deepcopy(new_pkts_list))

            temp_pcap_name = "temp_{}.pcap".format(traffic_data["pcap_name"])
            temp_pcap_name_path = os.path.join(pcap_root_path, temp_pcap_name)
            # 写文件pcap
            wrpcap(temp_pcap_name_path, new_pkts_list_sum)
            
            # 乱序
            source_pkts = rdpcap(temp_pcap_name_path)
            packet_list = list(source_pkts)
            random.shuffle(packet_list)
            unorderd_pcap_name = "unorderd_{}.pcap".format(traffic_data["pcap_name"])
            unorderd_pcap_name_path = os.path.join(pcap_root_path, unorderd_pcap_name)
            wrpcap(unorderd_pcap_name_path, packet_list)
            
            # 流量包回放
            tcpreplay_cmd = "tcpreplay -i {} {}".format(intf, unorderd_pcap_name_path)
            p = subprocess.Popen(tcpreplay_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
            output, error = p.communicate()
            result = output + error
            return result
        except Exception as e:
            return f"Exception: {e}"
        finally:
            if os.path.exists(temp_pcap_name_path):
                os.remove(temp_pcap_name_path)
            if os.path.exists(unorderd_pcap_name_path):
                os.remove(unorderd_pcap_name_path)

if __name__ == '__main__':
    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), str(datetime.now().microsecond)[:3], "test")
    test_data = {
        "traffic": {
            "protocol": "unordered_tcp",
            "type": "unordered_tcp",
            "pcap_name": "tcp_https"
        }
    }
    traffic_data = test_data["traffic"]
    unordered_tcp = UnorderedTcpPlayer()
    unordered_tcp.send_unordered_tcp_traffic(traffic_data, "ui", False)