#!/usr/bin/env python3
"""
Certbot --deploy-hook script: uploads a certificate issued through TrustView's ACME server to a
Barracuda Web Application Firewall (WAF) over its REST API, and binds it to an HTTPS service.

Run by Certbot after a successful issuance or renewal. Reads the certificate, chain and key from
$RENEWED_LINEAGE (which Certbot sets for every --deploy-hook invocation) unless --cert-file,
--chain-file and --key-file are given explicitly.

What it does, in order:

  1. Logs in to the WAF REST API (POST /restapi/<version>/login) and gets a session token.
  2. Uploads the certificate as a new signed PEM certificate with a unique, timestamped name
     (POST /restapi/<version>/certificates?upload=signed). A new name is used on every renewal
     because a certificate that is in use by a service can't be replaced in place.
  3. Binds the new certificate to the HTTPS service (PUT /restapi/<version>/services/<service>/ssl-security).
  4. Optionally deletes the certificate that was bound before (--delete-previous), once the new
     one is in place.
  5. Logs out.

Requires Python 3.8+ only - no extra packages. The WAF password is read from --password-file
or the BARRACUDA_WAF_PASSWORD environment variable, never from the command line.

Written against Barracuda's published REST API v3.x documentation (login, token, and certificate
upload endpoints).
"""
import argparse
import base64
import json
import os
import re
import ssl
import sys
import time
import uuid
import urllib.error
import urllib.parse
import urllib.request


class WafError(Exception):
    pass


class WafClient:
    def __init__(self, host, port, api_version, use_https=True, ca_file=None, insecure=False, timeout=60):
        scheme = "https" if use_https else "http"
        self.base = f"{scheme}://{host}:{port}/restapi/{api_version}"
        self.timeout = timeout
        self.token = None
        self.context = None
        if use_https:
            if insecure:
                self.context = ssl._create_unverified_context()
            else:
                self.context = ssl.create_default_context(cafile=ca_file)

    def _request(self, method, path, body=None, content_type=None):
        url = self.base + path
        headers = {"Accept": "application/json"}
        if content_type:
            headers["Content-Type"] = content_type
        if self.token:
            # The WAF expects the token as the basic-auth username, with an empty password.
            auth = base64.b64encode(f"{self.token}:".encode("utf-8")).decode("ascii")
            headers["Authorization"] = f"Basic {auth}"
        req = urllib.request.Request(url, data=body, headers=headers, method=method)
        try:
            with urllib.request.urlopen(req, timeout=self.timeout, context=self.context) as resp:
                raw = resp.read().decode("utf-8", errors="replace")
        except urllib.error.HTTPError as e:
            detail = e.read().decode("utf-8", errors="replace")
            raise WafError(f"{method} {path} failed with HTTP {e.code}: {detail.strip()}") from None
        except urllib.error.URLError as e:
            raise WafError(f"{method} {path} failed: {e.reason}") from None
        if not raw.strip():
            return {}
        try:
            return json.loads(raw)
        except ValueError:
            return {"raw": raw}

    def login(self, username, password):
        body = json.dumps({"username": username, "password": password}).encode("utf-8")
        result = self._request("POST", "/login", body, "application/json")
        token = result.get("token") if isinstance(result, dict) else None
        if not token:
            raise WafError(f"Login succeeded but no token was returned: {result}")
        self.token = token

    def logout(self):
        if self.token:
            try:
                self._request("DELETE", "/logout")
            except WafError:
                pass  # Best effort - the session times out on its own.
            self.token = None

    def upload_signed_pem(self, name, cert_pem, key_pem, chain_pem, key_type, allow_key_export):
        fields = [
            ("name", None, name),
            ("type", None, "pem"),
            ("key_type", None, key_type),
            ("assign_associated_key", None, "no"),
            ("allow_private_key_export", None, "yes" if allow_key_export else "no"),
            ("signed_certificate", "cert.pem", cert_pem),
            ("key", "privkey.pem", key_pem),
        ]
        if chain_pem:
            fields.append(("intermediary_certificate", "chain.pem", chain_pem))
        body, content_type = encode_multipart(fields)
        return self._request("POST", "/certificates?upload=signed", body, content_type)

    def get_ssl_security(self, service):
        return self._request("GET", f"/services/{urllib.parse.quote(service, safe='')}/ssl-security")

    def bind_certificate(self, service, cert_name):
        body = json.dumps({"certificate": cert_name}).encode("utf-8")
        return self._request(
            "PUT", f"/services/{urllib.parse.quote(service, safe='')}/ssl-security", body, "application/json"
        )

    def delete_certificate(self, cert_name):
        return self._request("DELETE", f"/certificates/{urllib.parse.quote(cert_name, safe='')}")


def encode_multipart(fields):
    """fields: list of (name, filename-or-None, str value). Returns (body bytes, content type)."""
    boundary = "----trustview" + uuid.uuid4().hex
    parts = []
    for name, filename, value in fields:
        disposition = f'form-data; name="{name}"'
        if filename:
            disposition += f'; filename="{filename}"'
        header = f"--{boundary}\r\nContent-Disposition: {disposition}\r\n"
        if filename:
            header += "Content-Type: application/x-pem-file\r\n"
        parts.append((header + "\r\n").encode("utf-8") + value.encode("utf-8") + b"\r\n")
    parts.append(f"--{boundary}--\r\n".encode("utf-8"))
    return b"".join(parts), f"multipart/form-data; boundary={boundary}"


