Browse Source

Some code cleanup and add current(not finished) version of MembersMgmtCommAttack

dustin.born 7 years ago
parent
commit
8bae1ec5e5

+ 175 - 51
code/Attack/MembersMgmtCommAttack.py

@@ -1,19 +1,31 @@
+from enum import Enum
+class MessageType(Enum):
+    """
+    Defines possible Message types
+    """
+
+    TIMEOUT = 3
+    SALITY_NL_REQUEST = 101
+    SALITY_NL_REPLY = 102
+    SALITY_HELLO = 103
+    SALITY_HELLO_REPLY = 104
+
 from random import randint, randrange, choice
 from random import randint, randrange, choice
 from collections import deque
 from collections import deque
+from scipy.stats import gamma
+from lea import Lea
 
 
 from Attack import BaseAttack
 from Attack import BaseAttack
 from Attack.AttackParameters import Parameter as Param
 from Attack.AttackParameters import Parameter as Param
 from Attack.AttackParameters import ParameterTypes
 from Attack.AttackParameters import ParameterTypes
 
 
-from ID2TLib import FileUtils
+from ID2TLib import FileUtils, PaddingGenerator
 from ID2TLib.PacketGenerator import PacketGenerator
 from ID2TLib.PacketGenerator import PacketGenerator
-from ID2TLib.IPGenerator import MappingIPGenerator 
+from ID2TLib.IPGenerator import IPGenerator 
 from ID2TLib.PcapAddressOperations import PcapAddressOperations
 from ID2TLib.PcapAddressOperations import PcapAddressOperations
-from ID2TLib.MapInputCSVToIDs import find_interval_with_most_comm
+from ID2TLib.MapInputCSVToIDs import find_interval_with_most_comm, determine_id_roles
 from ID2TLib.MacAddressGenerator import MacAddressGenerator
 from ID2TLib.MacAddressGenerator import MacAddressGenerator
-from ID2TLib.MessageType import MessageType
-from ID2TLib.genRandPort import generateRandomPort
-from ID2TLib import PaddingGenerator
+from ID2TLib.PortGenerator import gen_random_server_port
 
 
 class MembersMgmtCommAttack(BaseAttack.BaseAttack):
 class MembersMgmtCommAttack(BaseAttack.BaseAttack):
     def __init__(self):
     def __init__(self):
@@ -53,11 +65,16 @@ class MembersMgmtCommAttack(BaseAttack.BaseAttack):
             Param.PACKET_PADDING: ParameterTypes.TYPE_PADDING
             Param.PACKET_PADDING: ParameterTypes.TYPE_PADDING
         }
         }
 
 
+        # create dict with MessageType values for fast name lookup
+        self.msg_types = {}
+        for msg_type in MessageType:
+            self.msg_types[msg_type.value] = msg_type
+
     def init_params(self):
     def init_params(self):
         """
         """
         Initialize some parameters of this communication-attack using the user supplied command line parameters.
         Initialize some parameters of this communication-attack using the user supplied command line parameters.
-		The remaining parameters are implicitly set in the provided data file. Note: the timestamps in the file 
-		have to be sorted in ascending order
+        The remaining parameters are implicitly set in the provided data file. Note: the timestamps in the file 
+        have to be sorted in ascending order
 
 
         :param statistics: Reference to a statistics object.
         :param statistics: Reference to a statistics object.
         """
         """
@@ -65,10 +82,16 @@ class MembersMgmtCommAttack(BaseAttack.BaseAttack):
         self.DEFAULT_XML_PATH = "resources/MembersMgmtComm_example.xml"
         self.DEFAULT_XML_PATH = "resources/MembersMgmtComm_example.xml"
         # threshold for ID to be recognized as rather common in communication
         # threshold for ID to be recognized as rather common in communication
         self.MOST_COMMON_THRES = 0.08
         self.MOST_COMMON_THRES = 0.08
+        # probability for initiator ID to be local
+        self.PROB_INIT_IS_LOCAL = 0.8
+        # probability for responder ID to be local if comm_type is mixed
+        self.PROB_RESPND_IS_LOCAL = 0.2
 
 
         # PARAMETERS: initialize with default values
         # PARAMETERS: initialize with default values
         # (values are overwritten if user specifies them)
         # (values are overwritten if user specifies them)
+        # print(self.statistics.get_packet_count())
         self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
         self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
+        # print(self.get_param_value(Param.INJECT_AT_TIMESTAMP))
         self.add_param_value(Param.PACKETS_PER_SECOND, 0)
         self.add_param_value(Param.PACKETS_PER_SECOND, 0)
         self.add_param_value(Param.FILE_XML, self.DEFAULT_XML_PATH)
         self.add_param_value(Param.FILE_XML, self.DEFAULT_XML_PATH)
         self.add_param_value(Param.ATTACK_DURATION, 100)
         self.add_param_value(Param.ATTACK_DURATION, 100)
