Generator.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. from scapy.packet import Raw
  2. import numpy.random as random2
  3. import random
  4. import string
  5. from numpy.random import bytes
  6. from random import getrandbits
  7. from scapy.layers.inet import IP, Ether, UDP, TCP
  8. from scapy.packet import Raw
  9. from ID2TLib.Botnet.Message import MessageType
  10. from . import IPv4 as ip
  11. #################################################
  12. ######## Functions operating on payloads ########
  13. #################################################
  14. def add_padding(packet, bytes_padding:int = 0, user_padding:bool=True, rnd:bool = False):
  15. '''
  16. Adds padding to a packet with the given amount of bytes, but a maximum of 100 bytes, if called by the user.
  17. :param packet: the packet that will be extended with the additional payload
  18. :param bytes_padding: the amount of bytes that will be appended to the packet. Capped to 100,
  19. if called by the user.
  20. :param user_padding: true, if the function add_padding by the user and not within the code
  21. :param rnd: adds a random padding between 0 and bytes_padding, if true
  22. :return: the initial packet, extended with the wanted amount of bytes of padding
  23. '''
  24. if(user_padding == True and bytes_padding > 100):
  25. bytes_padding = 100
  26. if (rnd is True):
  27. r = int(round(bytes_padding / 4)) #sets bytes_padding to any number between 0 and bytes_padding
  28. bytes_padding = random2.random_integers(0, r) * 4 #, that's dividable by 4
  29. payload = generate_payload(bytes_padding)
  30. packet[Raw].load += Raw(load=payload).load
  31. return packet
  32. def equal_length(list_of_packets:list, length:int = 0, padding:int = 0, force_len:bool = False):
  33. '''
  34. Equals the length of all packets of a given list of packets to the given length. If the given length is smaller than the largest
  35. packet, all the other packets are extended to the largest packet's length. Adds additional padding
  36. afterwards to create realism.
  37. :param list_of_packets: The given list of packet.
  38. :param length: The length each packet should have. Can be redundant, if the largest packet has more bytes
  39. :param force_len: if true, all packets are forced to take on the length of param length
  40. than length.
  41. :param padding: The amount of bytes that can be appended at most by the second add, that creates realism.
  42. (The called function will randomly chose a value between zero and padding.)
  43. :return: The list of extended packets.
  44. '''
  45. if not force_len:
  46. largest_packet = length
  47. for packet in list_of_packets:
  48. packet_length = len(packet)
  49. if(packet_length > largest_packet):
  50. largest_packet = packet_length
  51. else:
  52. largest_packet = length
  53. for packet in list_of_packets:
  54. bytes_padding = largest_packet - len(packet)
  55. if(bytes_padding > 0):
  56. add_padding(packet, bytes_padding, False, False) #Add padding to extend to param:length
  57. add_padding(packet, padding, False, True) #Add random additional padding to create realism
  58. return list_of_packets
  59. def generate_payload(size:int=0):
  60. """
  61. Generates a payload of random bytes of the given amount
  62. :param size: number of generated bytes
  63. :return: the generated payload
  64. """
  65. payload = bytes(size)
  66. return payload
  67. #################################################
  68. ######## Generation of random port ########
  69. #################################################
  70. def gen_random_server_port(offset: int=2199):
  71. """
  72. Generates a valid random first and last character for a bots hostname
  73. and computes a port from these two characters.
  74. The default offset is chosen from a Sality implementation in 2011
  75. :param offset: port base for calculation
  76. :return: the generated server port
  77. """
  78. firstLetter = random.choice(string.ascii_letters);
  79. lastLetter = random.choice(string.ascii_letters + string.digits);
  80. return (offset + ord(firstLetter) * ord(lastLetter));
  81. #################################################
  82. ######## MAC address generation ########
  83. #################################################
  84. class MacAddressGenerator:
  85. def __init__(self, include_broadcast_macs=False, include_virtual_macs=False):
  86. self.broadcast = include_broadcast_macs
  87. self.virtual = include_virtual_macs
  88. self.generated = set()
  89. def random_mac(self) -> str:
  90. while True:
  91. mac = self._random_mac()
  92. if mac not in self.generated:
  93. self.generated.add(mac)
  94. return mac
  95. def clear(self):
  96. self.generated.clear()
  97. def generates_broadcast_macs(self) -> bool:
  98. return self.broadcast
  99. def generates_virtual_macs(self) -> bool:
  100. return self.virtual
  101. def set_broadcast_generation(self, broadcast: bool):
  102. self.broadcast = broadcast
  103. def set_virtual_generation(self, virtual: bool):
  104. self.virtual = virtual
  105. def _random_mac(self) -> str:
  106. mac_bytes = bytearray(getrandbits(8) for i in range(6))
  107. if not self.broadcast:
  108. mac_bytes[0] &= ~1 # clear the first bytes' first bit
  109. if not self.virtual:
  110. mac_bytes[0] &= ~2 # clear the first bytes' second bit
  111. return ":".join("%02X" % b for b in mac_bytes)
  112. #################################################
  113. ######## UDP/TCP Packet generation ########
  114. #################################################
  115. class PacketGenerator():
  116. """
  117. Creates packets, based on the set protocol
  118. """
  119. def __init__(self, protocol="udp"):
  120. """
  121. Creates a new Packet_Generator Object
  122. :param protocol: the protocol of the packets to be created, udp or tcp
  123. """
  124. super(PacketGenerator, self).__init__()
  125. self.protocol = protocol
  126. def generate_packet(self, ip_src: str = "192.168.64.32", ip_dst: str = "192.168.64.48",
  127. mac_src: str = "56:6D:D9:BC:70:1C",
  128. mac_dst: str = "F4:2B:95:B3:0E:1A", port_src: int = 1337, port_dst: int = 6442, ttl: int = 64,
  129. tcpflags: str = "S", payload: str = ""):
  130. """
  131. Creates a Packet with the specified Values for the current protocol
  132. :param ip_src: the source IP address of the IP header
  133. :param ip_dst the destination IP address of the IP header
  134. :param mac_src: the source MAC address of the MAC header
  135. :param mac_dst: the destination MAC address of the MAC header
  136. :param port_src: the source port of the header
  137. :param port_dst: the destination port of the header
  138. :param ttl: the ttl Value of the packet
  139. :param tcpflags: the TCP flags of the TCP header
  140. :param payload: the payload of the packet
  141. :return: the corresponding packet
  142. """
  143. if (self.protocol == "udp"):
  144. packet = generate_udp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst, ttl=ttl,
  145. port_src=port_src, port_dst=port_dst, payload=payload)
  146. elif (self.protocol == "tcp"):
  147. packet = generate_tcp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst, ttl=ttl,
  148. port_src=port_src, port_dst=port_dst, tcpflags=tcpflags, payload=payload)
  149. return packet
  150. def generate_mmcom_packet(self, ip_src: str = "192.168.64.32", ip_dst: str = "192.168.64.48",
  151. mac_src: str = "56:6D:D9:BC:70:1C",
  152. mac_dst: str = "F4:2B:95:B3:0E:1A", port_src: int = 1337, port_dst: int = 6442,
  153. tcpflags: str = "S", ttl: int = 64,
  154. message_type: MessageType = MessageType.SALITY_HELLO, neighborlist_entries: int = 1):
  155. """
  156. Creates a Packet for Members-Management-Communication with the specified Values and the current protocol
  157. :param ip_src: the source IP address of the IP header
  158. :param ip_dst the destination IP address of the IP header
  159. :param mac_src: the source MAC address of the MAC header
  160. :param mac_dst: the destination MAC address of the MAC header
  161. :param port_src: the source port of the header
  162. :param port_dst: the destination port of the header
  163. :param tcpflags: the TCP flags of the TCP header, if tcp is selected as protocol
  164. :param ttl: the ttl Value of the packet
  165. :param message_type: affects the size of the payload
  166. :param neighborlist_entries: number of entries of a Neighbourlist-reply, affects the size of the payload
  167. :return: the corresponding packet
  168. """
  169. # Determine length of the payload that has to be generated
  170. if (message_type == MessageType.SALITY_HELLO):
  171. payload_len = 0
  172. elif (message_type == MessageType.SALITY_HELLO_REPLY):
  173. payload_len = 22
  174. elif (message_type == MessageType.SALITY_NL_REQUEST):
  175. payload_len = 28
  176. elif (message_type == MessageType.SALITY_NL_REPLY):
  177. payload_len = 24 + 6 * neighborlist_entries
  178. else:
  179. payload_len = 0
  180. payload = generate_payload(payload_len)
  181. if (self.protocol == "udp"):
  182. packet = generate_udp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst, ttl=ttl,
  183. port_src=port_src, port_dst=port_dst, payload=payload)
  184. elif (self.protocol == "tcp"):
  185. packet = generate_tcp_packet(ip_src=ip_src, ip_dst=ip_dst, mac_src=mac_src, mac_dst=mac_dst, ttl=ttl,
  186. port_src=port_src, port_dst=port_dst, tcpflags=tcpflags, payload=payload)
  187. else:
  188. print("Error: unsupported protocol for generating Packets")
  189. return packet
  190. def generate_tcp_packet(ip_src: str = "192.168.64.32", ip_dst: str = "192.168.64.48",
  191. mac_src: str = "56:6D:D9:BC:70:1C", ttl: int = 64,
  192. mac_dst: str = "F4:2B:95:B3:0E:1A", port_src: int = 1337, port_dst: int = 6442,
  193. tcpflags: str = "S", payload: str = ""):
  194. """
  195. Builds a TCP packet with the values specified by the caller.
  196. :param ip_src: the source IP address of the IP header
  197. :param ip_dst the destination IP address of the IP header
  198. :param mac_src: the source MAC address of the MAC header
  199. :param ttl: the ttl value of the packet
  200. :param mac_dst: the destination MAC address of the MAC header
  201. :param port_src: the source port of the TCP header
  202. :param port_dst: the destination port of the TCP header
  203. :param tcpflags: the TCP flags of the TCP header
  204. :param payload: the payload of the packet
  205. :return: the corresponding TCP packet
  206. """
  207. ether = Ether(src=mac_src, dst=mac_dst)
  208. ip = IP(src=ip_src, dst=ip_dst, ttl=ttl)
  209. tcp = TCP(sport=port_src, dport=port_dst, flags=tcpflags)
  210. packet = ether / ip / tcp / Raw(load=payload)
  211. return packet
  212. def generate_udp_packet(ip_src: str = "192.168.64.32", ip_dst: str = "192.168.64.48",
  213. mac_src: str = "56:6D:D9:BC:70:1C", ttl: int = 64,
  214. mac_dst: str = "F4:2B:95:B3:0E:1A", port_src: int = 1337, port_dst: int = 6442,
  215. payload: str = ""):
  216. """
  217. Builds an UDP packet with the values specified by the caller.
  218. :param ip_src: the source IP address of the IP header
  219. :param ip_dst the destination IP address of the IP header
  220. :param mac_src: the source MAC address of the MAC header
  221. :param ttl: the ttl value of the packet
  222. :param mac_dst: the destination MAC address of the MAC header
  223. :param port_src: the source port of the UDP header
  224. :param port_dst: the destination port of the UDP header
  225. :param payload: the payload of the packet
  226. :return: the corresponding UDP packet
  227. """
  228. ether = Ether(src=mac_src, dst=mac_dst)
  229. ip = IP(src=ip_src, dst=ip_dst, ttl=ttl)
  230. udp = UDP(sport=port_src, dport=port_dst)
  231. packet = ether / ip / udp / Raw(load=payload)
  232. return packet
  233. #################################################
  234. ######## IP address generation ########
  235. #################################################
  236. class IPChooser:
  237. def random_ip(self):
  238. return ip.IPAddress.from_int(random.randrange(0, 1 << 32))
  239. def size(self):
  240. return 1 << 32
  241. def __len__(self):
  242. return self.size()
  243. class IPChooserByRange(IPChooser):
  244. def __init__(self, ip_range):
  245. self.range = ip_range
  246. def random_ip(self):
  247. start = int(self.range.first_address())
  248. end = start + self.range.block_size()
  249. return ip.IPAddress.from_int(random.randrange(start, end))
  250. def size(self):
  251. return self.range.block_size()
  252. class IPChooserByList(IPChooser):
  253. def __init__(self, ips):
  254. self.ips = list(ips)
  255. if not self.ips:
  256. raise ValueError("list of ips must not be empty")
  257. def random_ip(self):
  258. return random.choice(self.ips)
  259. def size(self):
  260. return len(self.ips)
  261. class IPGenerator:
  262. def __init__(self, ip_chooser=IPChooser(), # include all ip-addresses by default (before the blacklist)
  263. include_private_ips=False, include_localhost=False,
  264. include_multicast=False, include_reserved=False,
  265. include_link_local=False, blacklist=None):
  266. self.blacklist = []
  267. self.generated_ips = set()
  268. if not include_private_ips:
  269. for segment in ip.ReservedIPBlocks.PRIVATE_IP_SEGMENTS:
  270. self.add_to_blacklist(segment)
  271. if not include_localhost:
  272. self.add_to_blacklist(ip.ReservedIPBlocks.LOCALHOST_SEGMENT)
  273. if not include_multicast:
  274. self.add_to_blacklist(ip.ReservedIPBlocks.MULTICAST_SEGMENT)
  275. if not include_reserved:
  276. self.add_to_blacklist(ip.ReservedIPBlocks.RESERVED_SEGMENT)
  277. if not include_link_local:
  278. self.add_to_blacklist(ip.ReservedIPBlocks.ZERO_CONF_SEGMENT)
  279. if blacklist:
  280. for segment in blacklist:
  281. self.add_to_blacklist(segment)
  282. self.chooser = ip_chooser
  283. @staticmethod
  284. def from_range(range, *args, **kwargs):
  285. return IPGenerator(IPChooserByRange(range), *args, **kwargs)
  286. def add_to_blacklist(self, ip_segment):
  287. if isinstance(ip_segment, ip.IPAddressBlock):
  288. self.blacklist.append(ip_segment)
  289. else:
  290. self.blacklist.append(ip.IPAddressBlock.parse(ip_segment))
  291. def random_ip(self):
  292. if len(self.generated_ips) == self.chooser.size():
  293. raise ValueError("Exhausted the space of possible ip-addresses, no new unique ip-address can be generated")
  294. while True:
  295. random_ip = self.chooser.random_ip()
  296. if not self._is_in_blacklist(random_ip) and random_ip not in self.generated_ips:
  297. self.generated_ips.add(random_ip)
  298. return str(random_ip)
  299. def clear(self, clear_blacklist=True, clear_generated_ips=True):
  300. if clear_blacklist: self.blacklist.clear()
  301. if clear_generated_ips: self.generated_ips.clear()
  302. def _is_in_blacklist(self, ip: ip.IPAddress):
  303. return any(ip in block for block in self.blacklist)
  304. class MappingIPGenerator(IPGenerator):
  305. def __init__(self, *args, **kwargs):
  306. super().__init__(self, *args, **kwargs)
  307. self.mapping = {}
  308. def clear(self, clear_generated_ips=True, *args, **kwargs):
  309. super().clear(self, clear_generated_ips=clear_generated_ips, *args, **kwargs)
  310. if clear_generated_ips:
  311. self.mapping = {}
  312. def get_mapped_ip(self, key):
  313. if key not in self.mapping:
  314. self.mapping[key] = self.random_ip()
  315. return self.mapping[key]
  316. def __getitem__(self, item):
  317. return self.get_mapped_ip(item)