SQLiAttack.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import logging
  2. from random import randint, uniform
  3. from lea import Lea
  4. from Attack import BaseAttack
  5. from Attack.AttackParameters import Parameter as Param
  6. from Attack.AttackParameters import ParameterTypes
  7. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  8. # noinspection PyPep8
  9. from scapy.utils import RawPcapReader
  10. from scapy.layers.inet import IP, Ether, TCP, RandShort
  11. class SQLiAttack(BaseAttack.BaseAttack):
  12. template_attack_pcap_path = "resources/ATutorSQLi.pcap"
  13. # HTTP port
  14. http_port = 80
  15. # Metasploit experiments show this range of ports
  16. minDefaultPort = 30000
  17. maxDefaultPort = 50000
  18. def __init__(self, statistics, pcap_file_path):
  19. """
  20. Creates a new instance of the SQLi Attack.
  21. :param statistics: A reference to the statistics class.
  22. """
  23. # Initialize attack
  24. super(SQLiAttack, self).__init__(statistics, "SQLi Attack", "Injects a SQLi attack'",
  25. "Resource Exhaustion")
  26. # Define allowed parameters and their type
  27. self.supported_params = {
  28. Param.MAC_SOURCE: ParameterTypes.TYPE_MAC_ADDRESS,
  29. Param.IP_SOURCE: ParameterTypes.TYPE_IP_ADDRESS,
  30. Param.MAC_DESTINATION: ParameterTypes.TYPE_MAC_ADDRESS,
  31. Param.IP_DESTINATION: ParameterTypes.TYPE_IP_ADDRESS,
  32. Param.TARGET_HOST: ParameterTypes.TYPE_DOMAIN,
  33. #Param.TARGET_URI: ParameterTypes.TYPE_URI,
  34. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  35. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  36. Param.PACKETS_PER_SECOND: ParameterTypes.TYPE_FLOAT
  37. }
  38. # PARAMETERS: initialize with default utilsvalues
  39. # (values are overwritten if user specifies them)
  40. most_used_ip_address = self.statistics.get_most_used_ip_address()
  41. if isinstance(most_used_ip_address, list):
  42. most_used_ip_address = most_used_ip_address[0]
  43. self.add_param_value(Param.IP_SOURCE, most_used_ip_address)
  44. self.add_param_value(Param.MAC_SOURCE, self.statistics.get_mac_address(most_used_ip_address))
  45. #self.add_param_value(Param.TARGET_URI, "/")
  46. self.add_param_value(Param.TARGET_HOST, "www.hackme.com")
  47. self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
  48. self.add_param_value(Param.PACKETS_PER_SECOND,
  49. (self.statistics.get_pps_sent(most_used_ip_address) +
  50. self.statistics.get_pps_received(most_used_ip_address)) / 2)
  51. # victim configuration
  52. # consider that the destination has port 80 opened
  53. random_ip_address = self.statistics.get_random_ip_address()
  54. self.add_param_value(Param.IP_DESTINATION, random_ip_address)
  55. destination_mac = self.statistics.get_mac_address(random_ip_address)
  56. if isinstance(destination_mac, list) and len(destination_mac) == 0:
  57. destination_mac = self.generate_random_mac_address()
  58. self.add_param_value(Param.MAC_DESTINATION, destination_mac)
  59. def generate_attack_pcap(self):
  60. def update_timestamp(timestamp, pps):
  61. """
  62. Calculates the next timestamp to be used based on the packet per second rate (pps) and the maximum delay.
  63. :return: Timestamp to be used for the next packet.
  64. """
  65. # Calculate the request timestamp
  66. # A distribution to imitate the bursty behavior of traffic
  67. randomdelay = Lea.fromValFreqsDict({1 / pps: 70, 2 / pps: 20, 5 / pps: 7, 10 / pps: 3})
  68. return timestamp + uniform(1 / pps, randomdelay.random())
  69. # Aidmar
  70. def getIntervalPPS(complement_interval_pps, timestamp):
  71. """
  72. Gets the packet rate (pps) in specific time interval.
  73. :return: the corresponding packet rate for packet rate (pps) .
  74. """
  75. for row in complement_interval_pps:
  76. if timestamp <= row[0]:
  77. return row[1]
  78. return complement_interval_pps[-1][1] # in case the timstamp > capture max timestamp
  79. # Timestamp
  80. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  81. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  82. # Calculate complement packet rates of BG traffic per interval
  83. complement_interval_pps = self.statistics.calculate_complement_packet_rates(pps)
  84. # Initialize parameters
  85. packets = []
  86. mac_source = self.get_param_value(Param.MAC_SOURCE)
  87. ip_source = self.get_param_value(Param.IP_SOURCE)
  88. mac_destination = self.get_param_value(Param.MAC_DESTINATION)
  89. ip_destination = self.get_param_value(Param.IP_DESTINATION)
  90. target_host = self.get_param_value(Param.TARGET_HOST)
  91. target_uri = "/" #self.get_param_value(Param.TARGET_URI)
  92. # Check ip.src == ip.dst
  93. self.ip_src_dst_equal_check(ip_source, ip_destination)
  94. path_attack_pcap = None
  95. # Set TTL based on TTL distribution of IP address
  96. source_ttl_dist = self.statistics.get_ttl_distribution(ip_source)
  97. if len(source_ttl_dist) > 0:
  98. source_ttl_prob_dict = Lea.fromValFreqsDict(source_ttl_dist)
  99. source_ttl_value = source_ttl_prob_dict.random()
  100. else:
  101. source_ttl_value = self.statistics.process_db_query("most_used(ttlValue)")
  102. destination_ttl_dist = self.statistics.get_ttl_distribution(ip_destination)
  103. if len(destination_ttl_dist) > 0:
  104. destination_ttl_prob_dict = Lea.fromValFreqsDict(destination_ttl_dist)
  105. destination_ttl_value = destination_ttl_prob_dict.random()
  106. else:
  107. destination_ttl_value = self.statistics.process_db_query("most_used(ttlValue)")
  108. # Inject SQLi Attack
  109. # Read SQLi Attack pcap file
  110. orig_ip_dst = None
  111. exploit_raw_packets = RawPcapReader(self.template_attack_pcap_path)
  112. inter_arrival_time_dist = self.get_inter_arrival_time_dist(exploit_raw_packets)
  113. timeSteps = Lea.fromValFreqsDict(inter_arrival_time_dist)
  114. exploit_raw_packets = RawPcapReader(self.template_attack_pcap_path)
  115. port_source = randint(self.minDefaultPort,self.maxDefaultPort) # experiments show this range of ports
  116. # Random TCP sequence numbers
  117. global attacker_seq
  118. attacker_seq = randint(1000, 50000)
  119. global victim_seq
  120. victim_seq = randint(1000, 50000)
  121. for pkt_num, pkt in enumerate(exploit_raw_packets):
  122. eth_frame = Ether(pkt[0])
  123. ip_pkt = eth_frame.payload
  124. tcp_pkt = ip_pkt.payload
  125. str_tcp_seg = str(tcp_pkt.payload)
  126. # Clean payloads
  127. eth_frame.payload = b''
  128. ip_pkt.payload = b''
  129. tcp_pkt.payload = b''
  130. if pkt_num == 0:
  131. prev_orig_port_source = tcp_pkt.getfieldval("sport")
  132. orig_ip_dst = ip_pkt.getfieldval("dst") # victim IP
  133. if tcp_pkt.getfieldval("dport") == 80 or tcp_pkt.getfieldval("sport") == 80:
  134. # Attacker --> vicitm
  135. if ip_pkt.getfieldval("dst") == orig_ip_dst: # victim IP
  136. # There are 363 TCP connections with different source ports, for each of them we generate random port
  137. if tcp_pkt.getfieldval("sport") != prev_orig_port_source and tcp_pkt.getfieldval("dport") != 4444:
  138. port_source = randint(self.minDefaultPort, self.maxDefaultPort)
  139. prev_orig_port_source = tcp_pkt.getfieldval("sport")
  140. # New connection, new random TCP sequence numbers
  141. attacker_seq = randint(1000, 50000)
  142. victim_seq = randint(1000, 50000)
  143. # First packet in a connection has ACK = 0
  144. tcp_pkt.setfieldval("ack", 0)
  145. # Ether
  146. eth_frame.setfieldval("src", mac_source)
  147. eth_frame.setfieldval("dst", mac_destination)
  148. # IP
  149. ip_pkt.setfieldval("src", ip_source)
  150. ip_pkt.setfieldval("dst", ip_destination)
  151. ip_pkt.setfieldval("ttl", source_ttl_value)
  152. # TCP
  153. tcp_pkt.setfieldval("sport",port_source)
  154. str_tcp_seg = self.modify_payload(str_tcp_seg, '/ATutor', target_uri, orig_ip_dst, target_host)
  155. # TCP Seq, Ack
  156. if tcp_pkt.getfieldval("ack") != 0:
  157. tcp_pkt.setfieldval("ack", victim_seq)
  158. tcp_pkt.setfieldval("seq", attacker_seq)
  159. if not (tcp_pkt.getfieldval("flags") == 16 and len(str_tcp_seg) == 0): # flags=A:
  160. attacker_seq += max(len(str_tcp_seg), 1)
  161. new_pkt = (eth_frame / ip_pkt/ tcp_pkt / str_tcp_seg)
  162. new_pkt.time = timestamp_next_pkt
  163. pps = max(getIntervalPPS(complement_interval_pps, timestamp_next_pkt), 10)
  164. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps) + float(timeSteps.random())
  165. # Victim --> attacker
  166. else:
  167. # Ether
  168. eth_frame.setfieldval("src", mac_destination)
  169. eth_frame.setfieldval("dst", mac_source)
  170. # IP
  171. ip_pkt.setfieldval("src", ip_destination)
  172. ip_pkt.setfieldval("dst", ip_source)
  173. ip_pkt.setfieldval("ttl", destination_ttl_value)
  174. # TCP
  175. tcp_pkt.setfieldval("dport", port_source)
  176. str_tcp_seg = self.modify_payload(str_tcp_seg, '/ATutor', target_uri, orig_ip_dst, target_host)
  177. # TCP Seq, ACK
  178. tcp_pkt.setfieldval("ack", attacker_seq)
  179. tcp_pkt.setfieldval("seq", victim_seq)
  180. strLen = len(str_tcp_seg)
  181. if not (tcp_pkt.getfieldval("flags") == 16 and strLen == 0): # flags=A:
  182. victim_seq += max(strLen, 1)
  183. new_pkt = (eth_frame / ip_pkt / tcp_pkt / str_tcp_seg)
  184. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps) + float(timeSteps.random())
  185. new_pkt.time = timestamp_next_pkt
  186. # The last connection
  187. else:
  188. # New connection, new random TCP sequence numbers
  189. attacker_seq = randint(1000, 50000)
  190. victim_seq = randint(1000, 50000)
  191. # First packet in a connection has ACK = 0
  192. tcp_pkt.setfieldval("ack", 0)
  193. #port_source = randint(self.minDefaultPort, self.maxDefaultPort)
  194. # Attacker --> vicitm
  195. if ip_pkt.getfieldval("dst") == orig_ip_dst: # victim IP
  196. # Ether
  197. eth_frame.setfieldval("src", mac_source)
  198. eth_frame.setfieldval("dst", mac_destination)
  199. # IP
  200. ip_pkt.setfieldval("src", ip_source)
  201. ip_pkt.setfieldval("dst", ip_destination)
  202. ip_pkt.setfieldval("ttl", source_ttl_value)
  203. # TCP
  204. #tcp_pkt.setfieldval("sport", port_source)
  205. str_tcp_seg = self.modify_payload(str_tcp_seg, '/ATutor', target_uri, orig_ip_dst, target_host)
  206. # TCP Seq, Ack
  207. if tcp_pkt.getfieldval("ack") != 0:
  208. tcp_pkt.setfieldval("ack", victim_seq)
  209. tcp_pkt.setfieldval("seq", attacker_seq)
  210. if not (tcp_pkt.getfieldval("flags") == 16 and len(str_tcp_seg) == 0): # flags=A:
  211. attacker_seq += max(len(str_tcp_seg), 1)
  212. new_pkt = (eth_frame / ip_pkt / tcp_pkt / str_tcp_seg)
  213. new_pkt.time = timestamp_next_pkt
  214. pps = max(getIntervalPPS(complement_interval_pps, timestamp_next_pkt), 10)
  215. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps) + float(timeSteps.random())
  216. # Victim --> attacker
  217. else:
  218. # Ether
  219. eth_frame.setfieldval("src", mac_destination)
  220. eth_frame.setfieldval("dst", mac_source)
  221. # IP
  222. ip_pkt.setfieldval("src", ip_destination)
  223. ip_pkt.setfieldval("dst", ip_source)
  224. ip_pkt.setfieldval("ttl", destination_ttl_value)
  225. # TCP
  226. #tcp_pkt.setfieldval("dport", port_source)
  227. str_tcp_seg = self.modify_payload(str_tcp_seg, '/ATutor', target_uri, orig_ip_dst, target_host)
  228. # TCP Seq, ACK
  229. tcp_pkt.setfieldval("ack", attacker_seq)
  230. tcp_pkt.setfieldval("seq", victim_seq)
  231. strLen = len(str_tcp_seg)
  232. if not (tcp_pkt.getfieldval("flags") == 16 and strLen == 0): # flags=A:
  233. victim_seq += max(strLen, 1)
  234. new_pkt = (eth_frame / ip_pkt / tcp_pkt / str_tcp_seg)
  235. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps) + float(timeSteps.random())
  236. new_pkt.time = timestamp_next_pkt
  237. packets.append(new_pkt)
  238. # Store timestamp of first packet (for attack label)
  239. self.attack_start_utime = packets[0].time
  240. self.attack_end_utime = packets[-1].time
  241. if len(packets) > 0:
  242. packets = sorted(packets, key=lambda pkt: pkt.time)
  243. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  244. # return packets sorted by packet time_sec_start
  245. # pkt_num+1: because pkt_num starts at 0
  246. return pkt_num + 1, path_attack_pcap