SMBScanAttack.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import logging
  2. from random import shuffle, randint
  3. from lea import Lea
  4. from scapy.layers.inet import IP, Ether, TCP
  5. from scapy.layers.smb import *
  6. from scapy.layers.netbios import *
  7. from Attack import BaseAttack
  8. from Attack.AttackParameters import Parameter as Param
  9. from Attack.AttackParameters import ParameterTypes
  10. from ID2TLib.SMB2 import *
  11. from ID2TLib.Utility import update_timestamp, get_interval_pps, get_rnd_os, get_ip_range,\
  12. generate_source_port_from_platform, get_filetime_format
  13. from ID2TLib.SMBLib import smb_port, smb_versions, smb_dialects, get_smb_version, get_smb_platform_data,\
  14. invalid_smb_version
  15. logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
  16. # noinspection PyPep8
  17. class SMBScanAttack(BaseAttack.BaseAttack):
  18. def __init__(self):
  19. """
  20. Creates a new instance of the SMBScanAttack.
  21. """
  22. # Initialize attack
  23. super(SMBScanAttack, self).__init__("SmbScan Attack", "Injects an SMB scan",
  24. "Scanning/Probing")
  25. # Define allowed parameters and their type
  26. self.supported_params = {
  27. Param.IP_SOURCE: ParameterTypes.TYPE_IP_ADDRESS,
  28. Param.IP_DESTINATION: ParameterTypes.TYPE_IP_ADDRESS,
  29. Param.PORT_SOURCE: ParameterTypes.TYPE_PORT,
  30. Param.MAC_SOURCE: ParameterTypes.TYPE_MAC_ADDRESS,
  31. Param.MAC_DESTINATION: ParameterTypes.TYPE_MAC_ADDRESS,
  32. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  33. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  34. Param.IP_SOURCE_RANDOMIZE: ParameterTypes.TYPE_BOOLEAN,
  35. Param.PACKETS_PER_SECOND: ParameterTypes.TYPE_FLOAT,
  36. Param.PORT_SOURCE_RANDOMIZE: ParameterTypes.TYPE_BOOLEAN,
  37. Param.HOSTING_IP: ParameterTypes.TYPE_IP_ADDRESS,
  38. Param.HOSTING_VERSION: ParameterTypes.TYPE_STRING,
  39. Param.SOURCE_PLATFORM: ParameterTypes.TYPE_STRING,
  40. Param.PROTOCOL_VERSION: ParameterTypes.TYPE_STRING,
  41. Param.IP_DESTINATION_END: ParameterTypes.TYPE_IP_ADDRESS
  42. }
  43. def init_params(self):
  44. """
  45. Initialize the parameters of this attack using the user supplied command line parameters.
  46. Use the provided statistics to calculate default parameters and to process user
  47. supplied queries.
  48. :param statistics: Reference to a statistics object.
  49. """
  50. # PARAMETERS: initialize with default values
  51. # (values are overwritten if user specifies them)
  52. most_used_ip_address = self.statistics.get_most_used_ip_address()
  53. if isinstance(most_used_ip_address, list):
  54. most_used_ip_address = most_used_ip_address[0]
  55. self.add_param_value(Param.IP_SOURCE, most_used_ip_address)
  56. self.add_param_value(Param.IP_SOURCE_RANDOMIZE, 'False')
  57. self.add_param_value(Param.MAC_SOURCE, self.statistics.get_mac_address(most_used_ip_address))
  58. all_ips = self.statistics.get_ip_addresses()
  59. if not isinstance(all_ips, list):
  60. ip_destinations = []
  61. ip_destinations.append(all_ips)
  62. else:
  63. ip_destinations = all_ips
  64. self.add_param_value(Param.IP_DESTINATION, ip_destinations)
  65. destination_mac = []
  66. for ip in ip_destinations:
  67. destination_mac.append(self.statistics.get_mac_address(str(ip)))
  68. if isinstance(destination_mac, list) and len(destination_mac) == 0:
  69. destination_mac = self.generate_random_mac_address()
  70. self.add_param_value(Param.MAC_DESTINATION, destination_mac)
  71. self.add_param_value(Param.PORT_SOURCE, randint(1024, 65535))
  72. self.add_param_value(Param.PORT_SOURCE_RANDOMIZE, 'True')
  73. self.add_param_value(Param.PACKETS_PER_SECOND,
  74. (self.statistics.get_pps_sent(most_used_ip_address) +
  75. self.statistics.get_pps_received(most_used_ip_address)) / 2)
  76. self.add_param_value(Param.INJECT_AFTER_PACKET, randint(0, self.statistics.get_packet_count()))
  77. rnd_ip_count = self.statistics.get_ip_address_count()/2
  78. self.add_param_value(Param.HOSTING_IP, self.statistics.get_random_ip_address(rnd_ip_count))
  79. self.host_os = get_rnd_os()
  80. self.add_param_value(Param.HOSTING_VERSION, get_smb_version(platform=self.host_os))
  81. self.add_param_value(Param.SOURCE_PLATFORM, get_rnd_os())
  82. self.add_param_value(Param.PROTOCOL_VERSION, "1")
  83. self.add_param_value(Param.IP_DESTINATION_END, "0.0.0.0")
  84. def generate_attack_pcap(self):
  85. def get_ip_data(ip_address: str):
  86. """
  87. Gets the MSS, TTL and Windows Size values of a given IP
  88. :param ip_address: the ip of which (packet-)data shall be returned
  89. :return: MSS, TTL and Window Size values of the given IP
  90. """
  91. # Set MSS (Maximum Segment Size) based on MSS distribution of IP address
  92. mss_dist = self.statistics.get_mss_distribution(ip_address)
  93. if len(mss_dist) > 0:
  94. mss_prob_dict = Lea.fromValFreqsDict(mss_dist)
  95. mss_value = mss_prob_dict.random()
  96. else:
  97. mss_value = self.statistics.process_db_query("most_used(mssValue)")
  98. # Set TTL based on TTL distribution of IP address
  99. ttl_dist = self.statistics.get_ttl_distribution(ip_address)
  100. if len(ttl_dist) > 0:
  101. ttl_prob_dict = Lea.fromValFreqsDict(ttl_dist)
  102. ttl_value = ttl_prob_dict.random()
  103. else:
  104. ttl_value = self.statistics.process_db_query("most_used(ttlValue)")
  105. # Set Window Size based on Window Size distribution of IP address
  106. win_dist = self.statistics.get_win_distribution(ip_address)
  107. if len(win_dist) > 0:
  108. win_prob_dict = Lea.fromValFreqsDict(win_dist)
  109. win_value = win_prob_dict.random()
  110. else:
  111. win_value = self.statistics.process_db_query("most_used(winSize)")
  112. return mss_value, ttl_value, win_value
  113. pps = self.get_param_value(Param.PACKETS_PER_SECOND)
  114. # Calculate complement packet rates of the background traffic for each interval
  115. complement_interval_pps = self.statistics.calculate_complement_packet_rates(pps)
  116. # Timestamp
  117. timestamp_next_pkt = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  118. # store start time of attack
  119. self.attack_start_utime = timestamp_next_pkt
  120. timestamp_prv_reply, timestamp_confirm = 0,0
  121. # Initialize parameters
  122. ip_source = self.get_param_value(Param.IP_SOURCE)
  123. ip_destinations = self.get_param_value(Param.IP_DESTINATION)
  124. hosting_ip = self.get_param_value(Param.HOSTING_IP)
  125. ip_range_end = self.get_param_value(Param.IP_DESTINATION_END)
  126. mac_source = self.get_param_value(Param.MAC_SOURCE)
  127. mac_dest = self.get_param_value(Param.MAC_DESTINATION)
  128. # Check smb version
  129. smb_version = self.get_param_value(Param.PROTOCOL_VERSION)
  130. if smb_version not in smb_versions:
  131. invalid_smb_version(smb_version)
  132. hosting_version = self.get_param_value(Param.HOSTING_VERSION)
  133. if hosting_version not in smb_versions:
  134. invalid_smb_version(hosting_version)
  135. # Check source platform
  136. src_platform = self.get_param_value(Param.SOURCE_PLATFORM).lower()
  137. packets = []
  138. # randomize source ports according to platform, if specified
  139. if self.get_param_value(Param.PORT_SOURCE_RANDOMIZE):
  140. sport = generate_source_port_from_platform(src_platform)
  141. else:
  142. sport = self.get_param_value(Param.PORT_SOURCE)
  143. # No destination IP was specified, but a destination MAC was specified, generate IP that fits MAC
  144. if isinstance(ip_destinations, list) and isinstance(mac_dest, str):
  145. ip_destinations = self.statistics.get_ip_address_from_mac(mac_dest)
  146. if len(ip_destinations) == 0:
  147. ip_destinations = self.generate_random_ipv4_address("Unknown", 1)
  148. # Check ip.src == ip.dst
  149. self.ip_src_dst_equal_check(ip_source, ip_destinations)
  150. ip_dests = []
  151. if isinstance(ip_destinations, list):
  152. ip_dests = ip_destinations
  153. else:
  154. ip_dests.append(ip_destinations)
  155. # Generate IPs of destination IP range, if specified
  156. if ip_range_end != "0.0.0.0":
  157. ip_dests = get_ip_range(ip_dests[0], ip_range_end)
  158. shuffle(ip_dests)
  159. # Randomize source IP, if specified
  160. if self.get_param_value(Param.IP_SOURCE_RANDOMIZE):
  161. ip_source = self.generate_random_ipv4_address("Unknown", 1)
  162. while ip_source in ip_dests:
  163. ip_source = self.generate_random_ipv4_address("Unknown", 1)
  164. mac_source = self.statistics.get_mac_address(str(ip_source))
  165. if len(mac_source) == 0:
  166. mac_source = self.generate_random_mac_address()
  167. # Get MSS, TTL and Window size value for source IP
  168. source_mss_value, source_ttl_value, source_win_value = get_ip_data(ip_source)
  169. for ip in ip_dests:
  170. if ip != ip_source:
  171. # Get destination Mac Address
  172. mac_destination = self.statistics.get_mac_address(str(ip))
  173. if len(mac_destination) == 0:
  174. if isinstance(mac_dest, str):
  175. if len(self.statistics.get_ip_address_from_mac(mac_dest)) != 0:
  176. ip = self.statistics.get_ip_address_from_mac(mac_dest)
  177. self.ip_src_dst_equal_check(ip_source, ip)
  178. mac_destination = mac_dest
  179. else:
  180. mac_destination = self.generate_random_mac_address()
  181. # Get MSS, TTL and Window size value for destination IP
  182. destination_mss_value, destination_ttl_value, destination_win_value = get_ip_data(ip)
  183. minDelay, maxDelay = self.get_reply_delay(ip)
  184. # New connection, new random TCP sequence numbers
  185. attacker_seq = randint(1000, 50000)
  186. victim_seq = randint(1000, 50000)
  187. # Randomize source port for each connection if specified
  188. if self.get_param_value(Param.PORT_SOURCE_RANDOMIZE):
  189. sport = generate_source_port_from_platform(src_platform, sport)
  190. # 1) Build request package
  191. request_ether = Ether(src=mac_source, dst=mac_destination)
  192. request_ip = IP(src=ip_source, dst=ip, ttl=source_ttl_value, flags='DF')
  193. request_tcp = TCP(sport=sport, dport=smb_port, window=source_win_value, flags='S',
  194. seq=attacker_seq, options=[('MSS', source_mss_value)])
  195. attacker_seq += 1
  196. request = (request_ether / request_ip / request_tcp)
  197. request.time = timestamp_next_pkt
  198. # Append request
  199. packets.append(request)
  200. # Update timestamp for next package
  201. timestamp_reply = update_timestamp(timestamp_next_pkt, pps, minDelay)
  202. while (timestamp_reply <= timestamp_prv_reply):
  203. timestamp_reply = update_timestamp(timestamp_prv_reply, pps, minDelay)
  204. timestamp_prv_reply = timestamp_reply
  205. if ip in hosting_ip:
  206. # 2) Build TCP packages for ip that hosts SMB
  207. # destination sends SYN, ACK
  208. reply_ether = Ether(src=mac_destination, dst=mac_source)
  209. reply_ip = IP(src=ip, dst=ip_source, ttl=destination_ttl_value, flags='DF')
  210. reply_tcp = TCP(sport=smb_port, dport=sport, seq=victim_seq, ack=attacker_seq, flags='SA',
  211. window=destination_win_value, options=[('MSS', destination_mss_value)])
  212. victim_seq += 1
  213. reply = (reply_ether / reply_ip / reply_tcp)
  214. reply.time = timestamp_reply
  215. packets.append(reply)
  216. # requester confirms, ACK
  217. confirm_ether = request_ether
  218. confirm_ip = request_ip
  219. confirm_tcp = TCP(sport=sport, dport=smb_port, seq=attacker_seq, ack=victim_seq,
  220. window=source_win_value, flags='A')
  221. confirm = (confirm_ether / confirm_ip / confirm_tcp)
  222. timestamp_confirm = update_timestamp(timestamp_reply, pps, minDelay)
  223. confirm.time = timestamp_confirm
  224. packets.append(confirm)
  225. smb_MID = randint(1, 65535)
  226. smb_PID = randint(1, 65535)
  227. smb_req_tail_arr = []
  228. smb_req_tail_size = 0
  229. # select dialects based on smb version
  230. if smb_version is "1":
  231. smb_req_dialects = smb_dialects[0:6]
  232. else:
  233. smb_req_dialects = smb_dialects
  234. if len(smb_req_dialects) == 0:
  235. smb_req_tail_arr.append(SMBNegociate_Protocol_Request_Tail())
  236. smb_req_tail_size = len(SMBNegociate_Protocol_Request_Tail())
  237. else:
  238. for dia in smb_req_dialects:
  239. smb_req_tail_arr.append(SMBNegociate_Protocol_Request_Tail(BufferData = dia))
  240. smb_req_tail_size += len(SMBNegociate_Protocol_Request_Tail(BufferData = dia))
  241. smb_req_head = SMBNegociate_Protocol_Request_Header\
  242. (Flags2=0x2801, PID=smb_PID, MID=smb_MID, ByteCount=smb_req_tail_size)
  243. smb_req_length = len(smb_req_head) + smb_req_tail_size
  244. smb_req_net_bio = NBTSession(TYPE=0x00, LENGTH=smb_req_length)
  245. smb_req_tcp = TCP(sport=sport, dport=smb_port, flags='PA', seq=attacker_seq, ack=victim_seq)
  246. smb_req_ip = IP(src=ip_source, dst=ip, ttl=source_ttl_value)
  247. smb_req_ether = Ether(src=mac_source, dst=mac_destination)
  248. attacker_seq += len(smb_req_net_bio) + len(smb_req_head) + smb_req_tail_size
  249. smb_req_combined = (smb_req_ether / smb_req_ip / smb_req_tcp / smb_req_net_bio / smb_req_head)
  250. for i in range(0 , len(smb_req_tail_arr)):
  251. smb_req_combined = smb_req_combined / smb_req_tail_arr[i]
  252. timestamp_smb_req = update_timestamp(timestamp_confirm, pps, minDelay)
  253. smb_req_combined.time = timestamp_smb_req
  254. packets.append(smb_req_combined)
  255. # destination confirms SMB request package
  256. reply_tcp = TCP(sport=smb_port, dport=sport, seq=victim_seq, ack=attacker_seq,
  257. window=destination_win_value, flags='A')
  258. confirm_smb_req = (reply_ether / reply_ip / reply_tcp)
  259. timestamp_reply = update_timestamp(timestamp_smb_req, pps, minDelay)
  260. confirm_smb_req.time = timestamp_reply
  261. packets.append(confirm_smb_req)
  262. # smb response package
  263. first_timestamp = time.mktime(time.strptime(self.statistics.get_pcap_timestamp_start()[:19],
  264. "%Y-%m-%d %H:%M:%S"))
  265. server_Guid, security_blob, capabilities, data_size, server_start_time = get_smb_platform_data\
  266. (self.host_os, first_timestamp)
  267. timestamp_smb_rsp = update_timestamp(timestamp_reply, pps, minDelay)
  268. diff = timestamp_smb_rsp - timestamp_smb_req
  269. begin = get_filetime_format(timestamp_smb_req+diff*0.1)
  270. end = get_filetime_format(timestamp_smb_rsp-diff*0.1)
  271. system_time = randint(begin, end)
  272. if smb_version is not "1" and hosting_version is not "1":
  273. smb_rsp_paket = SMB2_SYNC_Header(Flags = 1)
  274. smb_rsp_negotiate_body = SMB2_Negotiate_Protocol_Response\
  275. (DialectRevision=0x02ff, SecurityBufferOffset=124, SecurityBufferLength=len(security_blob),
  276. SecurityBlob=security_blob, Capabilities=capabilities, MaxTransactSize=data_size,
  277. MaxReadSize=data_size, MaxWriteSize=data_size, SystemTime=system_time,
  278. ServerStartTime=server_start_time, ServerGuid=server_Guid)
  279. smb_rsp_length = len(smb_rsp_paket) + len(smb_rsp_negotiate_body)
  280. else:
  281. smb_rsp_paket = SMBNegociate_Protocol_Response_Advanced_Security\
  282. (Start="\xffSMB", PID=smb_PID, MID=smb_MID, DialectIndex=5, SecurityBlob=security_blob)
  283. smb_rsp_length = len(smb_rsp_paket)
  284. smb_rsp_net_bio = NBTSession(TYPE=0x00, LENGTH=smb_rsp_length)
  285. smb_rsp_tcp = TCP(sport=smb_port, dport=sport, flags='PA', seq=victim_seq, ack=attacker_seq)
  286. smb_rsp_ip = IP(src=ip, dst=ip_source, ttl=destination_ttl_value)
  287. smb_rsp_ether = Ether(src=mac_destination, dst=mac_source)
  288. victim_seq += len(smb_rsp_net_bio) + len(smb_rsp_paket)
  289. if smb_version is not "1"and hosting_version is not "1":
  290. victim_seq += len(smb_rsp_negotiate_body)
  291. smb_rsp_combined = (smb_rsp_ether / smb_rsp_ip / smb_rsp_tcp / smb_rsp_net_bio / smb_rsp_paket)
  292. if smb_version is not "1"and hosting_version is not "1":
  293. smb_rsp_combined = (smb_rsp_combined / smb_rsp_negotiate_body)
  294. smb_rsp_combined.time = timestamp_smb_rsp
  295. packets.append(smb_rsp_combined)
  296. # source confirms SMB response package
  297. confirm_tcp = TCP(sport=sport, dport=smb_port, seq=attacker_seq, ack=victim_seq,
  298. window=source_win_value, flags='A')
  299. confirm_smb_res = (confirm_ether / confirm_ip / confirm_tcp)
  300. timestamp_confirm = update_timestamp(timestamp_smb_rsp, pps, minDelay)
  301. confirm_smb_res.time = timestamp_confirm
  302. packets.append(confirm_smb_res)
  303. # attacker sends FIN ACK
  304. confirm_tcp = TCP(sport=sport, dport=smb_port, seq=attacker_seq, ack=victim_seq,
  305. window=source_win_value, flags='FA')
  306. source_fin_ack = (confirm_ether / confirm_ip / confirm_tcp)
  307. timestamp_src_fin_ack = update_timestamp(timestamp_confirm, pps, minDelay)
  308. source_fin_ack.time = timestamp_src_fin_ack
  309. attacker_seq += 1
  310. packets.append(source_fin_ack)
  311. # victim sends FIN ACK
  312. reply_tcp = TCP(sport=smb_port, dport=sport, seq=victim_seq, ack=attacker_seq,
  313. window=destination_win_value, flags='FA')
  314. destination_fin_ack = (reply_ether / reply_ip / reply_tcp)
  315. timestamp_dest_fin_ack = update_timestamp(timestamp_src_fin_ack, pps, minDelay)
  316. victim_seq += 1
  317. destination_fin_ack.time = timestamp_dest_fin_ack
  318. packets.append(destination_fin_ack)
  319. # source sends final ACK
  320. confirm_tcp = TCP(sport=sport, dport=smb_port, seq=attacker_seq, ack=victim_seq,
  321. window=source_win_value, flags='A')
  322. final_ack = (confirm_ether / confirm_ip / confirm_tcp)
  323. timestamp_final_ack = update_timestamp(timestamp_dest_fin_ack, pps, minDelay)
  324. final_ack.time = timestamp_final_ack
  325. packets.append(final_ack)
  326. else:
  327. # Build RST package
  328. reply_ether = Ether(src=mac_destination, dst=mac_source)
  329. reply_ip = IP(src=ip, dst=ip_source, ttl=destination_ttl_value, flags='DF')
  330. reply_tcp = TCP(sport=smb_port, dport=sport, seq=0, ack=attacker_seq, flags='RA',
  331. window=destination_win_value, options=[('MSS', destination_mss_value)])
  332. reply = (reply_ether / reply_ip / reply_tcp)
  333. reply.time = timestamp_reply
  334. packets.append(reply)
  335. pps = max(get_interval_pps(complement_interval_pps, timestamp_next_pkt), 10)
  336. timestamp_next_pkt = update_timestamp(timestamp_next_pkt, pps)
  337. # store end time of attack
  338. self.attack_end_utime = packets[-1].time
  339. # write attack packets to pcap
  340. pcap_path = self.write_attack_pcap(sorted(packets, key=lambda pkt: pkt.time))
  341. # return packets sorted by packet time_sec_start
  342. return len(packets), pcap_path