@@ -86,6 +109,30 @@ class MembersMgmtCommAttack(BaseAttack.BaseAttack):
 
 
         
         
     def generate_attack_pcap(self):
     def generate_attack_pcap(self):
+        def add_ids_to_config(ids_to_add, existing_ips, new_ips, bot_configs, idtype="local", router_mac=""):
+            ids = ids_to_add.copy()
+            macgen = MacAddressGenerator()
+            for ip in existing_ips:
+                random_id = choice(tuple(ids))
+                mac = self.statistics.process_db_query("macAddress(IPAddress=%s)" % ip)
+                bot_configs[random_id] = {"Type": idtype, "IP": ip, "MAC": mac}
+                ids.remove(random_id)
+
+            for ip in new_ips:
+                random_id = choice(tuple(ids))
+                if idtype == "local":
+                    mac = macgen.random_mac()
+                elif idtype == "external":
+                    mac = router_mac
+                bot_configs[random_id] = {"Type": idtype, "IP": ip, "MAC": mac}
+                ids.remove(random_id)
+
+        def index_increment(number: int, max: int):
+            if number + 1 < max:
+                return number + 1
+            else:
+                return 0
+
         # parse input CSV or XML
         # parse input CSV or XML
         filepath_xml = self.get_param_value(Param.FILE_XML)
         filepath_xml = self.get_param_value(Param.FILE_XML)
         filepath_csv = self.get_param_value(Param.FILE_CSV)
         filepath_csv = self.get_param_value(Param.FILE_CSV)
@@ -105,20 +152,24 @@ class MembersMgmtCommAttack(BaseAttack.BaseAttack):
             print("Error: There is no interval in the given CSV/XML that has enough communication")
             print("Error: There is no interval in the given CSV/XML that has enough communication")
             return 0, None
             return 0, None
 
 
-        mapped_ids, packet_start_idx, packet_end_idx = comm_interval["IDs"], comm_interval["Start"], comm_interval["End"]
+        mapped_ids, id_comms, packet_start_idx, packet_end_idx = comm_interval["IDs"], comm_interval["Comms"], comm_interval["Start"], comm_interval["End"]
+
+        # print start and end time of mapped interval
+        # print(abstract_packets[packet_start_idx]["Time"])
+        # print(abstract_packets[packet_end_idx]["Time"])
 
 
         # determine most common communicating IDs
         # determine most common communicating IDs
-        total_mentions = 0
-        most_common_thres = self.MOST_COMMON_THRES
-        most_common_ids = {}
-        for id_ in mapped_ids:
-            total_mentions += mapped_ids[id_]
-
-        for id_ in mapped_ids:
-            count = mapped_ids[id_]
-            mentions_percentage = count / total_mentions
-            if mentions_percentage >= most_common_thres:
-                most_common_ids[id_] = mentions_percentage
+        # total_mentions = 0
+        # most_common_thres = self.MOST_COMMON_THRES
+        # most_common_ids = {}
+        # for id_ in mapped_ids:
+        #     total_mentions += mapped_ids[id_]
+
+        # for id_ in mapped_ids:
+        #     count = mapped_ids[id_]
+        #     mentions_percentage = count / total_mentions
+        #     if mentions_percentage >= most_common_thres:
+        #         most_common_ids[id_] = mentions_percentage
 
 
         # determine amount of reused IPs
         # determine amount of reused IPs
         reuse_percent_total = self.get_param_value(Param.IP_REUSE_TOTAL)
         reuse_percent_total = self.get_param_value(Param.IP_REUSE_TOTAL)
@@ -129,41 +180,102 @@ class MembersMgmtCommAttack(BaseAttack.BaseAttack):
         reuse_count_local = int(reuse_percent_total * reuse_percent_local * len(mapped_ids))
         reuse_count_local = int(reuse_percent_total * reuse_percent_local * len(mapped_ids))
 
 
         # create bot IP and MAC configs
         # create bot IP and MAC configs
-        macgen = MacAddressGenerator() 
+        ipgen = IPGenerator()
         comm_type = self.get_param_value(Param.COMM_TYPE)
         comm_type = self.get_param_value(Param.COMM_TYPE)
         pcapops = PcapAddressOperations(self.statistics)
         pcapops = PcapAddressOperations(self.statistics)
+        router_mac = pcapops.get_probable_router_mac()
         bot_configs = {}
         bot_configs = {}
-
-        # where IP is external, already set MAC to router MAC here
-        if comm_type == "mixed":
-            ...
-        elif comm_type == "external":
-            ...
-        elif comm_type == "local":
-            existing_local_ips = pcapops.get_existing_priv_ips(reuse_count_local)
-            count_avail = min(reuse_count_local, len(existing_local_ips))
+        external_ids = set()
+        local_ids = set()
+        # print(self.get_param_value(Param.INJECT_AT_TIMESTAMP))
+        if comm_type == "local":
+            local_ids = set(mapped_ids.keys())
+        else:
+            init_local_or_external = Lea.fromValFreqsDict({"local": self.PROB_INIT_IS_LOCAL*100, "external": (1-self.PROB_INIT_IS_LOCAL)*100})
+            mixed_respnd_is_local = Lea.fromValFreqsDict({"local": self.PROB_RESPND_IS_LOCAL*100, "external": (1-self.PROB_RESPND_IS_LOCAL)*100})
             ids = set(mapped_ids.keys())
             ids = set(mapped_ids.keys())
