SMBScanAttack.py 21 KB

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