MembersMgmtCommAttack.py 30 KB

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