PortscanAttack.py 16 KB

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