fix: restore Trojan certificates and schedule host renewals

This commit is contained in:
chermack
2026-10-24 02:19:51 +08:00
parent 39255cc3dc
commit de8e02b33f
7 changed files with 330 additions and 21 deletions
+3 -1
View File
@@ -7,7 +7,9 @@ systemctl daemon-reload || true
systemctl start trojan
systemctl start trojan-web
systemctl start trojan-acme-challenge
systemctl enable trojan trojan-web trojan-acme-challenge trojan-acme-renew.timer || true
# systemctl.py does not run calendar timers; use the host renewal units shipped
# in trojan-stack/scripts rather than enabling an inert container timer.
systemctl enable trojan trojan-web trojan-acme-challenge || true
(
while sleep 300; do
/usr/local/sbin/rotate-trojan-log || true
+27 -16
View File
@@ -1,20 +1,31 @@
#!/bin/bash
set -euo pipefail
domain="${ACME_DOMAIN:?ACME_DOMAIN is required}"
home=/root/.acme.sh
cert_dir=/etc/trojan/certs
source_cert="$home/${domain}_ecc/fullchain.cer"
source_key="$home/${domain}_ecc/${domain}.key"
before=""
[[ -f "$cert_dir/fullchain.pem" ]] && before=$(openssl x509 -in "$cert_dir/fullchain.pem" -noout -fingerprint -sha256)
"$home/acme.sh" --cron --home "$home"
# For legacy/manual use. Docker scheduling is provided by the HOST systemd
# units in trojan-stack/scripts, not by the image's systemctl.py timer.
mapfile -t config < <(python -c 'import json; c=json.load(open("/usr/local/etc/trojan/config.json")); print(c["ssl"]["sni"]); print(c["ssl"]["cert"]); print(c["ssl"]["key"]); print(c["local_port"])')
[[ ${#config[@]} -eq 4 ]]
domain="${config[0]}"
acme_home=/root/.acme.sh
target_cert="${config[1]}"
target_key="${config[2]}"
source_cert="$acme_home/${domain}_ecc/fullchain.cer"
source_key="$acme_home/${domain}_ecc/${domain}.key"
before=$(timeout 10 openssl s_client -connect "127.0.0.1:${config[3]}" -servername "$domain" </dev/null 2>/dev/null | openssl x509 -noout -fingerprint -sha256) || before=""
result=0
"$acme_home/acme.sh" --renew --home "$acme_home" -d "$domain" --ecc \
--webroot "${ACME_WEBROOT:-/var/lib/trojan-acme-webroot}" || result=$?
[[ $result -eq 0 || $result -eq 2 ]]
test -r "$source_cert" -a -r "$source_key"
openssl x509 -in "$source_cert" -noout -checkend 0
mkdir -p "$cert_dir"
install -m 0644 "$source_cert" "$cert_dir/fullchain.pem"
install -m 0600 "$source_key" "$cert_dir/private.key"
openssl x509 -noout -modulus -in "$cert_dir/fullchain.pem" | openssl sha256 > /tmp/trojan-cert.modulus
openssl rsa -noout -modulus -in "$cert_dir/private.key" | openssl sha256 >> /tmp/trojan-cert.modulus
[[ $(cut -d' ' -f2 /tmp/trojan-cert.modulus | sort -u | wc -l) -eq 1 ]]
after=$(openssl x509 -in "$cert_dir/fullchain.pem" -noout -fingerprint -sha256)
openssl x509 -in "$source_cert" -noout -checkend 604800
cert_pub=$(openssl x509 -pubkey -noout -in "$source_cert" | openssl sha256)
key_pub=$(openssl pkey -pubout -in "$source_key" | openssl sha256)
[[ "$cert_pub" == "$key_pub" ]]
mkdir -p "$(dirname "$target_cert")" "$(dirname "$target_key")"
if [[ "$(readlink -f "$source_key")" != "$(readlink -f "$target_key")" ]]; then
install -m 0600 "$source_key" "$target_key"
fi
if [[ "$(readlink -f "$source_cert")" != "$(readlink -f "$target_cert")" ]]; then
install -m 0644 "$source_cert" "$target_cert"
fi
after=$(openssl x509 -in "$target_cert" -noout -fingerprint -sha256)
if [[ "$before" != "$after" ]]; then systemctl restart trojan; fi
+36
View File
@@ -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
+124 -4
View File
@@ -156,16 +156,16 @@ ss -ltnp | grep sshd
## 8. Trojan 证书续期
Trojan 的 `www.*` 证书仍由容器内 `acme.sh` 管理;Caddy 只管理 `git.*`。由于宿主机 80 已交给 Nginx,Trojan standalone 验证改用本地 8082:
Trojan 的 `www.*` 证书由容器内 `acme.sh` 管理;Caddy 管理 `git.*` 和后续增加的 `minio.*`。2026-10-24 已修正续期:宿主机真实 systemd 调度,使用现有 8082 文件服务完成 webroot 验证。原 standalone 方案与该常驻服务冲突,已废弃。完整过程见第 16 节。
```bash
docker exec trojan /root/.acme.sh/acme.sh --issue \
--server letsencrypt --standalone --httpport 8082 \
-d www.hk.chermack.top --ecc --force
--server letsencrypt --webroot /var/lib/trojan-acme-webroot \
-d www.hk.chermack.top --keylength ec-256
docker exec trojan systemctl restart trojan
```
美国服务器替换为 `www.us.chermack.top`。本次两张 Trojan 证书均已成功签发,有效期为 2026-07-25 至 2026-10-23。后续应确认容器内自动续期任务也携带 `--httpport 8082`。
美国服务器替换为 `www.us.chermack.top`。上面的 `--issue` 用于初次签发或迁移验证方式;常规检查使用宿主机 `trojan-certificate-renew.service` 调用 `--renew --ecc --webroot`,按 acme.sh 的续期时间执行,避免频繁强制签发。不要依赖容器内的 `.timer` 或未运行的 cron。
## 9. 重启后不可用:原因与永久修复
@@ -316,3 +316,123 @@ docker exec trojan /usr/local/bin/trojan web \
1. 两台服务器的 `trojan-mariadb` 仍将 `3306` 映射到公网;为避免额外中断,迁移中未改动。确认无外部依赖后,应限制为 `127.0.0.1:3306` 或移除映射。
2. `www.*` 与 `git.*` 使用不同的证书管理者:前者为 Trojan 容器内 acme.sh,后者为 Caddy。
3. 两台服务器均已部署 `trojan-container-services.service`。重启服务器后,优先检查该服务及容器内两个 Trojan 服务状态。
## 16. 香港证书过期恢复与两节点自动续期修复(2026-10-24)
本节时间除标注 UTC 外均为北京时间。操作范围为香港 `43.154.35.111` 和美国 `43.159.139.193` 的 Trojan 证书与调度;未调整用户、数据库、业务域名、端口或代理分流架构。
### 16.1 现场证据与原因
香港 `www.hk.chermack.top` 旧证书于 **2026-10-23 23:56:30** 到期。美国 `www.us.chermack.top` 旧证书原定 **2026-10-24 04:45:53** 到期,检查时尚有约三小时,因此同批提前恢复。两台的源证书和运行中证书均仍为 7 月签发;acme.sh 记录的续期时间分别为 9 月 22 日和 9 月 24 日,未成功执行。
两节点问题相同:
1. `trojan-manager-compat:2.0.3-hk/us` 使用 `systemctl.py`,PID 1 实际为 `tail`,容器内没有真实 systemd 定时调度。`trojan-acme-renew.timer` 虽 enabled,但状态为 dead;旧 acme.sh crontab 存在,cron 守护进程未运行。
2. 域名配置仍是 `Le_Webroot='no'` 的 standalone 验证。8082 已由 `trojan acme-http` 常驻服务监听,不能再启动 standalone 监听同一端口。
3. 旧脚本用 `openssl rsa -modulus` 校验 ECC 私钥,并将证书复制到 `/etc/trojan/certs/`;实际 Trojan 配置直接读取 `/root/.acme.sh/<域名>_ecc/fullchain.cer` 和对应私钥。
Git 与 MinIO 的 Caddy 续期正常,检查时证书已更新至 12 月到期。本次不调整 Caddy。
### 16.2 备份与紧急恢复
操作前以 root 专用目录(0700)备份完整 ACME 状态、原 Trojan 配置及旧维护脚本:
```text
香港:/opt/trojan/backups/certificate-renewal-20261023T175520Z
美国:/opt/trojan/backups/certificate-renewal-20261023T175606Z
acme-before.tar.gz # 包含账户与私钥,不得上传到 Git 或公开分享
config-before.json
renew-before
compat-init-before
crontab-before.txt
```
确认 Nginx 的 `/.well-known/acme-challenge/` 指向 `127.0.0.1:8082`,并在 `/var/lib/trojan-acme-webroot/.well-known/acme-challenge/` 写入临时验证文件,经域名 HTTP 访问成功;测试文件已删除。
随后分别执行(美国替换域名):
```bash
docker exec trojan /root/.acme.sh/acme.sh --issue \
--home /root/.acme.sh --server letsencrypt \
-d www.hk.chermack.top \
--webroot /var/lib/trojan-acme-webroot --keylength ec-256
docker exec trojan systemctl restart trojan
```
两次 HTTP-01 验证与签发均成功,配置已保存 `Le_Webroot='/var/lib/trojan-acme-webroot'`。仅重启 Trojan 核心加载证书,现有连接可能短暂重连;没有重启整个 Docker 容器、管理后台或数据库。
| 节点 | 新证书到期时间(北京时间) | 新证书序列号 |
| --- | --- | --- |
| 香港 | 2027-01-22 00:57:01 | `051911FACC1E378D646BE88B9CDD34A1F19E` |
| 美国 | 2027-01-22 00:57:47 | `06ECC2E3EBF581485D09EE5BEFB941C1FF72` |
### 16.3 自动续期的持久化部署
仓库新增文件及宿主机安装位置:
| 仓库文件(`trojan-stack/scripts/` 下) | 两台宿主机安装位置 |
| --- | --- |
| `renew-certificate-host.py` | `/usr/local/sbin/renew-trojan-certificate-host.py` |
| `trojan-certificate-renew.service` | `/etc/systemd/system/trojan-certificate-renew.service` |
| `trojan-certificate-renew.timer` | `/etc/systemd/system/trojan-certificate-renew.timer` |
部署副本保留在 `/opt/trojan/renewal-tools/`。依赖宿主机已有的 Python 3、OpenSSL、Docker CLI 和真实 systemd,没有增加容器或替换镜像。
脚本从容器绑定目录映射和实际 `config.json` 读取域名、证书路径及 TLS 端口;文件锁防止并发,单次最长受 service 的 20 分钟超时约束。检查流程为:
1. 读取正在运行的 TLS 证书指纹,启动/确认现有 ACME 文件服务。
2. 执行 `acme.sh --renew --ecc --webroot /var/lib/trojan-acme-webroot`;未到续期时间的返回码 2 按正常跳过处理。
3. 检查证书至少还有七天有效期、域名和证书/私钥公钥匹配,兼容 ECC 校验。
4. 若需要部署,写入配置实际引用的持久化路径;私钥权限设为 0600。
5. 运行中证书与源文件指纹不同时才重启核心,并验证实际 TLS 信任链、域名与指纹;失败返回非零,写入 journal。
定时器在**宿主机时区**每日 03:00、15:00 加 0–30 分钟随机延迟检查;开机五分钟后也检查,并通过 `Persistent=true` 补执行错过的日历任务。两台当前宿主机时区均为 CST(UTC+8)。启用命令:
```bash
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
```
已禁用旧容器 timer,并备份后移除旧 acme.sh cron 行,保留其他 cron 内容。`systemctl.py` 不支持停止 timer,但它原本没有活动调度进程;已确认旧 timer 为 disabled。仓库和运行容器中的 `compat-init` 已去掉对旧 timer 的启用,旧 `renew-trojan-certificate` 维护脚本也已修正为 webroot、通用公钥匹配和实际配置路径。
宿主机单元不随容器重启消失;将来重建容器仍需保留现有 bind mount、8082 ACME 服务和 Nginx 验证路由,并使用包含修正脚本的新镜像或重新同步维护脚本。现有镜像标签未重新构建。
### 16.4 验证结果与运维
- 两机真实宿主机 timer 均为 `enabled`、`active (waiting)`;service 首次执行均为 `Result=success`、`ExecMainStatus=0`。
- 实际签发完成后再次由 service 检查,均正常跳过未到期续签,TLS 指纹检查成功,没有重复重启核心。
- 本机经公网访问两个 `www.*`:均 HTTP 200、TLS 校验为 0;服务器经 Nginx 443/SNI 路由回归检查也均通过。
- 两个 Git 域名均为 HTTP 200;MinIO 匿名 S3 根路径为预期 403、TLS 校验为 0;相关容器仍健康。
- 验证覆盖 HTTP-01 真正签发、实际证书加载、调度执行及 HTTPS 路由;未使用用户代理凭据进行完整 Trojan 隧道流量测试,未为验证而重启整台服务器。
日常检查:
```bash
systemctl list-timers --all trojan-certificate-renew.timer
systemctl show trojan-certificate-renew.service -p Result -p ExecMainStatus
journalctl -u trojan-certificate-renew.service --since '7 days ago' --no-pager
systemctl start trojan-certificate-renew.service
# 美国将域名替换为 www.us.chermack.top
openssl s_client -connect 127.0.0.1:443 -servername www.hk.chermack.top \
</dev/null 2>/dev/null | openssl x509 -noout -dates -serial
```
当前已提供失败退出状态和持久日志,尚未配置邮件或聊天通知。acme.sh 当前下次续期计划为香港 `2026-12-21T17:55:35Z`、美国 `2026-12-23T07:28:12Z`,之后由各自 ACME 客户端按 CA 建议更新。
### 16.5 回滚与故障恢复
若新调度脚本出现问题,先暂停宿主机 timer,保留已经恢复的新证书:
```bash
systemctl disable --now trojan-certificate-renew.timer
journalctl -u trojan-certificate-renew.service -n 100 --no-pager
```
修正脚本后重新安装并执行 `systemctl start trojan-certificate-renew.service`,验证成功再 `systemctl enable --now trojan-certificate-renew.timer`。暂停期间没有自动续期,应及时恢复。
原脚本、cron、配置和 ACME 状态均可在上述备份目录取回;**不要直接恢复旧 ACME 压缩包中的过期证书到生产路径**。恢复旧配置前应先核对证书路径和有效期。本次业务配置与数据未改变,不需要回滚数据库、Nginx 或 Caddy。