-            for ip in existing_local_ips:
-                random_id = choice(tuple(ids))
-                mac = self.statistics.process_db_query("macAddress(IPAddress=%s)" % ip)
-                bot_configs[random_id] = {"Type": "local", "IP": ip, "MAC":mac}
-                ids.remove(random_id)
+            init_ids, respnd_ids, both_ids = determine_id_roles(abstract_packets[packet_start_idx:packet_end_idx+1], ids)
+
+            # assign IDs in 'both' local everytime for mixed? 
+            initiators = list(init_ids) + list(both_ids)
+            for id_ in initiators:
+                if id_ in local_ids or id_ in external_ids:
+                    continue
+
+                pos = init_local_or_external.random()          
+                if pos == "local":
+                    local_ids.add(id_) 
+                    for id_comm in id_comms:
+                        ids = id_comm.split("-")
+                        other = ids[0] if id_ == ids[1] else ids[1] 
+                        
+                        # what if before other was external ...
+                        if other in local_ids or other in external_ids:
+                            continue 
+
+                        if comm_type == "mixed":
+                            other_pos = mixed_respnd_is_local.random()
+                            if other_pos == "local":
+                                local_ids.add(other)
+                            elif other_pos == "external":
+                                external_ids.add(other)
+                        elif comm_type == "external":
+                            if not other in initiators:
+                                external_ids.add(other)
+
+                elif pos == "external":
+                    external_ids.add(id_)
+                    for id_comm in id_comms:
+                        ids = id_comm.split("-")
+                        other = ids[0] if id_ == ids[1] else ids[1] 
+                        
+                        # what if before other was external ...
+                        if other in local_ids or other in external_ids:
+                            continue 
+                        if not other in initiators:
+                            local_ids.add(other)
+
+
+        # print(initiators)
+        # print(local_ids)
+        # print(external_ids)
+
+        number_local_ids, number_external_ids = len(local_ids), len(external_ids)
+        if number_local_ids > 0:
+            reuse_count_local = int(reuse_percent_total * reuse_percent_local * number_local_ids) 
+            existing_local_ips = pcapops.get_existing_priv_ips(reuse_count_local)
+            new_local_ips = pcapops.get_new_priv_ips(number_local_ids - len(existing_local_ips))
+            add_ids_to_config(local_ids, existing_local_ips, new_local_ips, bot_configs)
 
 
-            count_remaining = number_bots - count_avail
-            new_local_ips = pcapops.get_new_priv_ips(count_remaining)
-            for ip in new_local_ips:
-                random_id = choice(tuple(ids))
-                mac = macgen.random_mac()
-                bot_configs[random_id] = {"Type": "local", "IP": ip, "MAC": mac}
-                ids.remove(random_id)
+        if number_external_ids > 0:
+            reuse_count_external = int(reuse_percent_total * reuse_percent_external * number_external_ids) 
+            existing_external_ips = pcapops.get_existing_external_ips(reuse_count_external)
+            remaining = len(external_ids) - len(existing_external_ips)
+            new_external_ips = [ipgen.random_ip() for _ in range(remaining)]
+            add_ids_to_config(external_ids, existing_external_ips, new_external_ips, bot_configs, idtype="external", router_mac=router_mac)
 
 
+        # print(bot_configs)
 
 
         # create bot port configs
         # create bot port configs
         for bot in bot_configs:
         for bot in bot_configs:
-            bot_configs[bot]["Port"] = generateRandomPort()    
-
-        if filepath_csv and filepath_xml == self.DEFAULT_XML_PATH:
-            filepath_xml = FileUtils.parse_csv_to_xml(filepath_csv) 
+            bot_configs[bot]["Port"] = gen_random_server_port()    
+
+        # create realistic ttl for every bot
+        # Gamma distribution parameters derived from MAWI 13.8G dataset
+        ids = bot_configs.keys()
+        alpha, loc, beta = (2.3261710235, -0.188306914406, 44.4853123884)
+        gd = gamma.rvs(alpha, loc=loc, scale=beta, size=len(ids))
+
+        for pos, bot in enumerate(bot_configs):
+            is_invalid = True
+            pos_max = len(gd)
+            while is_invalid:
+                ttl = int(round(gd[pos]))
+                if 0 < ttl < 256:  # validity check
+                    is_invalid = False
+                else:
+                    pos = index_increment(pos, pos_max)
+            bot_configs[bot]["TTL"] = ttl
 
 
         # Setup initial parameters for packet creation
         # Setup initial parameters for packet creation
         BUFFER_SIZE = 1000
         BUFFER_SIZE = 1000
