This commit is contained in:
1 parent
600623683c
commit
46a767c8d9
13 files changed
+570
-2
No files matched your search
@@ -0,0 +1 @@
|
||||
* text eol=lf
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/python3
|
||||
"""校验证书并同步至 Smail,私钥与回退副本仅在服务器保存。"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import pwd
|
||||
import shutil
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
|
||||
DOMAINS = ('solit.cn', 'mail.solit.cn', 'smtp.solit.cn', 'imap.solit.cn', 'pop.solit.cn')
|
||||
LINEAGE = Path('/var/lib/smail-acme-tls/certificates')
|
||||
TARGET = Path('/opt/smail/ssl')
|
||||
|
||||
|
||||
def run(*args, **kwargs):
|
||||
return subprocess.run(args, check=True, capture_output=True, **kwargs).stdout
|
||||
|
||||
|
||||
def replace_file(path, data, uid, gid):
|
||||
staged = path.with_name(path.name + '.new-' + uuid.uuid4().hex)
|
||||
fd = os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
os.fchown(stream.fileno(), uid, gid)
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(staged, path)
|
||||
fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def main():
|
||||
if os.geteuid() != 0:
|
||||
raise RuntimeError('必须使用 root 执行证书同步')
|
||||
# 先验证信任链、服务域名、有效期和密钥匹配,再修改运行文件。
|
||||
for domain in DOMAINS:
|
||||
run('openssl', 'verify', '-CAfile', '/etc/ssl/certs/ca-certificates.crt',
|
||||
'-untrusted', str(LINEAGE / 'solit.cn.issuer.crt'), '-verify_hostname', domain,
|
||||
str(LINEAGE / 'solit.cn.crt'))
|
||||
run('openssl', 'x509', '-in', str(LINEAGE / 'solit.cn.crt'), '-checkend', '604800', '-noout')
|
||||
public_cert = run('openssl', 'x509', '-in', str(LINEAGE / 'solit.cn.crt'), '-pubkey', '-noout')
|
||||
public_key = run('openssl', 'pkey', '-in', str(LINEAGE / 'solit.cn.key'), '-pubout')
|
||||
if public_cert != public_key:
|
||||
raise RuntimeError('证书与私钥不匹配')
|
||||
if TARGET.is_symlink() or TARGET.resolve() != TARGET:
|
||||
raise RuntimeError('证书目标目录不能包含符号链接')
|
||||
pairs = [('solit.cn.key', 'custom.key'), ('solit.cn.crt', 'custom.crt')]
|
||||
for _, name in pairs:
|
||||
path = TARGET / name
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_nlink != 1:
|
||||
raise RuntimeError('现有证书文件类型不符合要求')
|
||||
if all((LINEAGE / source).read_bytes() == (TARGET / name).read_bytes() for source, name in pairs):
|
||||
print('证书校验通过,运行文件已同步')
|
||||
return
|
||||
identity = pwd.getpwnam('smail')
|
||||
stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S') + '-' + uuid.uuid4().hex[:8]
|
||||
backup = Path('/var/backups') / ('smail-certificate-' + stamp)
|
||||
backup.mkdir(mode=0o700)
|
||||
for _, name in pairs:
|
||||
path = TARGET / name
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise RuntimeError('现有证书文件类型不符合要求')
|
||||
shutil.copy2(path, backup / name)
|
||||
os.chmod(backup / name, 0o600)
|
||||
try:
|
||||
for source, name in pairs:
|
||||
replace_file(TARGET / name, (LINEAGE / source).read_bytes(), identity.pw_uid, identity.pw_gid)
|
||||
run('nginx', '-t')
|
||||
run('systemctl', 'reload', 'nginx')
|
||||
except Exception:
|
||||
for _, name in pairs:
|
||||
replace_file(TARGET / name, (backup / name).read_bytes(), identity.pw_uid, identity.pw_gid)
|
||||
raise
|
||||
fingerprint = hashlib.sha256(run('openssl', 'x509', '-in', str(TARGET / 'custom.crt'), '-outform', 'DER')).hexdigest()
|
||||
print('证书已同步,SHA256=' + fingerprint)
|
||||
print('回退副本=' + str(backup))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,26 @@
|
||||
user www-data;
|
||||
worker_processes 1;
|
||||
pid /run/nginx.pid;
|
||||
error_log /var/log/nginx/error.log warn;
|
||||
include /etc/nginx/modules-enabled/*.conf;
|
||||
|
||||
events {
|
||||
worker_connections 512;
|
||||
}
|
||||
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
server_tokens off;
|
||||
sendfile on;
|
||||
keepalive_timeout 30;
|
||||
client_header_timeout 10s;
|
||||
client_body_timeout 90s;
|
||||
client_max_body_size 64m;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_session_cache shared:SSL:2m;
|
||||
ssl_session_timeout 1d;
|
||||
ssl_session_tickets off;
|
||||
access_log /var/log/nginx/access.log combined;
|
||||
include /etc/nginx/conf.d/*.conf;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/python3
|
||||
"""仅在临近到期时占用 443 续期,任何正常异常路径均恢复 Nginx。"""
|
||||
|
||||
import fcntl
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
|
||||
ROOT = Path('/var/lib/smail-acme-tls')
|
||||
DOMAINS = ('solit.cn', 'mail.solit.cn', 'smtp.solit.cn', 'imap.solit.cn', 'pop.solit.cn')
|
||||
|
||||
|
||||
def main():
|
||||
if os.geteuid() != 0:
|
||||
raise RuntimeError('必须使用 root 执行证书续期')
|
||||
with open('/run/smail-certificate-renew.lock', 'a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
certificate = str(ROOT / 'certificates/solit.cn.crt')
|
||||
subprocess.run(['openssl', 'x509', '-in', certificate, '-noout'], check=True)
|
||||
due = subprocess.run(['openssl', 'x509', '-in', certificate, '-noout', '-checkend', '2592000'],
|
||||
capture_output=True).returncode != 0
|
||||
if due:
|
||||
subprocess.run(['nginx', '-t'], check=True)
|
||||
subprocess.run(['systemctl', 'is-active', '--quiet', 'nginx'], check=True)
|
||||
command = ['/usr/local/libexec/smail-acme/lego', '--path', str(ROOT),
|
||||
'--email', '', '--accept-tos', '--key-type', 'rsa2048', '--tls',
|
||||
'--http-timeout', '20', '--cert.timeout', '30']
|
||||
for domain in DOMAINS:
|
||||
command.extend(['--domains', domain])
|
||||
command.extend(['renew', '--days', '30', '--reuse-key', '--no-random-sleep'])
|
||||
# systemd 的 ExecStopPost 另行覆盖进程被终止时的服务恢复。
|
||||
try:
|
||||
subprocess.run(['systemctl', 'stop', 'nginx'], check=True)
|
||||
subprocess.run(command, check=True, timeout=150,
|
||||
env={**os.environ, 'GOMEMLIMIT': '64MiB'})
|
||||
finally:
|
||||
subprocess.run(['systemctl', 'start', 'nginx'], check=True)
|
||||
else:
|
||||
print('证书有效期大于 30 天,本次不暂停 Web 服务')
|
||||
subprocess.run(['/usr/local/libexec/smail-acme/deploy_certificate.py'], check=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,20 @@
|
||||
[Unit]
|
||||
Description=Smail certificate renewal
|
||||
After=network-online.target nginx.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/libexec/smail-acme/renew_certificate.py
|
||||
ExecStopPost=/usr/bin/systemctl start nginx.service
|
||||
TimeoutStartSec=240
|
||||
MemoryHigh=96M
|
||||
MemoryMax=128M
|
||||
MemorySwapMax=0
|
||||
CPUQuota=100%
|
||||
TasksMax=64
|
||||
Environment=GOMEMLIMIT=64MiB
|
||||
UMask=0077
|
||||
PrivateTmp=true
|
||||
ProtectHome=true
|
||||
NoNewPrivileges=true
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Smail daily certificate expiry check
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 04:00:00
|
||||
RandomizedDelaySec=30m
|
||||
Persistent=true
|
||||
Unit=smail-certificate-renew.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,64 @@
|
||||
server {
|
||||
listen 80 default_server;
|
||||
listen [::]:80 default_server;
|
||||
server_name _;
|
||||
return 404;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name solit.cn mail.solit.cn smtp.solit.cn imap.solit.cn pop.solit.cn;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /var/lib/smail-acme;
|
||||
default_type text/plain;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 308 https://mail.solit.cn$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl default_server;
|
||||
listen [::]:443 ssl default_server;
|
||||
server_name _;
|
||||
ssl_reject_handshake on;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
listen [::]:443 ssl;
|
||||
server_name solit.cn smtp.solit.cn imap.solit.cn pop.solit.cn;
|
||||
ssl_certificate /var/lib/smail-acme-tls/certificates/solit.cn.crt;
|
||||
ssl_certificate_key /var/lib/smail-acme-tls/certificates/solit.cn.key;
|
||||
return 308 https://mail.solit.cn$request_uri;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
listen [::]:443 ssl;
|
||||
server_name mail.solit.cn;
|
||||
ssl_certificate /var/lib/smail-acme-tls/certificates/solit.cn.crt;
|
||||
ssl_certificate_key /var/lib/smail-acme-tls/certificates/solit.cn.key;
|
||||
|
||||
location / {
|
||||
proxy_pass https://127.0.0.1:8002;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header Connection "";
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name mail.solit.cn;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_verify_depth 3;
|
||||
proxy_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
|
||||
proxy_connect_timeout 5s;
|
||||
proxy_read_timeout 90s;
|
||||
proxy_send_timeout 90s;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user