PortscanAttack.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import logging
  2. import csv
  3. import socket
  4. from random import shuffle, randint, choice, uniform
  5. from lea import Lea
  6. from Attack import BaseAttack
  7. from Attack.AttackParameters import Parameter as Param
  8. from Attack.AttackParameters import ParameterTypes
  9. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  10. # noinspection PyPep8
  11. from scapy.layers.inet import IP, Ether, TCP
  12. class PortscanAttack(BaseAttack.BaseAttack):
  13. # Aidmar
  14. def get_ports_from_nmap_service_dst(self, ports_num):
  15. """
  16. Read the most ports_num frequently open ports from nmap-service-tcp file to be used in Portscan attack.
  17. :return: Ports numbers to be used as default dest ports or default open ports in Portscan attack.
  18. """
  19. ports_dst = []
  20. spamreader = csv.reader(open('nmap-services-tcp.csv', 'rt'), delimiter=',')
  21. for count in range(ports_num):
  22. # escape first row (header)
  23. next(spamreader)
  24. # save ports numbers
  25. ports_dst.append(next(spamreader)[0])
  26. # shuffle ports numbers
  27. if(ports_num==1000): # used for port.dst
  28. temp_array = [[0 for i in range(10)] for i in range(100)]
  29. port_dst_shuffled = []
  30. for count in range(0, 9):
  31. temp_array[count] = ports_dst[count * 100:count * 100 + 99]
  32. shuffle(temp_array[count])
  33. port_dst_shuffled += temp_array[count]
  34. else: # used for port.open
  35. shuffle(ports_dst)
  36. port_dst_shuffled = ports_dst
  37. return port_dst_shuffled
  38. def is_valid_ip_address(self,addr):
  39. """
  40. Check if the IP address family is suported.
  41. :param addr: IP address to be checked
  42. :return: Boolean
  43. """
  44. try:
  45. socket.inet_aton(addr)
  46. return True
  47. except socket.error:
  48. return False
  49. def __init__(self, statistics, pcap_file_path):
  50. """
  51. Creates a new instance of the PortscanAttack.
  52. :param statistics: A reference to the statistics class.
  53. """
  54. # Initialize attack
  55. super(PortscanAttack, self).__init__(statistics, "Portscan Attack", "Injects a nmap 'regular scan'",
  56. "Scanning/Probing")
  57. # Define allowed parameters and their type
  58. self.supported_params = {
  59. Param.IP_SOURCE: ParameterTypes.TYPE_IP_ADDRESS,
  60. Param.IP_DESTINATION: ParameterTypes.TYPE_IP_ADDRESS,
  61. Param.PORT_SOURCE: ParameterTypes.TYPE_PORT,
  62. Param.PORT_DESTINATION: ParameterTypes.TYPE_PORT,
  63. Param.PORT_OPEN: ParameterTypes.TYPE_PORT,
  64. Param.MAC_SOURCE: ParameterTypes.TYPE_MAC_ADDRESS,
  65. Param.MAC_DESTINATION: ParameterTypes.TYPE_MAC_ADDRESS,
  66. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  67. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  68. Param.PORT_DEST_SHUFFLE: ParameterTypes.TYPE_BOOLEAN,
  69. Param.PORT_DEST_ORDER_DESC: ParameterTypes.TYPE_BOOLEAN,
  70. Param.IP_SOURCE_RANDOMIZE: ParameterTypes.TYPE_BOOLEAN,
  71. Param.PACKETS_PER_SECOND: ParameterTypes.TYPE_FLOAT,
  72. Param.PORT_SOURCE_RANDOMIZE: ParameterTypes.TYPE_BOOLEAN
  73. }
  74. # PARAMETERS: initialize with default values
  75. # (values are overwritten if user specifies them)
  76. most_used_ip_address = self.statistics.get_most_used_ip_address()
  77. if isinstance(most_used_ip_address, list):
  78. most_used_ip_address = most_used_ip_address[0]
  79. self.add_param_value(Param.IP_SOURCE, most_used_ip_address)
  80. self.add_param_value(Param.IP_SOURCE_RANDOMIZE, 'False')
  81. self.add_param_value(Param.MAC_SOURCE, self.statistics.get_mac_address(most_used_ip_address))
  82. random_ip_address = self.statistics.get_random_ip_address()
  83. # Aidmar
  84. while not self.is_valid_ip_address(random_ip_address):
  85. random_ip_address = self.statistics.get_random_ip_address()
  86. self.add_param_value(Param.IP_DESTINATION, random_ip_address)
  87. destination_mac = self.statistics.get_mac_address(random_ip_address)
  88. if isinstance(destination_mac, list) and len(destination_mac) == 0:
  89. destination_mac = self.generate_random_mac_address()
  90. self.add_param_value(Param.MAC_DESTINATION, destination_mac)
  91. self.add_param_value(Param.PORT_DESTINATION, self.get_ports_from_nmap_service_dst(1000))
  92. #self.add_param_value(Param.PORT_DESTINATION, '1-1023,1720,1900,8080,56652')
  93. # Not used initial value
  94. self.add_param_value(Param.PORT_OPEN, '1,11,111,1111')
  95. self.add_param_value(Param.PORT_DEST_SHUFFLE, 'False')
  96. self.add_param_value(Param.PORT_DEST_ORDER_DESC, 'False')
  97. self.add_param_value(Param.PORT_SOURCE, randint(1024, 65535))
  98. self.add_param_value(Param.PORT_SOURCE_RANDOMIZE, 'False')
  99. self.add_param_value(Param.PACKETS_PER_SECOND,
  100. (self.statistics.get_pps_sent(most_used_ip_address) +
  101. self.statistics.get_pps_received(most_used_ip_address)) / 2)
  102. self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
  103. def generate_attack_pcap(self):
  104. def update_timestamp(timestamp, pps, maxdelay):
  105. """
  106. Calculates the next timestamp to be used based on the packet per second rate (pps) and the maximum delay.
  107. :return: Timestamp to be used for the next packet.
  108. """
  109. return timestamp + uniform(0.1 / pps, maxdelay)
  110. # Determine ports
  111. dest_ports = self.get_param_value(Param.PORT_DESTINATION)
  112. if self.get_param_value(Param.PORT_DEST_ORDER_DESC):
  113. dest_ports.reverse()
  114. elif self.get_param_value(Param.PORT_DEST_SHUFFLE):
  115. shuffle(dest_ports)
  116. if self.get_param_value(Param.PORT_SOURCE_RANDOMIZE):
  117. # Aidmar
  118. sport = randint(1, 65535)
  119. #sport = randint(0, 65535)
  120. else:
  121. sport = self.get_param_value(Param.PORT_SOURCE)
  122. # Timestamp
  123. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  124. # store start time of attack
  125. self.attack_start_utime = timestamp_next_pkt
  126. # Initialize parameters
  127. packets = []
  128. ip_source = self.get_param_value(Param.IP_SOURCE)
  129. ip_destination = self.get_param_value(Param.IP_DESTINATION)
  130. mac_source = self.get_param_value(Param.MAC_SOURCE)
  131. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  132. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  133. randomdelay = Lea.fromValFreqsDict({1 / pps: 70, 2 / pps: 30, 5 / pps: 15, 10 / pps: 3})
  134. maxdelay = randomdelay.random()
  135. # open ports
  136. # Aidmar
  137. ports_open = self.get_param_value(Param.PORT_OPEN)
  138. if ports_open == [1,11,111,1111]: # user did not define open ports
  139. # the ports that were already used by ip.dst (direction in) in the background traffic are open ports
  140. ports_used_by_ip_dst = None #self.statistics.process_db_query(
  141. #"SELECT portNumber FROM ip_ports WHERE portDirection='in' AND ipAddress='" + ip_destination + "'")
  142. if ports_used_by_ip_dst:
  143. ports_open = ports_used_by_ip_dst
  144. print("\nPorts used by %s: %s" % (ip_destination, ports_open))
  145. else: # if no ports were retrieved from database
  146. # Take open ports from nmap-service file
  147. #ports_temp = self.get_ports_from_nmap_service_dst(100)
  148. #ports_open = ports_temp[0:randint(1,10)]
  149. # OR take open ports from the most used ports in traffic statistics
  150. ports_open = self.statistics.process_db_query(
  151. "SELECT portNumber FROM ip_ports GROUP BY portNumber ORDER BY SUM(portCount) DESC LIMIT "+str(randint(1,10)))
  152. print("\nPorts retrieved from statistics: %s" % (ports_open))
  153. # in case of one open port, convert ports_open to array
  154. if not isinstance(ports_open, list):
  155. ports_open = [ports_open]
  156. # =========================================================================================================
  157. # MSS (Maximum Segment Size) for Ethernet. Allowed values [536,1500]
  158. # Aidmar
  159. mss_dst = self.statistics.get_most_used_mss(ip_destination)
  160. if mss_dst is None:
  161. mss_dst = self.statistics.process_db_query("most_used(mssValue)")
  162. mss_src = self.statistics.get_most_used_mss(ip_source)
  163. if mss_src is None:
  164. mss_src = self.statistics.process_db_query("most_used(mssValue)")
  165. # mss = self.statistics.get_mss(ip_destination)
  166. # =========================================================================================================
  167. # Set TTL based on TTL distribution of IP address
  168. ttl_dist = self.statistics.get_ttl_distribution(ip_source)
  169. if len(ttl_dist) > 0:
  170. ttl_prob_dict = Lea.fromValFreqsDict(ttl_dist)
  171. ttl_value = ttl_prob_dict.random()
  172. else:
  173. ttl_value = self.statistics.process_db_query("most_used(ttlValue)")
  174. # Aidmar
  175. replies = []
  176. for dport in dest_ports:
  177. # Parameters changing each iteration
  178. if self.get_param_value(Param.IP_SOURCE_RANDOMIZE) and isinstance(ip_source, list):
  179. ip_source = choice(ip_source)
  180. # 1) Build request package
  181. request_ether = Ether(src=mac_source, dst=mac_destination)
  182. request_ip = IP(src=ip_source, dst=ip_destination, ttl=ttl_value)
  183. # Aidmar - random src port for each packet
  184. sport = randint(1, 65535)
  185. # Aidmar - use most used window size
  186. win_size = self.statistics.process_db_query("most_used(winSize)")
  187. request_tcp = TCP(sport=sport, dport=dport, window=win_size, flags='S', options=[('MSS', mss_src)])
  188. # =========================================================================================================
  189. request = (request_ether / request_ip / request_tcp)
  190. # first packet uses timestamp provided by attack parameter Param.INJECT_AT_TIMESTAMP
  191. """if len(packets) > 0:
  192. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  193. request.time = timestamp_next_pkt
  194. """
  195. # Aidmar - mimic DDoS attack style: put update_timestamp at the end of the loop
  196. request.time = timestamp_next_pkt
  197. # 2) Build reply package
  198. if dport in ports_open: # destination port is OPEN
  199. reply_ether = Ether(src=mac_destination, dst=mac_source)
  200. reply_ip = IP(src=ip_destination, dst=ip_source, flags='DF')
  201. #if mss_dst is None:
  202. # reply_tcp = TCP(sport=dport, dport=sport, seq=0, ack=1, flags='SA', window=29200)
  203. #else:
  204. reply_tcp = TCP(sport=dport, dport=sport, seq=0, ack=1, flags='SA', window=29200,
  205. options=[('MSS', mss_dst)])
  206. reply = (reply_ether / reply_ip / reply_tcp)
  207. # Aidmar - edit name timestamp_reply
  208. timestamp_reply = update_timestamp(timestamp_next_pkt, pps, maxdelay) # TO-DO
  209. if len(replies) > 0:
  210. last_reply_timestamp = replies[-1].time
  211. timestamp_reply = timestamp_next_pkt
  212. while (timestamp_reply <= last_reply_timestamp):
  213. timestamp_reply = update_timestamp(timestamp_reply, pps, maxdelay)
  214. else:
  215. timestamp_reply = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  216. reply.time = timestamp_reply
  217. replies.append(reply)
  218. # requester confirms
  219. # TO-DO: confirms should be in Attacker queue not in victim (reply) queue
  220. confirm_ether = request_ether
  221. confirm_ip = request_ip
  222. confirm_tcp = TCP(sport=sport, dport=dport, seq=1, window=0, flags='R')
  223. reply = (confirm_ether / confirm_ip / confirm_tcp)
  224. # Aidmar - edit name timestamp_confirm
  225. timestamp_confirm = update_timestamp(timestamp_reply, pps, maxdelay) # TO-DO
  226. reply.time = timestamp_confirm
  227. replies.append(reply)
  228. # else: destination port is NOT OPEN -> no reply is sent by target
  229. # Aidmar
  230. # Append reply
  231. if replies:
  232. while timestamp_next_pkt >= replies[0].time:
  233. packets.append(replies[0])
  234. replies.remove(replies[0])
  235. if len(replies) == 0:
  236. break
  237. # Append request
  238. packets.append(request)
  239. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  240. # Requests are sent all, send all replies
  241. if len(replies)>0:
  242. for reply in replies:
  243. packets.append(reply)
  244. # store end time of attack
  245. self.attack_end_utime = packets[-1].time
  246. # write attack packets to pcap
  247. pcap_path = self.write_attack_pcap(sorted(packets, key=lambda pkt: pkt.time))
  248. # return packets sorted by packet time_sec_start
  249. return len(packets), pcap_path