@@ -180,7 +292,7 @@ class MembersMgmtCommAttack(BaseAttack.BaseAttack):
         nl_requests = {}
         nl_requests = {}
 
 
         # create packets to write to pcap file
         # create packets to write to pcap file
-        for abst_packet in abstract_packets[packet_start_idx:packet_end_idx]:
+        for abst_packet in abstract_packets[packet_start_idx:packet_end_idx+1]:
             # map/retrieve addresses to ids from input file
             # map/retrieve addresses to ids from input file
             id_src, id_dst = abst_packet["Src"], abst_packet["Dst"]
             id_src, id_dst = abst_packet["Src"], abst_packet["Dst"]
             if (not id_src in bot_configs) or (not id_dst in bot_configs):
             if (not id_src in bot_configs) or (not id_dst in bot_configs):
@@ -189,6 +301,15 @@ class MembersMgmtCommAttack(BaseAttack.BaseAttack):
             ip_src, ip_dst = bot_configs[id_src]["IP"], bot_configs[id_dst]["IP"]
             ip_src, ip_dst = bot_configs[id_src]["IP"], bot_configs[id_dst]["IP"]
             mac_src, mac_dst = bot_configs[id_src]["MAC"], bot_configs[id_dst]["MAC"]
             mac_src, mac_dst = bot_configs[id_src]["MAC"], bot_configs[id_dst]["MAC"]
             port_src, port_dst = bot_configs[id_src]["Port"], bot_configs[id_dst]["Port"]
             port_src, port_dst = bot_configs[id_src]["Port"], bot_configs[id_dst]["Port"]
+            ttl = bot_configs[id_src]["TTL"]
+            type_src, type_dst = bot_configs[id_src]["Type"], bot_configs[id_dst]["Type"]
+
+            if type_src == "external" and type_dst == "external":
+                continue
+            if comm_type == "external":
+                if type_src == "local" and type_dst == "local":
+                    continue
+
 
 
             # update timestamps and duration
             # update timestamps and duration
             file_timestamp = float(abst_packet["Time"])
             file_timestamp = float(abst_packet["Time"])
@@ -203,13 +324,16 @@ class MembersMgmtCommAttack(BaseAttack.BaseAttack):
                 break
                 break
         
         
             # create ip packet and add to packets list
             # create ip packet and add to packets list
-            message_type = int(abst_packet["Type"])
+            message_type = self.msg_types[int(abst_packet["Type"])]
             nl_size = 0
             nl_size = 0
 
 
-            if message_type == MessageType.SALITY_NL_REPLY.value:
+            if message_type == MessageType.SALITY_NL_REPLY:
                 nl_size = randint(1, 25)
                 nl_size = randint(1, 25)
+            elif message_type == MessageType.TIMEOUT:
+                continue
 
 
-            packet = pkt_gen.generate_MMCOM_Packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst, port_src=port_src, port_dst=port_dst, message_type=message_type, neighborlist_entries=nl_size)
+            packet = pkt_gen.generate_mmcom_packet(ip_src=ip_src, ip_dst=ip_dst, ttl=ttl, mac_src=mac_src, mac_dst=mac_dst, 
+                port_src=port_src, port_dst=port_dst, message_type=message_type, neighborlist_entries=nl_size)
             PaddingGenerator.add_padding(packet, padding)
             PaddingGenerator.add_padding(packet, padding)
 
 
             packet.time = pcap_timestamp
             packet.time = pcap_timestamp
@@ -217,7 +341,7 @@ class MembersMgmtCommAttack(BaseAttack.BaseAttack):
             total_pkts += 1
             total_pkts += 1
 
 
             # Store timestamp of first packet (for attack label)
             # Store timestamp of first packet (for attack label)
-            if total_pkts <= 1 :
+            if total_pkts <= 1:
                 self.attack_start_utime = packets[0].time
                 self.attack_start_utime = packets[0].time
             elif total_pkts % BUFFER_SIZE == 0: # every 1000 packets write them to the pcap file (append)
             elif total_pkts % BUFFER_SIZE == 0: # every 1000 packets write them to the pcap file (append)
                 packets = list(packets)
                 packets = list(packets)

+ 0 - 25
code/ID2TLib/IPPacketGenerator.py

