#!/usr/bin/env python3
"""
HTTPS server for the Hangout Services cross-origin tab origin disclosure POC.

Serves on https://127.0.0.1:8443 with a self-signed cert. Chrome's
--host-resolver-rules maps *.meet.google.com and the victim domains to
127.0.0.1, so the same server backs multiple origins.
"""
import http.server
import ssl
import os
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
CERT = os.path.join(HERE, "poc-cert.pem")
KEY = os.path.join(HERE, "poc-key.pem")
PORT = 9000

if not (os.path.exists(CERT) and os.path.exists(KEY)):
    print("[*] Generating self-signed cert...", file=sys.stderr)
    subprocess.check_call([
        "openssl", "req", "-x509", "-newkey", "rsa:2048",
        "-keyout", KEY, "-out", CERT,
        "-days", "365", "-nodes",
        "-subj", "/CN=localhost",
    ])

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=HERE, **kw)

    def log_message(self, fmt, *args):
        sys.stderr.write("[server] " + (fmt % args) + "\n")


def main():
    httpd = http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler)
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(certfile=CERT, keyfile=KEY)
    httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
    print(f"[*] Serving HTTPS on https://127.0.0.1:{PORT}/", file=sys.stderr)
    httpd.serve_forever()


if __name__ == "__main__":
    main()
