413 lines
18 KiB
Python
413 lines
18 KiB
Python
#!/usr/bin/python3
|
|
"""Root helper for applying validated Raymand CTI Nginx settings."""
|
|
import json
|
|
import os
|
|
import pwd
|
|
import re
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
STATE = Path("/opt/cti/nginx-management")
|
|
NGINX_DIR = Path("/etc/nginx/raymand-cti")
|
|
WEBRTC_STATE = STATE / "webrtc.json"
|
|
WEBRTC_CONFIG = NGINX_DIR / "webrtc.conf"
|
|
HOST_STATE = STATE / "host.json"
|
|
STAGED_HOST = STATE / "host.candidate.json"
|
|
SITE_CONFIG = Path("/etc/nginx/sites-available/raymand-cti")
|
|
WEBRTC_SITE = Path("/etc/nginx/sites-available/raymand-cti-webrtc")
|
|
WEBRTC_ENABLED = Path("/etc/nginx/sites-enabled/raymand-cti-webrtc")
|
|
SSL_DIR = Path("/etc/ssl/raymand-cti")
|
|
SSL_CERT = SSL_DIR / "fullchain.pem"
|
|
SSL_KEY = SSL_DIR / "privkey.pem"
|
|
STAGED_CERT = STATE / "ssl-fullchain.candidate"
|
|
STAGED_KEY = STATE / "ssl-private-key.candidate"
|
|
STAGED_DTLS_CERT = STATE / "dtls-fullchain.candidate"
|
|
STAGED_DTLS_KEY = STATE / "dtls-private-key.candidate"
|
|
ASTERISK_KEYS = Path("/opt/cti/base/etc/asterisk/keys")
|
|
ASTERISK_WSS_CERT = ASTERISK_KEYS / "raymand-webrtc-fullchain.pem"
|
|
ASTERISK_WSS_KEY = ASTERISK_KEYS / "raymand-webrtc-privkey.pem"
|
|
ASTERISK_DTLS_CERT = ASTERISK_KEYS / "raymand-webrtc-dtls.pem"
|
|
ASTERISK_DTLS_KEY = ASTERISK_KEYS / "raymand-webrtc-dtls-key.pem"
|
|
|
|
|
|
def atomic_write(path: Path, content: bytes, mode: int) -> None:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
fd, name = tempfile.mkstemp(prefix="." + path.name + ".", dir=path.parent)
|
|
try:
|
|
os.fchmod(fd, mode)
|
|
with os.fdopen(fd, "wb") as target:
|
|
target.write(content)
|
|
target.flush()
|
|
os.fsync(target.fileno())
|
|
os.replace(name, path)
|
|
finally:
|
|
try:
|
|
os.unlink(name)
|
|
except FileNotFoundError:
|
|
pass
|
|
|
|
|
|
def command(args):
|
|
return subprocess.run(args, text=True, stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT, timeout=30)
|
|
|
|
|
|
def read_service_file(path: Path, limit: int) -> bytes:
|
|
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
|
try:
|
|
info = os.fstat(fd)
|
|
if not stat.S_ISREG(info.st_mode) or info.st_uid != pwd.getpwnam("pline").pw_uid:
|
|
raise RuntimeError("Staged Nginx input has an unexpected owner or file type")
|
|
if info.st_mode & 0o077 or info.st_size > limit:
|
|
raise RuntimeError("Staged Nginx input permissions or size are invalid")
|
|
with os.fdopen(fd, "rb", closefd=False) as source:
|
|
data = source.read(limit + 1)
|
|
if len(data) > limit:
|
|
raise RuntimeError("Staged Nginx input exceeds the maximum size")
|
|
return data
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
def reload_nginx():
|
|
test = command(["/usr/sbin/nginx", "-t"])
|
|
if test.returncode:
|
|
raise RuntimeError("Nginx configuration test failed: " + test.stdout[-2000:])
|
|
reload = command(["/bin/systemctl", "reload", "nginx.service"])
|
|
if reload.returncode:
|
|
raise RuntimeError("Nginx reload failed: " + reload.stdout[-2000:])
|
|
|
|
|
|
def validate_server_name(name):
|
|
label = r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?"
|
|
if name == "_":
|
|
return
|
|
if not isinstance(name, str) or not re.fullmatch(
|
|
r"(?:\[[0-9A-Fa-f:]+\]|" + label + r"(?:\." + label + r")*|(?:[0-9]{1,3}\.){3}[0-9]{1,3})", name):
|
|
raise RuntimeError("Server name must be a valid DNS name, IP address, or _")
|
|
|
|
|
|
def read_host_settings():
|
|
try:
|
|
settings = json.loads(HOST_STATE.read_text(encoding="utf-8"))
|
|
except (OSError, json.JSONDecodeError):
|
|
settings = {"serverName": "_", "httpPort": 80, "httpsPort": 443}
|
|
return settings
|
|
|
|
|
|
def replace_site_ports(host):
|
|
text = SITE_CONFIG.read_text(encoding="utf-8")
|
|
blocks = []
|
|
start = None
|
|
depth = 0
|
|
for index, line in enumerate(text.splitlines(keepends=True)):
|
|
if start is None and re.match(r"\s*server\s*\{", line):
|
|
start = index
|
|
depth = 0
|
|
if start is not None:
|
|
depth += line.count("{") - line.count("}")
|
|
if depth == 0:
|
|
blocks.append((start, index + 1))
|
|
start = None
|
|
lines = text.splitlines(keepends=True)
|
|
if len(blocks) < 2:
|
|
raise RuntimeError("Managed Raymand CTI Nginx site has an unexpected structure")
|
|
for block_index, (first, end) in reversed(list(enumerate(blocks[:2]))):
|
|
segment = lines[first:end]
|
|
port = host["httpPort"] if block_index == 0 else host["httpsPort"]
|
|
out = []
|
|
has_redirect = False
|
|
redirect_enabled = host.get("redirectHttpToHttps", True)
|
|
if not isinstance(redirect_enabled, bool):
|
|
raise RuntimeError("HTTP-to-HTTPS redirect setting is invalid")
|
|
for line in segment:
|
|
stripped = line.strip()
|
|
if re.match(r"listen\s+(?:\[::\]:)?\d+\b", stripped):
|
|
line = re.sub(r"(listen\s+)(\[::\]:)?\d+", lambda match: match.group(1) + (match.group(2) or "") + str(port), line, count=1)
|
|
if re.match(r"\s*server_name\s+", line):
|
|
indent = line[:len(line) - len(line.lstrip())]
|
|
line = f"{indent}server_name {host['serverName']};\n"
|
|
if block_index == 0 and re.match(r"\s*return\s+301\s+https://\$host", line):
|
|
has_redirect = True
|
|
if not redirect_enabled:
|
|
continue
|
|
indent = line[:len(line) - len(line.lstrip())]
|
|
line = f"{indent}return 301 https://$host:{host['httpsPort']}$request_uri;\n"
|
|
out.append(line)
|
|
if block_index == 0:
|
|
if redirect_enabled and not has_redirect:
|
|
closing = next((i for i in range(len(out) - 1, -1, -1) if out[i].strip() == "}"), None)
|
|
if closing is None:
|
|
raise RuntimeError("HTTP server block is malformed")
|
|
out.insert(closing, f" return 301 https://$host:{host['httpsPort']}$request_uri;\n")
|
|
# Keep the panel reachable over HTTP when automatic redirect is disabled.
|
|
if not any(re.match(r"\s*root\s+/var/www/cti", line) for line in out):
|
|
closing = next((i for i in range(len(out) - 1, -1, -1) if out[i].strip() == "}"), None)
|
|
if closing is None:
|
|
raise RuntimeError("HTTP server block is malformed")
|
|
out[closing:closing] = [
|
|
" root /var/www/cti;\n", " index index.html;\n",
|
|
" client_max_body_size 1024m;\n",
|
|
" location / { try_files $uri $uri/ /index.html; }\n",
|
|
" location = /api { return 301 /api/; }\n",
|
|
" location /api/ { proxy_pass http://127.0.0.1:8080/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }\n",
|
|
" location /ws { proxy_pass http://127.0.0.1:8080/ws; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection \"upgrade\"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; }\n",
|
|
]
|
|
lines[first:end] = out
|
|
atomic_write(SITE_CONFIG, "".join(lines).encode(), 0o644)
|
|
|
|
|
|
def restore_site(original):
|
|
atomic_write(SITE_CONFIG, original, 0o644)
|
|
|
|
|
|
def read_ssl():
|
|
cert = SSL_CERT.read_text(encoding="utf-8") if SSL_CERT.is_file() else ""
|
|
key = SSL_KEY.read_text(encoding="utf-8") if SSL_KEY.is_file() else ""
|
|
print(json.dumps({"fullchain": cert, "privateKey": key}))
|
|
|
|
|
|
def validate_ssl_pair(cert_data: bytes, key_data: bytes):
|
|
with tempfile.TemporaryDirectory(prefix="raymand-nginx-ssl-") as work:
|
|
cert_candidate = Path(work) / "fullchain.pem"
|
|
key_candidate = Path(work) / "private-key.pem"
|
|
cert_candidate.write_bytes(cert_data)
|
|
key_candidate.write_bytes(key_data)
|
|
cert_check = command(["/usr/bin/openssl", "x509", "-in", str(cert_candidate), "-noout", "-checkend", "0"])
|
|
key_check = command(["/usr/bin/openssl", "pkey", "-in", str(key_candidate), "-passin", "pass:", "-noout", "-check"])
|
|
cert_pub = command(["/usr/bin/openssl", "x509", "-in", str(cert_candidate), "-pubkey", "-noout"])
|
|
key_pub = command(["/usr/bin/openssl", "pkey", "-in", str(key_candidate), "-passin", "pass:", "-pubout"])
|
|
if any(result.returncode for result in (cert_check, key_check, cert_pub, key_pub)):
|
|
raise RuntimeError("Certificate or private key is not valid PEM, or the certificate has expired")
|
|
if cert_pub.stdout.strip() != key_pub.stdout.strip():
|
|
raise RuntimeError("Private key does not match the certificate")
|
|
|
|
|
|
def replace_with_rollback(primary: Path, primary_data: bytes, primary_mode: int,
|
|
secondary: Path = None, secondary_data: bytes = None,
|
|
secondary_mode: int = 0o600):
|
|
originals = {}
|
|
for path in (primary, secondary):
|
|
if path is not None:
|
|
originals[path] = path.read_bytes() if path.exists() else None
|
|
try:
|
|
atomic_write(primary, primary_data, primary_mode)
|
|
if secondary is not None:
|
|
atomic_write(secondary, secondary_data, secondary_mode)
|
|
reload_nginx()
|
|
except Exception:
|
|
for path, old in originals.items():
|
|
if old is None:
|
|
try:
|
|
path.unlink()
|
|
except FileNotFoundError:
|
|
pass
|
|
else:
|
|
atomic_write(path, old, 0o600 if path == SSL_KEY else 0o644)
|
|
try:
|
|
command(["/usr/sbin/nginx", "-t"])
|
|
command(["/bin/systemctl", "reload", "nginx.service"])
|
|
except Exception:
|
|
pass
|
|
raise
|
|
|
|
|
|
def apply_ssl():
|
|
cert_data = read_service_file(STAGED_CERT, 2 * 1024 * 1024)
|
|
key_data = read_service_file(STAGED_KEY, 1024 * 1024)
|
|
validate_ssl_pair(cert_data, key_data)
|
|
try:
|
|
settings = json.loads(read_service_file(STAGED_HOST, 16 * 1024).decode("utf-8"))
|
|
name = settings.get("serverName")
|
|
http_port, https_port = settings.get("httpPort"), settings.get("httpsPort")
|
|
validate_server_name(name)
|
|
if any(isinstance(p, bool) or not isinstance(p, int) or not 1 <= p <= 65535
|
|
for p in (http_port, https_port)) or http_port == https_port:
|
|
raise RuntimeError("HTTP and HTTPS ports must be valid and distinct")
|
|
except (OSError, json.JSONDecodeError, AttributeError) as exc:
|
|
raise RuntimeError("Cannot read the staged host SSL settings") from exc
|
|
old_site = SITE_CONFIG.read_bytes()
|
|
old_host = HOST_STATE.read_bytes() if HOST_STATE.exists() else None
|
|
old_cert = SSL_CERT.read_bytes() if SSL_CERT.exists() else None
|
|
old_key = SSL_KEY.read_bytes() if SSL_KEY.exists() else None
|
|
try:
|
|
replace_site_ports(settings)
|
|
atomic_write(SSL_CERT, cert_data, 0o644)
|
|
atomic_write(SSL_KEY, key_data, 0o600)
|
|
atomic_write(HOST_STATE, (json.dumps(settings) + "\n").encode(), 0o644)
|
|
reload_nginx()
|
|
except Exception:
|
|
restore_site(old_site)
|
|
if old_cert is None:
|
|
SSL_CERT.unlink(missing_ok=True)
|
|
else:
|
|
atomic_write(SSL_CERT, old_cert, 0o644)
|
|
if old_key is None:
|
|
SSL_KEY.unlink(missing_ok=True)
|
|
else:
|
|
atomic_write(SSL_KEY, old_key, 0o600)
|
|
if old_host is None:
|
|
HOST_STATE.unlink(missing_ok=True)
|
|
else:
|
|
atomic_write(HOST_STATE, old_host, 0o644)
|
|
try:
|
|
reload_nginx()
|
|
except Exception:
|
|
pass
|
|
raise
|
|
STAGED_CERT.unlink(missing_ok=True)
|
|
STAGED_KEY.unlink(missing_ok=True)
|
|
STAGED_HOST.unlink(missing_ok=True)
|
|
|
|
|
|
def apply_webrtc():
|
|
try:
|
|
settings = json.loads(read_service_file(WEBRTC_STATE, 16 * 1024).decode("utf-8"))
|
|
except (OSError, json.JSONDecodeError) as exc:
|
|
raise RuntimeError("Cannot read WebRTC settings") from exc
|
|
if not isinstance(settings, dict):
|
|
raise RuntimeError("WebRTC settings are invalid")
|
|
mode = settings.get("mode")
|
|
dtls_mode = settings.get("dtlsMode", "auto")
|
|
port = settings.get("httpPort")
|
|
upstream_host = settings.get("upstreamHost", "127.0.0.1")
|
|
server_name = settings.get("serverName", "_")
|
|
public_port = settings.get("port", 443)
|
|
validate_server_name(server_name)
|
|
if isinstance(public_port, bool) or not isinstance(public_port, int) or not 1 <= public_port <= 65535:
|
|
raise RuntimeError("WebRTC public port is invalid")
|
|
if mode not in ("proxy", "direct") or dtls_mode not in ("auto", "custom"):
|
|
raise RuntimeError("WebRTC mode is invalid")
|
|
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
|
|
raise RuntimeError("Asterisk HTTP port is invalid")
|
|
label = r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?"
|
|
if not isinstance(upstream_host, str) or not re.fullmatch(
|
|
r"(?:\[[0-9A-Fa-f:]+\]|" + label + r"(?:\." + label + r")*|(?:[0-9]{1,3}\.){3}[0-9]{1,3})",
|
|
upstream_host):
|
|
raise RuntimeError("Asterisk HTTP bind address is invalid")
|
|
|
|
rendered = b""
|
|
host = read_host_settings()
|
|
same_site = public_port == host.get("httpsPort", 443) and server_name == host.get("serverName", "_")
|
|
vhost = None
|
|
if mode == "proxy":
|
|
if public_port == host.get("httpPort", 80):
|
|
raise RuntimeError("WebRTC TLS port cannot be the same as the host HTTP redirect port")
|
|
rendered = (
|
|
"# Managed by Raymand CTI. Keep this file unchanged.\n"
|
|
"location = /asterisk-ws {\n"
|
|
f" proxy_pass http://{upstream_host}:{port}/ws;\n"
|
|
" proxy_http_version 1.1;\n"
|
|
" proxy_set_header Upgrade $http_upgrade;\n"
|
|
" proxy_set_header Connection \"upgrade\";\n"
|
|
" proxy_set_header Host $host;\n"
|
|
" proxy_set_header X-Real-IP $remote_addr;\n"
|
|
" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n"
|
|
" proxy_set_header X-Forwarded-Proto $scheme;\n"
|
|
" proxy_read_timeout 86400s;\n"
|
|
"}\n"
|
|
).encode() if same_site else b""
|
|
if not same_site:
|
|
vhost = (
|
|
"# Managed by Raymand CTI. Keep this file unchanged.\n"
|
|
f"server {{\n listen {public_port} ssl;\n listen [::]:{public_port} ssl;\n"
|
|
f" server_name {server_name};\n"
|
|
f" ssl_certificate {SSL_CERT};\n ssl_certificate_key {SSL_KEY};\n"
|
|
" ssl_protocols TLSv1.2 TLSv1.3;\n"
|
|
" location = /asterisk-ws {\n"
|
|
f" proxy_pass http://{upstream_host}:{port}/ws;\n"
|
|
" proxy_http_version 1.1;\n"
|
|
" proxy_set_header Upgrade $http_upgrade;\n"
|
|
" proxy_set_header Connection \"upgrade\";\n"
|
|
" proxy_set_header Host $host;\n"
|
|
" proxy_set_header X-Real-IP $remote_addr;\n"
|
|
" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n"
|
|
" proxy_set_header X-Forwarded-Proto $scheme;\n"
|
|
" proxy_read_timeout 86400s;\n }\n}\n"
|
|
).encode()
|
|
|
|
if mode == "direct":
|
|
if not SSL_CERT.is_file() or not SSL_KEY.is_file():
|
|
raise RuntimeError("Apply a valid host SSL certificate before enabling direct Asterisk HTTPS")
|
|
cert_data = SSL_CERT.read_bytes()
|
|
key_data = SSL_KEY.read_bytes()
|
|
validate_ssl_pair(cert_data, key_data)
|
|
install_asterisk_pair(ASTERISK_WSS_CERT, ASTERISK_WSS_KEY, cert_data, key_data)
|
|
|
|
if dtls_mode == "custom":
|
|
if STAGED_DTLS_CERT.exists() and STAGED_DTLS_KEY.exists():
|
|
cert_data = read_service_file(STAGED_DTLS_CERT, 2 * 1024 * 1024)
|
|
key_data = read_service_file(STAGED_DTLS_KEY, 1024 * 1024)
|
|
elif ASTERISK_DTLS_CERT.is_file() and ASTERISK_DTLS_KEY.is_file():
|
|
cert_data = ASTERISK_DTLS_CERT.read_bytes()
|
|
key_data = ASTERISK_DTLS_KEY.read_bytes()
|
|
else:
|
|
raise RuntimeError("Custom DTLS certificate files are missing; paste them again in the settings page")
|
|
validate_ssl_pair(cert_data, key_data)
|
|
install_asterisk_pair(ASTERISK_DTLS_CERT, ASTERISK_DTLS_KEY, cert_data, key_data)
|
|
STAGED_DTLS_CERT.unlink(missing_ok=True)
|
|
STAGED_DTLS_KEY.unlink(missing_ok=True)
|
|
else:
|
|
ASTERISK_DTLS_CERT.unlink(missing_ok=True)
|
|
ASTERISK_DTLS_KEY.unlink(missing_ok=True)
|
|
|
|
old_vhost = WEBRTC_SITE.read_bytes() if WEBRTC_SITE.exists() else None
|
|
old_enabled = os.readlink(WEBRTC_ENABLED) if WEBRTC_ENABLED.is_symlink() else None
|
|
old_enabled_regular = WEBRTC_ENABLED.exists() and not WEBRTC_ENABLED.is_symlink()
|
|
try:
|
|
if vhost is not None:
|
|
atomic_write(WEBRTC_SITE, vhost, 0o644)
|
|
WEBRTC_ENABLED.parent.mkdir(parents=True, exist_ok=True)
|
|
WEBRTC_ENABLED.unlink(missing_ok=True)
|
|
WEBRTC_ENABLED.symlink_to(WEBRTC_SITE)
|
|
else:
|
|
WEBRTC_ENABLED.unlink(missing_ok=True)
|
|
WEBRTC_SITE.unlink(missing_ok=True)
|
|
replace_with_rollback(WEBRTC_CONFIG, rendered, 0o644)
|
|
except Exception:
|
|
if old_vhost is None:
|
|
WEBRTC_SITE.unlink(missing_ok=True)
|
|
else:
|
|
atomic_write(WEBRTC_SITE, old_vhost, 0o644)
|
|
WEBRTC_ENABLED.unlink(missing_ok=True)
|
|
if old_enabled is not None:
|
|
WEBRTC_ENABLED.symlink_to(old_enabled)
|
|
elif old_enabled_regular:
|
|
atomic_write(WEBRTC_ENABLED, b"", 0o644)
|
|
raise
|
|
|
|
|
|
def install_asterisk_pair(cert_path: Path, key_path: Path, cert_data: bytes, key_data: bytes):
|
|
user = pwd.getpwnam("pline")
|
|
ASTERISK_KEYS.mkdir(parents=True, exist_ok=True)
|
|
atomic_write(cert_path, cert_data, 0o644)
|
|
atomic_write(key_path, key_data, 0o600)
|
|
os.chown(cert_path, user.pw_uid, user.pw_gid)
|
|
os.chown(key_path, user.pw_uid, user.pw_gid)
|
|
|
|
|
|
def main():
|
|
if os.geteuid() != 0:
|
|
raise RuntimeError("This helper must be run through its restricted sudo rule")
|
|
if len(sys.argv) != 2 or sys.argv[1] not in ("read-ssl", "apply-ssl", "apply-webrtc"):
|
|
raise RuntimeError("Unsupported Nginx operation")
|
|
if sys.argv[1] == "read-ssl":
|
|
read_ssl()
|
|
return
|
|
if sys.argv[1] == "apply-ssl":
|
|
apply_ssl()
|
|
else:
|
|
apply_webrtc()
|
|
print("Nginx configuration applied")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except Exception as error:
|
|
print(str(error), file=sys.stderr)
|
|
sys.exit(1)
|