fix: restore Trojan certificates and schedule host renewals
This commit is contained in:
@@ -6,3 +6,39 @@
|
||||
4. 使用 `verify.sh` 验证管理端、证书、Trojan 监听与公开 443 分享链接。
|
||||
5. 正式切换时停止并重命名旧容器为 `trojan-legacy`,再以本 compose 启动新容器。
|
||||
6. 任一核心检查失败,立即运行 `rollback.sh`。保留旧容器至少一个证书续期周期。
|
||||
|
||||
## Docker 证书自动续期(2026-10-24 修正)
|
||||
|
||||
兼容镜像使用 `systemctl.py`,容器中的 `.timer` 不会实际调度。必须在
|
||||
**宿主机**安装仓库 `trojan-stack/scripts/` 下的脚本和 systemd 单元:
|
||||
|
||||
```bash
|
||||
install -m 0755 trojan-stack/scripts/renew-certificate-host.py /usr/local/sbin/renew-trojan-certificate-host.py
|
||||
install -m 0644 trojan-stack/scripts/trojan-certificate-renew.service /etc/systemd/system/
|
||||
install -m 0644 trojan-stack/scripts/trojan-certificate-renew.timer /etc/systemd/system/
|
||||
systemd-analyze verify /etc/systemd/system/trojan-certificate-renew.service /etc/systemd/system/trojan-certificate-renew.timer
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now trojan-certificate-renew.timer
|
||||
systemctl start trojan-certificate-renew.service
|
||||
systemctl list-timers --all trojan-certificate-renew.timer
|
||||
journalctl -u trojan-certificate-renew.service -n 80 --no-pager
|
||||
```
|
||||
|
||||
依赖宿主机 Python 3、OpenSSL、Docker CLI 和真实 systemd。默认操作 `trojan`
|
||||
容器,配置与证书必须使用持久化 bind mount。域名与实际证书路径从现有
|
||||
`/usr/local/etc/trojan/config.json` 读取,当前实现针对 ECC 证书。
|
||||
|
||||
HTTP-01 使用 `/var/lib/trojan-acme-webroot`,宿主机 Nginx 的
|
||||
`/.well-known/acme-challenge/` 必须转发到现有 `127.0.0.1:8082` 常驻文件服务。
|
||||
初次从旧 standalone 配置迁移时先使用 `acme.sh --issue --webroot
|
||||
/var/lib/trojan-acme-webroot -d <域名> --keylength ec-256` 签发;之后脚本按
|
||||
到期计划调用 `--renew --ecc --webroot`,不用 `--force`。
|
||||
|
||||
定时器每天 03:00、15:00(宿主机时区)加 0–30 分钟随机延迟检查,开机后
|
||||
5 分钟也检查,并补执行关机期间错过的日历任务。脚本使用文件锁防并发;
|
||||
校验至少 7 天有效期、域名、ECC/RSA 通用公钥匹配,然后部署到配置指定路径。
|
||||
只有运行中证书指纹与文件不同才重启 Trojan,最后校验运行端口 TLS 信任链、
|
||||
域名与证书指纹。失败会使 service 返回非零并写入 journal;尚未接入外部通知。
|
||||
|
||||
容器内旧 `trojan-acme-renew.timer` 与旧 acme.sh crontab 应停用,避免未来启动
|
||||
cron 后出现两套调度。安装宿主机定时器不需要重建或重启整个容器。
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Renew a legacy Trojan container's certificate using host systemd scheduling."""
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
|
||||
def run(args, **kwargs):
|
||||
return subprocess.run(args, check=True, timeout=900, **kwargs)
|
||||
|
||||
|
||||
def main():
|
||||
container = os.environ.get("TROJAN_CONTAINER", "trojan")
|
||||
lock = open("/run/lock/trojan-certificate-renew.lock", "w")
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
print("Another renewal check is running", flush=True)
|
||||
return
|
||||
info = json.loads(run(["docker", "inspect", container], capture_output=True).stdout)[0]
|
||||
if not info["State"]["Running"]:
|
||||
raise RuntimeError("Trojan container is not running")
|
||||
|
||||
def host_path(path):
|
||||
for mount in sorted(info["Mounts"], key=lambda m: len(m["Destination"]), reverse=True):
|
||||
dest = mount["Destination"].rstrip("/")
|
||||
if path.startswith(dest + "/"):
|
||||
root = Path(mount["Source"]).resolve()
|
||||
target = (root / path[len(dest) + 1:]).resolve()
|
||||
if root not in target.parents:
|
||||
raise RuntimeError("Certificate path escapes its bind mount")
|
||||
return target
|
||||
raise RuntimeError("Certificate/config must be stored in a persistent bind mount: " + path)
|
||||
|
||||
config = json.loads(host_path("/usr/local/etc/trojan/config.json").read_text())
|
||||
domain = config["ssl"]["sni"]
|
||||
if not domain or any(c not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-" for c in domain):
|
||||
raise RuntimeError("Invalid certificate domain")
|
||||
port = int(config["local_port"])
|
||||
acme_home = "/root/.acme.sh"
|
||||
source_cert = host_path(f"{acme_home}/{domain}_ecc/fullchain.cer")
|
||||
source_key = host_path(f"{acme_home}/{domain}_ecc/{domain}.key")
|
||||
target_cert = host_path(config["ssl"]["cert"])
|
||||
target_key = host_path(config["ssl"]["key"])
|
||||
|
||||
# Use the running TLS endpoint as the before-state: acme.sh may have already
|
||||
# replaced source files during an earlier, interrupted renewal attempt.
|
||||
def served_fingerprint(verify=False):
|
||||
context = ssl.create_default_context() if verify else ssl._create_unverified_context()
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=10) as sock:
|
||||
with context.wrap_socket(sock, server_hostname=domain) as tls:
|
||||
return hashlib.sha256(tls.getpeercert(binary_form=True)).hexdigest()
|
||||
|
||||
try:
|
||||
before = served_fingerprint()
|
||||
except (OSError, ssl.SSLError):
|
||||
before = None
|
||||
run(["docker", "exec", container, "systemctl", "start", "trojan-acme-challenge"])
|
||||
result = subprocess.run([
|
||||
"docker", "exec", container, acme_home + "/acme.sh", "--renew",
|
||||
"--home", acme_home, "-d", domain, "--ecc",
|
||||
"--webroot", "/var/lib/trojan-acme-webroot",
|
||||
], timeout=900)
|
||||
# acme.sh returns 2 when a certificate is not yet due for renewal.
|
||||
if result.returncode not in (0, 2):
|
||||
raise RuntimeError(f"acme.sh renewal failed: {result.returncode}")
|
||||
run(["openssl", "x509", "-in", str(source_cert), "-noout", "-checkend", "604800"])
|
||||
run(["openssl", "x509", "-in", str(source_cert), "-noout", "-checkhost", domain])
|
||||
cert_pub = run(["openssl", "x509", "-in", str(source_cert), "-pubkey", "-noout"], capture_output=True).stdout
|
||||
key_pub = run(["openssl", "pkey", "-in", str(source_key), "-pubout"], capture_output=True).stdout
|
||||
if cert_pub != key_pub:
|
||||
raise RuntimeError("Certificate and private key do not match")
|
||||
der = run(["openssl", "x509", "-in", str(source_cert), "-outform", "DER"], capture_output=True).stdout
|
||||
expected = hashlib.sha256(der).hexdigest()
|
||||
|
||||
def install(source, target, mode):
|
||||
if source == target:
|
||||
os.chmod(target, mode)
|
||||
return
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temp = tempfile.mkstemp(prefix=".renew-", dir=target.parent)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as output:
|
||||
os.fchmod(output.fileno(), mode)
|
||||
output.write(source.read_bytes())
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
os.replace(temp, target)
|
||||
finally:
|
||||
if os.path.exists(temp):
|
||||
os.unlink(temp)
|
||||
|
||||
install(source_key, target_key, 0o600)
|
||||
install(source_cert, target_cert, 0o644)
|
||||
if before != expected:
|
||||
run(["docker", "exec", container, "systemctl", "restart", "trojan"])
|
||||
print("Restarted Trojan to load renewed certificate", flush=True)
|
||||
for attempt in range(10):
|
||||
try:
|
||||
if served_fingerprint(verify=True) == expected:
|
||||
print(f"OK: {domain}, active certificate SHA256={expected}", flush=True)
|
||||
return
|
||||
except (OSError, ssl.SSLError):
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise RuntimeError("Running Trojan did not present the expected valid certificate")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Renew and verify Trojan certificate in Docker
|
||||
Requires=docker.service
|
||||
After=docker.service network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/python3 /usr/local/sbin/renew-trojan-certificate-host.py
|
||||
TimeoutStartSec=20min
|
||||
UMask=0077
|
||||
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=Check Trojan certificate renewal twice daily
|
||||
|
||||
[Timer]
|
||||
OnBootSec=5min
|
||||
OnCalendar=*-*-* 03,15:00:00
|
||||
RandomizedDelaySec=30min
|
||||
Persistent=true
|
||||
Unit=trojan-certificate-renew.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
Reference in New Issue
Block a user