@@ -1,25 +0,0 @@
-from scapy.layers.inet import IP, Ether, TCP
-from scapy.packet import Raw
-
-def generate_ip_packet(ip_src:str="192.168.64.32", ip_dst:str="192.168.64.48", mac_src:str="56:6D:D9:BC:70:1C", 
-					   mac_dst:str="F4:2B:95:B3:0E:1A", port_src:int=1337, port_dst:int=6442, tcpflags:str="S", payload:str=""):
-	"""
-    Builds an IP packet with the values specified by the caller. If a parameter was not specified by the caller, 
-    it is set to a default value.
-    
-    :param ip_src: the source IP address of the IP header
-    :param ip_dst the destination IP address of the IP header
-    :param mac_src: the source MAC address of the MAC header
-    :param mac_dst: the destination MAC address of the MAC header
-    :param port_src: the source port of the TCP header
-    :param port_dst: the destination port of the TCP header
-    :param tcpflags: the TCP flags of the TCP header
-    :param payload: the payload of the packet
-    :return: the corresponding IP packet
-    """
-
-	ether = Ether(src=mac_src, dst=mac_dst)
-	ip = IP(src=ip_src, dst=ip_dst)
-	tcp = TCP(sport=port_src, dport=port_dst, flags=tcpflags)
-	packet = ether / ip / tcp / Raw(load=payload)
-	return packet

+ 57 - 5
code/ID2TLib/MapInputCSVToIDs.py

@@ -1,8 +1,9 @@
+from Attack.MembersMgmtCommAttack import MessageType
 
 
 # needed because of machine inprecision. E.g A time difference of 0.1s is stored as >0.1s
 # needed because of machine inprecision. E.g A time difference of 0.1s is stored as >0.1s
 EPS_TOLERANCE = 1e-13  # works for a difference of 0.1, no less
 EPS_TOLERANCE = 1e-13  # works for a difference of 0.1, no less
 
 
-def find_interval_with_most_comm(packets, number_ids: int, max_int_time: float):
+def find_interval_with_most_comm(packets: list, number_ids: int, max_int_time: float):
     """
     """
     Finds a time interval of the given seconds where the given number of ids communicate among themselves the most.
     Finds a time interval of the given seconds where the given number of ids communicate among themselves the most.
     
     
@@ -100,21 +101,30 @@ def find_interval_with_most_comm(packets, number_ids: int, max_int_time: float):
 
 
         return picked_ids, total_msg_count
         return picked_ids, total_msg_count
 
 
-    def get_indv_id_counts(picked_ids: dict, msg_counts: dict):
+    def get_indv_id_counts_and_comms(picked_ids: dict, msg_counts: dict):
+        """ 
+        Retrieves the total mentions of one ID in the communication pattern
+        and all communication entries that include only picked IDs.
+        """
         indv_id_counts = {}
         indv_id_counts = {}
+        id_comms = set()
         for msg in msg_counts:
         for msg in msg_counts:
             ids = msg.split("-")
             ids = msg.split("-")
             if ids[0] in picked_ids and ids[1] in picked_ids:
             if ids[0] in picked_ids and ids[1] in picked_ids:
+                msg_other_dir = "{}-{}".format(ids[1], ids[0])
+                if (not msg in id_comms) and (not msg_other_dir in id_comms):
+                    id_comms.add(msg)
+
                 for id_ in ids:
                 for id_ in ids:
                     if id_ in indv_id_counts:
                     if id_ in indv_id_counts:
                         indv_id_counts[id_] += msg_counts[msg]
                         indv_id_counts[id_] += msg_counts[msg]
                     else:
                     else:
                         indv_id_counts[id_] = msg_counts[msg]
                         indv_id_counts[id_] = msg_counts[msg]
 
 
-        return indv_id_counts
+        return indv_id_counts, id_comms
 
 
 
 
-    # first find all possible intervals that contain enough ids that communicate among themselves
+    # first find all possible intervals that contain enough IDs that communicate among themselves
     idx_low, idx_high = 0, 0
     idx_low, idx_high = 0, 0
     msg_counts = dict()
     msg_counts = dict()
     possible_intervals = []
     possible_intervals = []
@@ -174,7 +184,49 @@ def find_interval_with_most_comm(packets, number_ids: int, max_int_time: float):
     for j, interval in enumerate(summed_intervals):
     for j, interval in enumerate(summed_intervals):
         idx = sum_intervals_idxs[j]
         idx = sum_intervals_idxs[j]
         msg_counts_picked = possible_intervals[idx][0]
         msg_counts_picked = possible_intervals[idx][0]
-        indv_id_counts = get_indv_id_counts(interval["IDs"], msg_counts_picked)
+        indv_id_counts, id_comms = get_indv_id_counts_and_comms(interval["IDs"], msg_counts_picked)
         interval["IDs"] = indv_id_counts
         interval["IDs"] = indv_id_counts
+        interval["Comms"] = id_comms
 
 
     return summed_intervals
     return summed_intervals
