#!/usr/bin/env python

import os
import socket
import ssl
import sys
import time
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
from SocketServer import ThreadingMixIn
from threading import Thread


class GetHandler(BaseHTTPRequestHandler):
    # Some of the http server code came from Dave Kennedy's AES shell
    # over http - the server specific code

    # should be performing GET requests Help from
    # http://pymotw.com/2/BaseHTTPServer/
    def do_GET(self):
        print "Someone is trying to make a GET request to this server..."
        # 404 since we aren't serving up any pages, only receiving data
        self.send_response(404)
        self.end_headers()
        return

    # handle post request
    def do_POST(self):

        # current directory
        exfil_directory = os.path.join(os.getcwd(), "data")
        loot_path = exfil_directory + "/"

        # Info for this from -
        # http://stackoverflow.com/questions/13146064/simple-
        # python-webserver-to-save-file
        if self.path == "/post_enum_data.php":

            self.send_response(200)
            self.end_headers()

            # Check to make sure the agent directory exists, and a loot
            # directory for the agent.  If not, make them
            if not os.path.isdir(loot_path):
                os.makedirs(loot_path)

            # Get the date info
            current_date = time.strftime("%m/%d/%Y")
            current_time = time.strftime("%H:%M:%S")
            screenshot_name = current_date.replace("/", "") +\
                "_" + current_time.replace(":", "") + "enumeration_data.txt"

            # Read the length of the screenshot file being uploaded
            screen_length = self.headers['content-length']
            screen_data = self.rfile.read(int(screen_length))

            # Write out the file
            with open(loot_path + screenshot_name, 'a') as cc_data_file:
                cc_data_file.write(screen_data)

        # All other Post requests
        else:

            self.send_response(404)
            self.end_headers()

            print "Odd... someone else is trying to access this web server..."
            print "Might want to check that out..."
        return


class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    pass


def serve_on_port():
    try:
        cert_path = os.path.dirname(os.path.realpath(__file__)) +\
            '/web/server.pem'
        server = ThreadingHTTPServer(
            ("0.0.0.0", 443), GetHandler)
        server.socket = ssl.wrap_socket(
            server.socket, certfile=cert_path, server_side=True)
        server.serve_forever()
    except socket.error:
        print "[*][*] Error: Port %d is currently in use!" % port
        print "[*][*] Error: Please restart when port is free!\n"
        sys.exit()
    return


try:
    print "[*] Starting web (https) server..."
    # bind to all interfaces
    Thread(target=serve_on_port).start()
    print "[*] Web server is currently running"
    print "[*] Type \"kill -9 " + str(os.getpid()) + "\" to stop the web server."
# handle keyboard interrupts
except KeyboardInterrupt:
    print "[!] Rage quiting, and stopping the web server!"
