PortscanAttack.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 - ip-dst should be valid and not equal to ip.src
  84. while not self.is_valid_ip_address(random_ip_address) or random_ip_address==most_used_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. # Aidmar - check ip.src == ip.dst
  131. if ip_source == ip_destination:
  132. print("\nERROR: Invalid IP addresses; source IP is the same as destination IP: " + ip_source + ".")
  133. import sys
  134. sys.exit(0)
  135. mac_source = self.get_param_value(Param.MAC_SOURCE)
  136. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  137. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  138. randomdelay = Lea.fromValFreqsDict({1 / pps: 70, 2 / pps: 30, 5 / pps: 15, 10 / pps: 3})
  139. maxdelay = randomdelay.random()
  140. # open ports
  141. # Aidmar
  142. ports_open = self.get_param_value(Param.PORT_OPEN)
  143. if ports_open == [1,11,111,1111]: # user did not define open ports
  144. # the ports that were already used by ip.dst (direction in) in the background traffic are open ports
  145. ports_used_by_ip_dst = None #self.statistics.process_db_query(
  146. #"SELECT portNumber FROM ip_ports WHERE portDirection='in' AND ipAddress='" + ip_destination + "'")
  147. if ports_used_by_ip_dst:
  148. ports_open = ports_used_by_ip_dst
  149. print("\nPorts used by %s: %s" % (ip_destination, ports_open))
  150. else: # if no ports were retrieved from database
  151. # Take open ports from nmap-service file
  152. #ports_temp = self.get_ports_from_nmap_service_dst(100)
  153. #ports_open = ports_temp[0:randint(1,10)]
  154. # OR take open ports from the most used ports in traffic statistics
  155. ports_open = self.statistics.process_db_query(
  156. "SELECT portNumber FROM ip_ports GROUP BY portNumber ORDER BY SUM(portCount) DESC LIMIT "+str(randint(1,10)))
  157. print("\nPorts retrieved from statistics: %s" % (ports_open))
  158. # in case of one open port, convert ports_open to array
  159. if not isinstance(ports_open, list):
  160. ports_open = [ports_open]
  161. # =========================================================================================================
  162. # MSS (Maximum Segment Size) for Ethernet. Allowed values [536,1500]
  163. # Aidmar
  164. mss_dst = self.statistics.get_most_used_mss(ip_destination)
  165. if mss_dst is None:
  166. mss_dst = self.statistics.process_db_query("most_used(mssValue)")
  167. mss_src = self.statistics.get_most_used_mss(ip_source)
  168. if mss_src is None:
  169. mss_src = self.statistics.process_db_query("most_used(mssValue)")
  170. # mss = self.statistics.get_mss(ip_destination)
  171. # =========================================================================================================
  172. # Set TTL based on TTL distribution of IP address
  173. ttl_dist = self.statistics.get_ttl_distribution(ip_source)
  174. if len(ttl_dist) > 0:
  175. ttl_prob_dict = Lea.fromValFreqsDict(ttl_dist)
  176. ttl_value = ttl_prob_dict.random()
  177. else:
  178. ttl_value = self.statistics.process_db_query("most_used(ttlValue)")
  179. # Aidmar
  180. replies = []
  181. for dport in dest_ports:
  182. # Parameters changing each iteration
  183. if self.get_param_value(Param.IP_SOURCE_RANDOMIZE) and isinstance(ip_source, list):
  184. ip_source = choice(ip_source)
  185. # 1) Build request package
  186. request_ether = Ether(src=mac_source, dst=mac_destination)
  187. request_ip = IP(src=ip_source, dst=ip_destination, ttl=ttl_value)
  188. # Aidmar - random src port for each packet
  189. sport = randint(1, 65535)
  190. # Aidmar - use most used window size
  191. win_size = self.statistics.process_db_query("most_used(winSize)")
  192. request_tcp = TCP(sport=sport, dport=dport, window=win_size, flags='S', options=[('MSS', mss_src)])
  193. # =========================================================================================================
  194. request = (request_ether / request_ip / request_tcp)
  195. # first packet uses timestamp provided by attack parameter Param.INJECT_AT_TIMESTAMP
  196. """if len(packets) > 0:
  197. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  198. request.time = timestamp_next_pkt
  199. """
  200. # Aidmar - mimic DDoS attack style: put update_timestamp at the end of the loop
  201. request.time = timestamp_next_pkt
  202. # 2) Build reply package
  203. if dport in ports_open: # destination port is OPEN
  204. reply_ether = Ether(src=mac_destination, dst=mac_source)
  205. reply_ip = IP(src=ip_destination, dst=ip_source, flags='DF')
  206. #if mss_dst is None:
  207. # reply_tcp = TCP(sport=dport, dport=sport, seq=0, ack=1, flags='SA', window=29200)
  208. #else:
  209. reply_tcp = TCP(sport=dport, dport=sport, seq=0, ack=1, flags='SA', window=29200,
  210. options=[('MSS', mss_dst)])
  211. reply = (reply_ether / reply_ip / reply_tcp)
  212. # Aidmar - edit name timestamp_reply
  213. timestamp_reply = update_timestamp(timestamp_next_pkt, pps, maxdelay) # TO-DO
  214. if len(replies) > 0:
  215. last_reply_timestamp = replies[-1].time
  216. timestamp_reply = timestamp_next_pkt
  217. while (timestamp_reply <= last_reply_timestamp):
  218. timestamp_reply = update_timestamp(timestamp_reply, pps, maxdelay)
  219. else:
  220. timestamp_reply = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  221. reply.time = timestamp_reply
  222. replies.append(reply)
  223. # requester confirms
  224. # TO-DO: confirms should be in Attacker queue not in victim (reply) queue
  225. confirm_ether = request_ether
  226. confirm_ip = request_ip
  227. confirm_tcp = TCP(sport=sport, dport=dport, seq=1, window=0, flags='R')
  228. reply = (confirm_ether / confirm_ip / confirm_tcp)
  229. # Aidmar - edit name timestamp_confirm
  230. timestamp_confirm = update_timestamp(timestamp_reply, pps, maxdelay) # TO-DO
  231. reply.time = timestamp_confirm
  232. replies.append(reply)
  233. # else: destination port is NOT OPEN -> no reply is sent by target
  234. # Aidmar
  235. # Append reply
  236. if replies:
  237. while timestamp_next_pkt >= replies[0].time:
  238. packets.append(replies[0])
  239. replies.remove(replies[0])
  240. if len(replies) == 0:
  241. break
  242. # Append request
  243. packets.append(request)
  244. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps, maxdelay)
  245. # Requests are sent all, send all replies
  246. if len(replies)>0:
  247. for reply in replies:
  248. packets.append(reply)
  249. # store end time of attack
  250. self.attack_end_utime = packets[-1].time
  251. # write attack packets to pcap
  252. pcap_path = self.write_attack_pcap(sorted(packets, key=lambda pkt: pkt.time))
  253. # return packets sorted by packet time_sec_start
  254. return len(packets), pcap_path