+
+
+def determine_id_roles(packets: list, all_ids: set):
+    """
+    Determine the role of every mapped ID. The role can be initiator, responder or both.
+    :param packets: the mapped section of abstract packets
+    :param all_ids: all IDs that were mapped/chosen
+    :return: a dict that for every ID contains its role
+    """
+    init_ids, respnd_ids, both_ids = set(), set(), set()
+    def process_initiator(id_: str):
+        if id_ in both_ids:
+            pass
+        elif not id_ in respnd_ids:
+            init_ids.add(id_)
+        elif id_ in respnd_ids:
+            respnd_ids.remove(id_)
+            both_ids.add(id_)
+
+    def process_responder(id_: str):
+        if id_ in both_ids:
+            pass
+        elif not id_ in init_ids:
+            respnd_ids.add(id_)
+        elif id_ in init_ids:
+            init_ids.remove(id_)
+            both_ids.add(id_)
+
+    for packet in packets:
+        id_src, id_dst, msg_type = packet["Src"], packet["Dst"], packet["Type"]
+        if (not id_src in all_ids) or (not id_dst in all_ids):
+            continue
+        if int(msg_type) in {MessageType.SALITY_HELLO.value, MessageType.SALITY_NL_REQUEST.value}:
+            process_initiator(id_src)
+            process_responder(id_dst)
+        elif int(msg_type) in {MessageType.SALITY_HELLO_REPLY.value, MessageType.SALITY_NL_REPLY.value}:
+            process_initiator(id_dst)
+            process_responder(id_src)
+
+    return init_ids, respnd_ids, both_ids
+

+ 0 - 12
code/ID2TLib/MessageType.py

@@ -1,12 +0,0 @@
-from enum import Enum
-
-class MessageType(Enum):
-	"""
-	Defines possible Message types
-	"""
-
-	TIMEOUT = 3
-	SALITY_NL_REQUEST = 101
-	SALITY_NL_REPLY = 102
-	SALITY_HELLO = 103
-	SALITY_HELLO_REPLY = 104

+ 19 - 19
code/ID2TLib/PacketGenerator.py

@@ -1,4 +1,4 @@
-from ID2TLib.MessageType import MessageType
+from Attack.MembersMgmtCommAttack import MessageType
 
 
 import ID2TLib.PayloadGenerator as PayloadGenerator
 import ID2TLib.PayloadGenerator as PayloadGenerator
 
 
@@ -11,8 +11,8 @@ class PacketGenerator():
 		super(PacketGenerator, self).__init__()
 		super(PacketGenerator, self).__init__()
 		self.protocol = protocol
 		self.protocol = protocol
 
 
-	def generate_Packet(self, ip_src: str="192.168.64.32", ip_dst: str="192.168.64.48", mac_src: str="56:6D:D9:BC:70:1C",
-		mac_dst: str="F4:2B:95:B3:0E:1A", port_src: int=1337, port_dst: int=6442,
+	def generate_packet(self, ip_src: str="192.168.64.32", ip_dst: str="192.168.64.48", mac_src: str="56:6D:D9:BC:70:1C",
+		mac_dst: str="F4:2B:95:B3:0E:1A", port_src: int=1337, port_dst: int=6442, ttl: int=64,
 		tcpflags: str="S", payload: str=""):
 		tcpflags: str="S", payload: str=""):
 		"""
 		"""
 		Creates a Packet with the specified Values for the current protocol
 		Creates a Packet with the specified Values for the current protocol
@@ -30,18 +30,18 @@ class PacketGenerator():
 
 
 	    #directly generate packet with the current protocol
 	    #directly generate packet with the current protocol
 		if(self.protocol == "udp"):
 		if(self.protocol == "udp"):
-			packet = generate_udp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst,
+			packet = generate_udp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst, ttl=ttl,
 				port_src=port_src, port_dst=port_dst, payload=payload)
 				port_src=port_src, port_dst=port_dst, payload=payload)
 		elif(self.protocol == "tcp"):
 		elif(self.protocol == "tcp"):
-			packet = generate_tcp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst,
+			packet = generate_tcp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst, ttl=ttl,
 				port_src=port_src, port_dst=port_dst, tcpflags=tcpflags, payload=payload)
 				port_src=port_src, port_dst=port_dst, tcpflags=tcpflags, payload=payload)
 		#else raise exception?
 		#else raise exception?
 		return packet
 		return packet
 		
 		
 
 
-	def generate_MMCOM_Packet(self, ip_src: str="192.168.64.32", ip_dst: str="192.168.64.48", mac_src: str="56:6D:D9:BC:70:1C",
-			mac_dst: str="F4:2B:95:B3:0E:1A", port_src: int=1337, port_dst: int=6442, tcpflags: str="S",
-			message_type: MessageType=103, neighborlist_entries: int=1):
+	def generate_mmcom_packet(self, ip_src: str="192.168.64.32", ip_dst: str="192.168.64.48", mac_src: str="56:6D:D9:BC:70:1C",
+			mac_dst: str="F4:2B:95:B3:0E:1A", port_src: int=1337, port_dst: int=6442, tcpflags: str="S", ttl: int=64,
+			message_type: MessageType=MessageType.SALITY_HELLO, neighborlist_entries: int=1):
 		"""
 		"""
 		Creates a Packet for Members-Management-Communication with the specified Values and the current protocol
 		Creates a Packet for Members-Management-Communication with the specified Values and the current protocol
 
 
