MembersMgmtCommAttack.py 32 KB

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