MembersMgmtCommAttack.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. import os
  2. import sys
  3. from collections import deque
  4. from datetime import datetime
  5. from random import randint, randrange, choice, uniform
  6. import ID2TLib.Botnet.libbotnetcomm as lb
  7. from lea import Lea
  8. from scapy.layers.inet import IP, IPOption_Security
  9. import ID2TLib.Botnet.Message as Bmsg
  10. import ID2TLib.Utility as Util
  11. from Attack import BaseAttack
  12. from Attack.AttackParameters import Parameter as Param
  13. from Attack.AttackParameters import ParameterTypes
  14. from ID2TLib import Generator
  15. from ID2TLib.Botnet.CommunicationProcessor import CommunicationProcessor
  16. from ID2TLib.Botnet.MessageMapping import MessageMapping
  17. from ID2TLib.PcapAddressOperations import PcapAddressOperations
  18. from ID2TLib.Ports import PortSelectors
  19. class MembersMgmtCommAttack(BaseAttack.BaseAttack):
  20. def __init__(self):
  21. """
  22. Creates a new instance of the Membership Management Communication.
  23. """
  24. # Initialize communication
  25. super(MembersMgmtCommAttack, self).__init__("Membership Management Communication Attack (MembersMgmtCommAttack)",
  26. "Injects Membership Management Communication", "Botnet communication")
  27. # Define allowed parameters and their type
  28. self.supported_params = {
  29. # parameters regarding attack
  30. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  31. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  32. Param.PACKETS_LIMIT: ParameterTypes.TYPE_INTEGER_POSITIVE,
  33. Param.ATTACK_DURATION: ParameterTypes.TYPE_INTEGER_POSITIVE,
  34. # use num_attackers to specify number of communicating devices?
  35. Param.NUMBER_INITIATOR_BOTS: ParameterTypes.TYPE_INTEGER_POSITIVE,
  36. # input file containing botnet communication
  37. Param.FILE_CSV: ParameterTypes.TYPE_FILEPATH,
  38. Param.FILE_XML: ParameterTypes.TYPE_FILEPATH,
  39. # the percentage of IP reuse (if total and other is specified, percentages are multiplied)
  40. Param.IP_REUSE_TOTAL: ParameterTypes.TYPE_PERCENTAGE,
  41. Param.IP_REUSE_LOCAL: ParameterTypes.TYPE_PERCENTAGE,
  42. Param.IP_REUSE_EXTERNAL: ParameterTypes.TYPE_PERCENTAGE,
  43. # the user-selected padding to add to every packet
  44. Param.PACKET_PADDING: ParameterTypes.TYPE_PADDING,
  45. # presence of NAT at the gateway of the network
  46. Param.NAT_PRESENT: ParameterTypes.TYPE_BOOLEAN,
  47. # whether the TTL distribution should be based on the input PCAP
  48. # or the CAIDA dataset
  49. Param.TTL_FROM_CAIDA: ParameterTypes.TYPE_BOOLEAN,
  50. # whether the destination port of a response should be the ephemeral port
  51. # its request came from or a static (server)port based on a hostname
  52. Param.MULTIPORT: ParameterTypes.TYPE_BOOLEAN,
  53. # information about the interval selection strategy
  54. Param.INTERVAL_SELECT_STRATEGY: ParameterTypes.TYPE_INTERVAL_SELECT_STRAT,
  55. Param.INTERVAL_SELECT_START: ParameterTypes.TYPE_INTEGER_POSITIVE,
  56. Param.INTERVAL_SELECT_END: ParameterTypes.TYPE_INTEGER_POSITIVE,
  57. # determines whether injected packets are marked with an unused IP option
  58. # to easily filter them in e.g. wireshark
  59. Param.HIDDEN_MARK: ParameterTypes.TYPE_BOOLEAN
  60. }
  61. # create dict with MessageType values for fast name lookup
  62. self.msg_types = {}
  63. for msg_type in Bmsg.MessageType:
  64. self.msg_types[msg_type.value] = msg_type
  65. def init_params(self):
  66. """
  67. Initialize some parameters of this communication-attack using the user supplied command line parameters.
  68. The remaining parameters are implicitly set in the provided data file. Note: the timestamps in the file
  69. have to be sorted in ascending order
  70. :param statistics: Reference to a statistics object.
  71. """
  72. # set class constants
  73. self.DEFAULT_XML_PATH = Util.RESOURCE_DIR + "Botnet/MembersMgmtComm_example.xml"
  74. # PARAMETERS: initialize with default values
  75. # (values are overwritten if user specifies them)
  76. self.add_param_value(Param.INJECT_AFTER_PACKET, 1 + randint(0, self.statistics.get_packet_count() // 5))
  77. self.add_param_value(Param.FILE_XML, self.DEFAULT_XML_PATH)
  78. # Alternatively new attack parameter?
  79. duration = int(float(self.statistics.get_capture_duration()))
  80. self.add_param_value(Param.ATTACK_DURATION, duration)
  81. self.add_param_value(Param.NUMBER_INITIATOR_BOTS, 1)
  82. # NAT on by default
  83. self.add_param_value(Param.NAT_PRESENT, True)
  84. # TODO: change 1 to something better
  85. self.add_param_value(Param.IP_REUSE_TOTAL, 1)
  86. self.add_param_value(Param.IP_REUSE_LOCAL, 0.5)
  87. self.add_param_value(Param.IP_REUSE_EXTERNAL, 0.5)
  88. # add default additional padding
  89. self.add_param_value(Param.PACKET_PADDING, 20)
  90. # choose the input PCAP as default base for the TTL distribution
  91. self.add_param_value(Param.TTL_FROM_CAIDA, False)
  92. # do not use multiple ports for requests and responses
  93. self.add_param_value(Param.MULTIPORT, False)
  94. # interval selection strategy
  95. self.add_param_value(Param.INTERVAL_SELECT_STRATEGY, "optimal")
  96. self.add_param_value(Param.HIDDEN_MARK, False)
  97. def generate_attack_pcap(self):
  98. """
  99. Injects the packets of this attack into a PCAP and stores it as a temporary file.
  100. :return: a tuple of the number packets injected, the path to the temporary attack PCAP
  101. and a list of additionally created files
  102. """
  103. # create the final messages that have to be sent, including all bot configurations
  104. messages = self._create_messages()
  105. if messages == []:
  106. return 0, None
  107. # Setup (initial) parameters for packet creation loop
  108. BUFFER_SIZE = 1000
  109. pkt_gen = Generator.PacketGenerator()
  110. padding = self.get_param_value(Param.PACKET_PADDING)
  111. packets = deque(maxlen=BUFFER_SIZE)
  112. total_pkts = 0
  113. limit_packetcount = self.get_param_value(Param.PACKETS_LIMIT)
  114. limit_duration = self.get_param_value(Param.ATTACK_DURATION)
  115. path_attack_pcap = None
  116. overThousand = False
  117. msg_packet_mapping = MessageMapping(messages, self.statistics.get_pcap_timestamp_start())
  118. mark_packets = self.get_param_value(Param.HIDDEN_MARK)
  119. # create packets to write to PCAP file
  120. for msg in messages:
  121. # retrieve the source and destination configurations
  122. id_src, id_dst = msg.src["ID"], msg.dst["ID"]
  123. ip_src, ip_dst = msg.src["IP"], msg.dst["IP"]
  124. mac_src, mac_dst = msg.src["MAC"], msg.dst["MAC"]
  125. if msg.type.is_request():
  126. port_src, port_dst = int(msg.src["SrcPort"]), int(msg.dst["DstPort"])
  127. else:
  128. port_src, port_dst = int(msg.src["DstPort"]), int(msg.dst["SrcPort"])
  129. ttl = int(msg.src["TTL"])
  130. # update duration
  131. duration = msg.time - messages[0].time
  132. # if total number of packets has been sent or the attack duration has been exceeded, stop
  133. if ((limit_packetcount is not None and total_pkts >= limit_packetcount) or
  134. (limit_duration is not None and duration >= limit_duration)):
  135. break
  136. # if the type of the message is a NL reply, determine the number of entries
  137. nl_size = 0
  138. if msg.type == Bmsg.MessageType.SALITY_NL_REPLY:
  139. nl_size = randint(1, 25) # what is max NL entries?
  140. # create suitable IP/UDP packet and add to packets list
  141. packet = pkt_gen.generate_mmcom_packet(ip_src=ip_src, ip_dst=ip_dst, ttl=ttl, mac_src=mac_src, mac_dst=mac_dst,
  142. port_src=port_src, port_dst=port_dst, message_type=msg.type, neighborlist_entries=nl_size)
  143. Generator.add_padding(packet, padding,True, True)
  144. packet.time = msg.time
  145. if mark_packets and isinstance(packet.payload, IP): # do this only for ip-packets
  146. ip_data = packet.payload
  147. hidden_opt = IPOption_Security()
  148. hidden_opt.option = 2 # "normal" security opt
  149. hidden_opt.security = 16 # magic value indicating NSA
  150. ip_data.options = hidden_opt
  151. packets.append(packet)
  152. msg_packet_mapping.map_message(msg, packet)
  153. total_pkts += 1
  154. # Store timestamp of first packet (for attack label)
  155. if total_pkts <= 1:
  156. self.attack_start_utime = packets[0].time
  157. elif total_pkts % BUFFER_SIZE == 0: # every 1000 packets write them to the PCAP file (append)
  158. if overThousand: # if over 1000 packets written, there may be a different packet-length for the last few packets
  159. packets = list(packets)
  160. Generator.equal_length(packets, length = max_len, padding = padding, force_len = True)
  161. last_packet = packets[-1]
  162. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  163. packets = deque(maxlen=BUFFER_SIZE)
  164. else:
  165. packets = list(packets)
  166. Generator.equal_length(packets, padding = padding)
  167. last_packet = packets[-1]
  168. max_len = len(last_packet)
  169. overThousand = True
  170. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  171. packets = deque(maxlen=BUFFER_SIZE)
  172. # if there are unwritten packets remaining, write them to the PCAP file
  173. if len(packets) > 0:
  174. if overThousand:
  175. packets = list(packets)
  176. Generator.equal_length(packets, length = max_len, padding = padding, force_len = True)
  177. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  178. last_packet = packets[-1]
  179. else:
  180. packets = list(packets)
  181. Generator.equal_length(packets, padding = padding)
  182. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  183. last_packet = packets[-1]
  184. # write the mapping to a file
  185. current_ts = datetime.now().strftime("%Y%m%d-%H%M%S")
  186. mapping_filename = "mapping_" + current_ts + ".xml"
  187. msg_packet_mapping.write_to_file(mapping_filename)
  188. # Store timestamp of last packet
  189. self.attack_end_utime = last_packet.time
  190. # Return packets sorted by packet by timestamp and total number of packets (sent)
  191. return total_pkts , path_attack_pcap, [mapping_filename]
  192. def generate_attack_packets(self):
  193. pass
  194. def _create_messages(self):
  195. """
  196. Creates the messages that are to be injected into the PCAP.
  197. :return: the final messages as a list
  198. """
  199. def add_ids_to_config(ids_to_add: list, existing_ips: list, new_ips: list, bot_configs: dict, idtype:str="local", router_mac:str=""):
  200. """
  201. Creates IP and MAC configurations for the given IDs and adds them to the existing configurations object.
  202. :param ids_to_add: all sorted IDs that have to be configured and added
  203. :param existing_ips: the existing IPs in the PCAP file that should be assigned to some, or all, IDs
  204. :param new_ips: the newly generated IPs that should be assigned to some, or all, IDs
  205. :param bot_configs: the existing configurations for the bots
  206. :param idtype: the locality type of the IDs
  207. :param router_mac: the MAC address of the router in the PCAP
  208. """
  209. ids = ids_to_add.copy()
  210. # macgen only needed, when IPs are new local IPs (therefore creating the object here suffices for the current callers
  211. # to not end up with the same MAC paired with different IPs)
  212. macgen = Generator.MacAddressGenerator()
  213. # assign existing IPs and the corresponding MAC addresses in the PCAP to the IDs
  214. for ip in existing_ips:
  215. random_id = choice(ids)
  216. mac = self.statistics.process_db_query("macAddress(IPAddress=%s)" % ip)
  217. bot_configs[random_id] = {"Type": idtype, "IP": ip, "MAC": mac}
  218. ids.remove(random_id)
  219. # assign new IPs and for local IPs new MACs or for external IPs the router MAC to the IDs
  220. for ip in new_ips:
  221. random_id = choice(ids)
  222. if idtype == "local":
  223. mac = macgen.random_mac()
  224. elif idtype == "external":
  225. mac = router_mac
  226. bot_configs[random_id] = {"Type": idtype, "IP": ip, "MAC": mac}
  227. ids.remove(random_id)
  228. def assign_realistic_ttls(bot_configs:list):
  229. '''
  230. Assigns a realisitic ttl to each bot from @param: bot_configs. Uses statistics and distribution to be able
  231. to calculate a realisitc ttl.
  232. :param bot_configs: List that contains all bots that should be assigned with realistic ttls.
  233. '''
  234. ids = sorted(bot_configs.keys())
  235. for pos,bot in enumerate(ids):
  236. bot_type = bot_configs[bot]["Type"]
  237. if(bot_type == "local"): # Set fix TTL for local Bots
  238. bot_configs[bot]["TTL"] = 128
  239. # Set TTL based on TTL distribution of IP address
  240. else: # Set varying TTl for external Bots
  241. bot_ttl_dist = self.statistics.get_ttl_distribution(bot_configs[bot]["IP"])
  242. if len(bot_ttl_dist) > 0:
  243. source_ttl_prob_dict = Lea.fromValFreqsDict(bot_ttl_dist)
  244. bot_configs[bot]["TTL"] = source_ttl_prob_dict.random()
  245. else:
  246. most_used_ttl = self.statistics.process_db_query("most_used(ttlValue)")
  247. if isinstance(most_used_ttl, list):
  248. bot_configs[bot]["TTL"] = choice(self.statistics.process_db_query("most_used(ttlValue)"))
  249. else:
  250. bot_configs[bot]["TTL"] = self.statistics.process_db_query("most_used(ttlValue)")
  251. def assign_realistic_timestamps(messages: list, external_ids: set, local_ids: set, avg_delay_local:float, avg_delay_external: float, zero_reference:float):
  252. """
  253. Assigns realistic timestamps to a set of messages
  254. :param messages: the set of messages to be updated
  255. :param external_ids: the set of bot ids, that are outside the network, i.e. external
  256. :param local_ids: the set of bot ids, that are inside the network, i.e. local
  257. :avg_delay_local: the avg_delay between the dispatch and the reception of a packet between local computers
  258. :avg_delay_external: the avg_delay between the dispatch and the reception of a packet between a local and an external computer
  259. :zero_reference: the timestamp which is regarded as the beginning of the pcap_file and therefore handled like a timestamp that resembles 0
  260. """
  261. updated_msgs = []
  262. last_response = {} # Dict, takes a tuple of 2 Bot_IDs as a key (requester, responder), returns the time of the last response, the requester received
  263. # necessary in order to make sure, that additional requests are sent only after the response to the last one was received
  264. for msg in messages: # init
  265. last_response[(msg.src, msg.dst)] = -1
  266. # update all timestamps
  267. for req_msg in messages:
  268. if(req_msg in updated_msgs):
  269. # message already updated
  270. continue
  271. # if req_msg.timestamp would be before the timestamp of the response to the last request, req_msg needs to be sent later (else branch)
  272. if last_response[(req_msg.src, req_msg.dst)] == -1 or last_response[(req_msg.src, req_msg.dst)] < (zero_reference + req_msg.time - 0.05):
  273. ## update req_msg timestamp with a variation of up to 50ms
  274. req_msg.time = zero_reference + req_msg.time + uniform(-0.05, 0.05)
  275. updated_msgs.append(req_msg)
  276. else:
  277. req_msg.time = last_response[(req_msg.src, req_msg.dst)] + 0.06 + uniform(-0.05, 0.05)
  278. # update response if necessary
  279. if req_msg.refer_msg_id != -1:
  280. respns_msg = messages[req_msg.refer_msg_id]
  281. # check for local or external communication and update response timestamp with the respective avg delay
  282. if req_msg.src in external_ids or req_msg.dst in external_ids:
  283. #external communication
  284. respns_msg.time = req_msg.time + avg_delay_external + uniform(-0.1*avg_delay_external, 0.1*avg_delay_external)
  285. else:
  286. #local communication
  287. respns_msg.time = req_msg.time + avg_delay_local + uniform(-0.1*avg_delay_local, 0.1*avg_delay_local)
  288. updated_msgs.append(respns_msg)
  289. last_response[(req_msg.src, req_msg.dst)] = respns_msg.time
  290. def assign_ttls_from_caida(bot_configs):
  291. """
  292. Assign realistic TTL values to bots with respect to their IP, based on the CAIDA dataset.
  293. If there exists an entry for a bot's IP, the TTL is chosen based on a distribution over all used TTLs by this IP.
  294. If there is no such entry, the TTL is chosen based on a distribution over all used TTLs and their respective frequency.
  295. :param bot_configs: the existing bot configurations
  296. """
  297. def get_ip_ttl_distrib():
  298. """
  299. Parses the CSV file containing a mapping between IP and their used TTLs.
  300. :return: returns a dict with the IPs as keys and dicts for their TTL disribution as values
  301. """
  302. ip_based_distrib = {}
  303. with open("resources/CaidaTTL_perIP.csv", "r") as file:
  304. # every line consists of: IP, TTL, Frequency
  305. next(file) # skip CSV header line
  306. for line in file:
  307. ip_addr, ttl, freq = line.split(",")
  308. if ip_addr not in ip_based_distrib:
  309. ip_based_distrib[ip_addr] = {} # the values for ip_based_distrib are dicts with key=TTL, value=Frequency
  310. ip_based_distrib[ip_addr][ttl] = int(freq)
  311. return ip_based_distrib
  312. def get_total_ttl_distrib():
  313. """
  314. Parses the CSV file containing an overview of all used TTLs and their respective frequency.
  315. :return: returns a dict with the TTLs as keys and their frequencies as keys
  316. """
  317. total_ttl_distrib = {}
  318. with open("resources/CaidaTTL_total.csv", "r") as file:
  319. # every line consists of: TTL, Frequency, Fraction
  320. next(file) # skip CSV header line
  321. for line in file:
  322. ttl, freq, _ = line.split(",")
  323. total_ttl_distrib[ttl] = int(freq)
  324. return total_ttl_distrib
  325. # get the TTL distribution for every IP that is available in "resources/CaidaTTL_perIP.csv"
  326. ip_ttl_distrib = get_ip_ttl_distrib()
  327. # build a probability dict for the total TTL distribution
  328. total_ttl_prob_dict = Lea.fromValFreqsDict(get_total_ttl_distrib())
  329. # loop over every bot id and assign a TTL to the respective bot
  330. for bot_id in sorted(bot_configs):
  331. bot_type = bot_configs[bot_id]["Type"]
  332. bot_ip = bot_configs[bot_id]["IP"]
  333. if bot_type == "local":
  334. bot_configs[bot_id]["TTL"] = 128
  335. # if there exists detailed information about the TTL distribution of this IP
  336. elif bot_ip in ip_ttl_distrib:
  337. ip_ttl_freqs = ip_ttl_distrib[bot_ip]
  338. source_ttl_prob_dict = Lea.fromValFreqsDict(ip_ttl_freqs) # build a probability dict from this IP's TTL distribution
  339. bot_configs[bot_id]["TTL"] = source_ttl_prob_dict.random()
  340. # otherwise assign a random TTL based on the total TTL distribution
  341. else:
  342. bot_configs[bot_id]["TTL"] = total_ttl_prob_dict.random()
  343. # parse input CSV or XML
  344. filepath_xml = self.get_param_value(Param.FILE_XML)
  345. filepath_csv = self.get_param_value(Param.FILE_CSV)
  346. # use C++ communication processor for faster interval finding
  347. cpp_comm_proc = lb.botnet_comm_processor();
  348. # only use CSV input if the XML path is the default one
  349. # --> prefer XML input over CSV input (in case both are given)
  350. print_updates = False
  351. if filepath_csv and filepath_xml == self.DEFAULT_XML_PATH:
  352. filename = os.path.splitext(os.path.basename(filepath_csv))[0]
  353. filesize = os.path.getsize(filepath_csv) / 2**20 # get filesize in MB
  354. if filesize > 10:
  355. print("\nParsing input CSV file...", end=" ")
  356. sys.stdout.flush()
  357. print_updates = True
  358. cpp_comm_proc.parse_csv(filepath_csv)
  359. if print_updates:
  360. print("done.")
  361. print("Writing corresponding XML file...", end=" ")
  362. sys.stdout.flush()
  363. filepath_xml = cpp_comm_proc.write_xml(Util.OUT_DIR, filename)
  364. if print_updates: print("done.")
  365. else:
  366. filesize = os.path.getsize(filepath_xml) / 2**20 # get filesize in MB
  367. if filesize > 10:
  368. print("Parsing input XML file...", end=" ")
  369. sys.stdout.flush()
  370. print_updates = True
  371. cpp_comm_proc.parse_xml(filepath_xml)
  372. if print_updates: print("done.")
  373. # find a good communication mapping in the input file that matches the users parameters
  374. nat = self.get_param_value(Param.NAT_PRESENT)
  375. comm_proc = CommunicationProcessor(self.msg_types, nat)
  376. duration = self.get_param_value(Param.ATTACK_DURATION)
  377. number_init_bots = self.get_param_value(Param.NUMBER_INITIATOR_BOTS)
  378. strategy = self.get_param_value(Param.INTERVAL_SELECT_STRATEGY)
  379. start_idx = self.get_param_value(Param.INTERVAL_SELECT_START)
  380. end_idx = self.get_param_value(Param.INTERVAL_SELECT_END)
  381. potential_long_find_time = (strategy == "optimal" and (filesize > 4 and self.statistics.get_packet_count() > 1000))
  382. if print_updates or potential_long_find_time:
  383. if not print_updates: print()
  384. print("Selecting communication interval from input CSV/XML file...", end=" ")
  385. sys.stdout.flush()
  386. if potential_long_find_time:
  387. print("\nWarning: Because of the large input files and the (chosen) interval selection strategy 'optimal',")
  388. print("this may take a while. Consider using selection strategy 'random' or 'custom'...", end=" ")
  389. sys.stdout.flush()
  390. print_updates = True
  391. comm_interval = comm_proc.get_comm_interval(cpp_comm_proc, strategy, number_init_bots, duration, start_idx, end_idx)
  392. if not comm_interval:
  393. print("Error: An interval that satisfies the input cannot be found.")
  394. return []
  395. if print_updates: print("done.") # print corresponding message to interval finding message
  396. # retrieve the mapping information
  397. mapped_ids, packet_start_idx, packet_end_idx = comm_interval["IDs"], comm_interval["Start"], comm_interval["End"]
  398. while len(mapped_ids) > number_init_bots:
  399. rm_idx = randrange(0, len(mapped_ids))
  400. del mapped_ids[rm_idx]
  401. if print_updates: print("Generating attack packets...", end=" ")
  402. sys.stdout.flush()
  403. # get the messages contained in the chosen interval
  404. abstract_packets = cpp_comm_proc.get_messages(packet_start_idx, packet_end_idx);
  405. comm_proc.set_mapping(abstract_packets, mapped_ids)
  406. # determine ID roles and select the messages that are to be mapped into the PCAP
  407. messages = comm_proc.det_id_roles_and_msgs()
  408. # use the previously detetermined roles to assign the locality of all IDs
  409. local_ids, external_ids = comm_proc.det_ext_and_local_ids()
  410. # determine number of reused local and external IPs
  411. reuse_percent_total = self.get_param_value(Param.IP_REUSE_TOTAL)
  412. reuse_percent_external = self.get_param_value(Param.IP_REUSE_EXTERNAL)
  413. reuse_percent_local = self.get_param_value(Param.IP_REUSE_LOCAL)
  414. reuse_count_external = int(reuse_percent_total * reuse_percent_external * len(mapped_ids))
  415. reuse_count_local = int(reuse_percent_total * reuse_percent_local * len(mapped_ids))
  416. # create IP and MAC configurations for the IDs/Bots
  417. ipgen = Generator.IPGenerator()
  418. pcapops = PcapAddressOperations(self.statistics)
  419. router_mac = pcapops.get_probable_router_mac()
  420. bot_configs = {}
  421. # retrieve and assign the IPs and MACs for the bots with respect to the given parameters
  422. # (IDs are always added to bot_configs in the same order under a given seed)
  423. number_local_ids, number_external_ids = len(local_ids), len(external_ids)
  424. # assign addresses for local IDs
  425. if number_local_ids > 0:
  426. reuse_count_local = int(reuse_percent_total * reuse_percent_local * number_local_ids)
  427. existing_local_ips = sorted(pcapops.get_existing_local_ips(reuse_count_local))
  428. new_local_ips = sorted(pcapops.get_new_local_ips(number_local_ids - len(existing_local_ips)))
  429. add_ids_to_config(sorted(local_ids), existing_local_ips, new_local_ips, bot_configs)
  430. # assign addresses for external IDs
  431. if number_external_ids > 0:
  432. reuse_count_external = int(reuse_percent_total * reuse_percent_external * number_external_ids)
  433. existing_external_ips = sorted(pcapops.get_existing_external_ips(reuse_count_external))
  434. remaining = len(external_ids) - len(existing_external_ips)
  435. for external_ip in existing_external_ips: ipgen.add_to_blacklist(external_ip)
  436. new_external_ips = sorted([ipgen.random_ip() for _ in range(remaining)])
  437. add_ids_to_config(sorted(external_ids), existing_external_ips, new_external_ips, bot_configs, idtype="external", router_mac=router_mac)
  438. # this is the timestamp at which the first packet should be injected, the packets have to be shifted to the beginning of the
  439. # pcap file (INJECT_AT_TIMESTAMP) and then the offset of the packets have to be compensated to start at the given point in time
  440. zero_reference = self.get_param_value(Param.INJECT_AT_TIMESTAMP) - messages[0].time
  441. # calculate the average delay values for local and external responses
  442. avg_delay_local, avg_delay_external = self.statistics.get_avg_delay_local_ext()
  443. #set timestamps
  444. assign_realistic_timestamps(messages, external_ids, local_ids, avg_delay_local, avg_delay_external, zero_reference)
  445. portSelector = PortSelectors.LINUX
  446. reserved_ports = set(int(line.strip()) for line in open(Util.RESOURCE_DIR + "reserved_ports.txt").readlines())
  447. def filter_reserved(get_port):
  448. port = get_port()
  449. while port in reserved_ports:
  450. port = get_port()
  451. return port
  452. # create port configurations for the bots
  453. use_multiple_ports = self.get_param_value(Param.MULTIPORT)
  454. for bot in sorted(bot_configs):
  455. bot_configs[bot]["SrcPort"] = filter_reserved(portSelector.select_port_udp)
  456. if not use_multiple_ports:
  457. bot_configs[bot]["DstPort"] = filter_reserved(Generator.gen_random_server_port)
  458. else:
  459. bot_configs[bot]["DstPort"] = filter_reserved(portSelector.select_port_udp)
  460. # assign realistic TTL for every bot
  461. if self.get_param_value(Param.TTL_FROM_CAIDA):
  462. assign_ttls_from_caida(bot_configs)
  463. else:
  464. assign_realistic_ttls(bot_configs)
  465. # put together the final messages including the full sender and receiver
  466. # configurations (i.e. IP, MAC, port, ...) for easier later use
  467. final_messages = []
  468. messages = sorted(messages, key=lambda msg: msg.time)
  469. new_id = 0
  470. for msg in messages:
  471. type_src, type_dst = bot_configs[msg.src]["Type"], bot_configs[msg.dst]["Type"]
  472. id_src, id_dst = msg.src, msg.dst
  473. # sort out messages that do not have a suitable locality setting
  474. if type_src == "external" and type_dst == "external":
  475. continue
  476. msg.src, msg.dst = bot_configs[id_src], bot_configs[id_dst]
  477. msg.src["ID"], msg.dst["ID"] = id_src, id_dst
  478. msg.msg_id = new_id
  479. new_id += 1
  480. ### Important here to update refers, if needed later?
  481. final_messages.append(msg)
  482. return final_messages