@@ -58,32 +58,32 @@ class PacketGenerator():
 	    """
 	    """
 
 
 	    #Determine length of the payload that has to be generated
 	    #Determine length of the payload that has to be generated
-		if(message_type == MessageType.SALITY_HELLO.value):
+		if(message_type == MessageType.SALITY_HELLO):
 			payload_len = 0
 			payload_len = 0
-		elif(message_type == MessageType.SALITY_HELLO_REPLY.value):
+		elif(message_type == MessageType.SALITY_HELLO_REPLY):
 			payload_len = 22
 			payload_len = 22
-		elif(message_type == MessageType.SALITY_NL_REQUEST.value):
+		elif(message_type == MessageType.SALITY_NL_REQUEST):
 			payload_len = 28
 			payload_len = 28
-		elif(message_type == MessageType.SALITY_NL_REPLY.value):
+		elif(message_type == MessageType.SALITY_NL_REPLY):
 			payload_len = 24 + 6 * neighborlist_entries
 			payload_len = 24 + 6 * neighborlist_entries
 		else:
 		else:
 			payload_len = 0
 			payload_len = 0
 
 
 		#generate payload
 		#generate payload
-		payload = PayloadGenerator.generate_Payload(payload_len)
+		payload = PayloadGenerator.generate_payload(payload_len)
 
 
 		#generate the packet
 		#generate the packet
 		if(self.protocol == "udp"):
 		if(self.protocol == "udp"):
-			packet = generate_udp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst,
+			packet = generate_udp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst, ttl=ttl,
 				port_src=port_src, port_dst=port_dst, payload=payload)
 				port_src=port_src, port_dst=port_dst, payload=payload)
 		elif(self.protocol == "tcp"):
 		elif(self.protocol == "tcp"):
-			packet = generate_tcp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst,
+			packet = generate_tcp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst, ttl=ttl,
 				port_src=port_src, port_dst=port_dst, tcpflags=tcpflags, payload=payload)
 				port_src=port_src, port_dst=port_dst, tcpflags=tcpflags, payload=payload)
 		#else raise exception?
 		#else raise exception?
 		return packet
 		return packet
 
 
 
 
-def generate_tcp_packet(ip_src:str="192.168.64.32", ip_dst:str="192.168.64.48", mac_src:str="56:6D:D9:BC:70:1C", 
+def generate_tcp_packet(ip_src:str="192.168.64.32", ip_dst:str="192.168.64.48", mac_src:str="56:6D:D9:BC:70:1C", ttl: int=64,
 					   mac_dst:str="F4:2B:95:B3:0E:1A", port_src:int=1337, port_dst:int=6442, tcpflags:str="S", payload:str=""):
 					   mac_dst:str="F4:2B:95:B3:0E:1A", port_src:int=1337, port_dst:int=6442, tcpflags:str="S", payload:str=""):
 	"""
 	"""
     Builds an TCP packet with the values specified by the caller. If a parameter was not specified by the caller, 
     Builds an TCP packet with the values specified by the caller. If a parameter was not specified by the caller, 
