SQLiAttack.py 14 KB

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