def find_certificate_name(obj):
    """Find the currently bound certificate name in an ssl-security GET response, whatever its nesting."""
    if isinstance(obj, dict):
        for key, value in obj.items():
            if key.lower() == "certificate" and isinstance(value, str) and value:
                return value
        for value in obj.values():
            found = find_certificate_name(value)
            if found:
                return found
    elif isinstance(obj, list):
        for item in obj:
            found = find_certificate_name(item)
            if found:
                return found
    return None


def read_pem(path):
    with open(path, "r", encoding="utf-8") as f:
        content = f.read().strip()
    if "-----BEGIN" not in content:
        raise SystemExit(f"'{path}' does not look like a PEM file (no BEGIN marker found).")
    return content + "\n"


def read_password(args):
    if args.password_file:
        with open(args.password_file, "r", encoding="utf-8") as f:
            password = f.read().strip()
    else:
        password = os.environ.get("BARRACUDA_WAF_PASSWORD", "")
    if not password:
        raise SystemExit("No WAF password given - use --password-file or set BARRACUDA_WAF_PASSWORD.")
    return password


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--host", required=True, help="Barracuda WAF management IP or hostname")
    parser.add_argument("--port", type=int, help="REST API port (default: 8443 for HTTPS, 8000 for HTTP)")
    parser.add_argument("--http", action="store_true", help="Use plain HTTP (port 8000) instead of HTTPS - not recommended")
    parser.add_argument("--api-version", default="v3.2", help="REST API version in the URL path (default: v3.2)")
    parser.add_argument("--ca-file", help="CA bundle used to verify the WAF management certificate")
    parser.add_argument("--insecure", action="store_true", help="Don't verify the WAF management certificate (testing only)")
    parser.add_argument("--user", required=True, help="WAF administrator username")
    parser.add_argument("--password-file", help="File containing the WAF password (else $BARRACUDA_WAF_PASSWORD)")
    parser.add_argument("--service", required=True, help="Name of the HTTPS service on the WAF to bind the certificate to")
    parser.add_argument("--cert-prefix", required=True, help="Prefix for the certificate name on the WAF, e.g. www_example_com")
    parser.add_argument("--key-type", choices=["rsa", "ecdsa"], default="rsa", help="Private key type (default: rsa)")
    parser.add_argument("--allow-key-export", action="store_true", help="Allow the private key to be exported from the WAF")
    parser.add_argument("--delete-previous", action="store_true", help="Delete the previously bound certificate after binding the new one")
    parser.add_argument("--cert-file", help="Leaf certificate (defaults to $RENEWED_LINEAGE/cert.pem)")
    parser.add_argument("--chain-file", help="Intermediate chain (defaults to $RENEWED_LINEAGE/chain.pem)")
    parser.add_argument("--key-file", help="Private key (defaults to $RENEWED_LINEAGE/privkey.pem)")
    args = parser.parse_args(argv)

    if not re.fullmatch(r"[A-Za-z0-9_]+", args.cert_prefix):
        raise SystemExit("--cert-prefix may only contain letters, digits and underscores.")

    lineage = os.environ.get("RENEWED_LINEAGE")
    cert_file = args.cert_file or (os.path.join(lineage, "cert.pem") if lineage else None)
    chain_file = args.chain_file or (os.path.join(lineage, "chain.pem") if lineage else None)
    key_file = args.key_file or (os.path.join(lineage, "privkey.pem") if lineage else None)
    if not cert_file or not key_file:
        raise SystemExit(
            "No certificate/key path given, and $RENEWED_LINEAGE is not set - pass --cert-file, "
            "--chain-file and --key-file explicitly, or run this script from a Certbot --deploy-hook."
        )

    cert_pem = read_pem(cert_file)
    key_pem = read_pem(key_file)
    chain_pem = read_pem(chain_file) if chain_file and os.path.exists(chain_file) else None
    password = read_password(args)

    port = args.port or (8000 if args.http else 8443)
    cert_name = f"{args.cert_prefix}_{time.strftime('%Y%m%d%H%M%S')}"

    client = WafClient(args.host, port, args.api_version, use_https=not args.http,
                       ca_file=args.ca_file, insecure=args.insecure)
    try:
        client.login(args.user, password)

        previous = None
        if args.delete_previous:
            previous = find_certificate_name(client.get_ssl_security(args.service))

        client.upload_signed_pem(cert_name, cert_pem, key_pem, chain_pem, args.key_type, args.allow_key_export)
        print(f"Uploaded certificate '{cert_name}' to {args.host}.")

        client.bind_certificate(args.service, cert_name)
        print(f"Bound '{cert_name}' to service '{args.service}'.")

        if args.delete_previous:
            if previous and previous != cert_name:
                try:
                    client.delete_certificate(previous)
                    print(f"Deleted previous certificate '{previous}'.")
                except WafError as e:
                    print(f"Warning: could not delete previous certificate '{previous}': {e}", file=sys.stderr)
            else:
                print("No previously bound certificate found to delete.")
    except WafError as e:
        raise SystemExit(f"Barracuda WAF deployment failed: {e}")
    finally:
        client.logout()


if __name__ == "__main__":
    main()