@@ -101,13 +101,13 @@ def generate_tcp_packet(ip_src:str="192.168.64.32", ip_dst:str="192.168.64.48",
     """
     """
 
 
 	ether = Ether(src=mac_src, dst=mac_dst)
 	ether = Ether(src=mac_src, dst=mac_dst)
-	ip = IP(src=ip_src, dst=ip_dst)
+	ip = IP(src=ip_src, dst=ip_dst, ttl=ttl)
 	tcp = TCP(sport=port_src, dport=port_dst, flags=tcpflags)
 	tcp = TCP(sport=port_src, dport=port_dst, flags=tcpflags)
 	packet = ether / ip / tcp / Raw(load=payload)
 	packet = ether / ip / tcp / Raw(load=payload)
 	return packet
 	return packet
 
 
 
 
-def generate_udp_packet(ip_src:str="192.168.64.32", ip_dst:str="192.168.64.48", mac_src:str="56:6D:D9:BC:70:1C", 
+def generate_udp_packet(ip_src:str="192.168.64.32", ip_dst:str="192.168.64.48", mac_src:str="56:6D:D9:BC:70:1C", ttl: int=64,
 					   mac_dst:str="F4:2B:95:B3:0E:1A", port_src:int=1337, port_dst:int=6442, payload:str=""):
 					   mac_dst:str="F4:2B:95:B3:0E:1A", port_src:int=1337, port_dst:int=6442, payload:str=""):
 	"""
 	"""
     Builds an UDP packet with the values specified by the caller. If a parameter was not specified by the caller, 
     Builds an UDP packet with the values specified by the caller. If a parameter was not specified by the caller, 
@@ -126,7 +126,7 @@ def generate_udp_packet(ip_src:str="192.168.64.32", ip_dst:str="192.168.64.48",
     """
     """
 
 
 	ether = Ether(src=mac_src, dst=mac_dst)
 	ether = Ether(src=mac_src, dst=mac_dst)
-	ip = IP(src=ip_src, dst=ip_dst)
+	ip = IP(src=ip_src, dst=ip_dst, ttl=ttl)
 	udp = UDP(sport=port_src, dport=port_dst)
 	udp = UDP(sport=port_src, dport=port_dst)
 	packet = ether / ip / udp / Raw(load=payload)
 	packet = ether / ip / udp / Raw(load=payload)
 	return packet
 	return packet

+ 1 - 2
code/ID2TLib/PaddingGenerator.py

@@ -11,11 +11,10 @@ def add_padding(packet, bytes_padding = 0, user_padding=True):
     :return: the initial packet, extended with the wanted amount of bytes of padding
     :return: the initial packet, extended with the wanted amount of bytes of padding
     '''
     '''
 
 
-    # should equal_length be limited by this?
     if(user_padding and bytes_padding > 100):
     if(user_padding and bytes_padding > 100):
         bytes_padding = 100
         bytes_padding = 100
 
 
-    payload = PayloadGenerator.generate_Payload(bytes_padding)
+    payload = PayloadGenerator.generate_payload(bytes_padding)
     packet[Raw].load += Raw(load=payload).load
     packet[Raw].load += Raw(load=payload).load
     return packet
     return packet
 
 

+ 2 - 1
code/ID2TLib/PayloadGenerator.py

@@ -1,11 +1,12 @@
 from numpy.random import bytes
 from numpy.random import bytes
 
 
-def generate_Payload(size:int=0):
+def generate_payload(size:int=0):
 
 
 	"""
 	"""
 	Generates a payload of random bytes of the given amount
 	Generates a payload of random bytes of the given amount
 
 
 	:param size: number of generated bytes
 	:param size: number of generated bytes
+    :return: the generated payload
 	"""
 	"""
 
 
 	payload = bytes(size)
 	payload = bytes(size)

+ 8 - 7
code/ID2TLib/PcapAddressOperations.py

@@ -72,8 +72,8 @@ class PcapAddressOperations():
             retr_priv_ips.append(str(random_priv_ip))
             retr_priv_ips.append(str(random_priv_ip))
             priv_ips.remove(random_priv_ip)
             priv_ips.remove(random_priv_ip)
 
 
-        if count == 1:
-            return retr_priv_ips[0]
+        # if count == 1:
+        #     return retr_priv_ips[0]
 
 
         return retr_priv_ips
         return retr_priv_ips
 
 
@@ -146,12 +146,12 @@ class PcapAddressOperations():
                 retr_priv_ips.append(str(random_priv_ip))
                 retr_priv_ips.append(str(random_priv_ip))
                 uncertain_priv_ips.remove(random_priv_ip)
                 uncertain_priv_ips.remove(random_priv_ip)
 
 
-        if count == 1:
-            return retr_public_ips[0]
+        # if count == 1:
+        #     return retr_priv_ips[0]
             
             
         return retr_priv_ips
         return retr_priv_ips
 
 
-    def get_existing_public_ips(self, count: int=1):
+    def get_existing_external_ips(self, count: int=1):
         """
         """
         Returns the given number of private IPs that are existent in the pcap file.
         Returns the given number of private IPs that are existent in the pcap file.
 
 
@@ -171,13 +171,14 @@ class PcapAddressOperations():
 
 
         retr_public_ips = []
         retr_public_ips = []
         public_ips = self.remaining_public_ips
         public_ips = self.remaining_public_ips
+
         for _ in range(0, total):
         for _ in range(0, total):
             random_public_ip = choice(tuple(public_ips))
             random_public_ip = choice(tuple(public_ips))
             retr_public_ips.append(str(random_public_ip))
             retr_public_ips.append(str(random_public_ip))
             public_ips.remove(random_public_ip)
             public_ips.remove(random_public_ip)
 
 
-        if count == 1:
-            return retr_public_ips[0]
+        # if count == 1:
+        #     return retr_public_ips[0]
 
 
         return retr_public_ips
         return retr_public_ips
 
 

+ 11 - 0
code/ID2TLib/PortGenerator.py

@@ -0,0 +1,11 @@
+import random
+import string
+
+def gen_random_server_port():
+    """
+    Generates a valid random first and last character for a bots hostname
+    and computes a port from these two characters.
+    """
+    firstLetter = random.choice(string.ascii_letters);
+    lastLetter = random.choice(string.ascii_letters + string.digits);
+    return (ord(firstLetter) * ord(lastLetter));

+ 0 - 8
code/ID2TLib/genRandPort.py

@@ -1,8 +0,0 @@
-import random
-import string
-
-def generateRandomPort(default: int=0):
-
-    firstLetter = random.choice(string.ascii_letters);
-    lastLetter = random.choice(string.ascii_letters + string.digits);
-    return (default + ord(firstLetter) * ord(lastLetter));