部署Nginx反代与可信证书并补充远程验收和续期保护

This commit is contained in:
xuans committed 2026-09-17 23:01:35 +08:00
1 parent 6d26e24fec
commit 76e8835ca4
13 files changed
+570 -2

No files matched your search

+108
View File
@@ -0,0 +1,108 @@
"""证书更新脚本的隔离回归,不操作生产文件或服务。"""
import importlib.util
from pathlib import Path
import subprocess
import unittest
from unittest.mock import mock_open, patch
BASE = Path(__file__).resolve().parent
def load(name):
path = BASE / (name + '.py')
if not path.exists():
path = BASE.parents[1] / 'deploy/nginx' / (name + '.py')
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
renew = load('renew_certificate')
deploy = load('deploy_certificate')
class RenewalTests(unittest.TestCase):
def execute(self, callback):
with patch.object(renew.os, 'geteuid', return_value=0), \
patch('builtins.open', mock_open()), \
patch.object(renew.fcntl, 'flock'), \
patch.object(renew.subprocess, 'run', side_effect=callback):
renew.main()
def test_not_due_keeps_nginx_running(self):
calls = []
def run(command, **kwargs):
calls.append(command)
return subprocess.CompletedProcess(command, 0)
self.execute(run)
self.assertNotIn(['systemctl', 'stop', 'nginx'], calls)
self.assertIn(['/usr/local/libexec/smail-acme/deploy_certificate.py'], calls)
def test_due_failure_restores_nginx(self):
for failure in (subprocess.CalledProcessError(1, 'lego'),
subprocess.TimeoutExpired('lego', 150)):
with self.subTest(failure=type(failure).__name__):
calls = []
def run(command, **kwargs):
calls.append(command)
if '-checkend' in command:
return subprocess.CompletedProcess(command, 1)
if command[0].endswith('/lego'):
raise failure
return subprocess.CompletedProcess(command, 0)
with self.assertRaises(type(failure)):
self.execute(run)
self.assertEqual(calls[-1], ['systemctl', 'start', 'nginx'])
self.assertNotIn(['/usr/local/libexec/smail-acme/deploy_certificate.py'], calls)
def test_due_success_is_bounded_and_reuses_key(self):
calls = []
def run(command, **kwargs):
calls.append(command)
if '-checkend' in command:
return subprocess.CompletedProcess(command, 1)
if command[0].endswith('/lego'):
self.assertEqual(kwargs['timeout'], 150)
self.assertIn('--reuse-key', command)
self.assertIn('--no-random-sleep', command)
return subprocess.CompletedProcess(command, 0)
self.execute(run)
self.assertLess(calls.index(['systemctl', 'start', 'nginx']),
calls.index(['/usr/local/libexec/smail-acme/deploy_certificate.py']))
def test_non_root_is_rejected(self):
with patch.object(renew.os, 'geteuid', return_value=1000), \
self.assertRaises(RuntimeError):
renew.main()
def test_untrusted_certificate_never_replaces_files(self):
with patch.object(deploy.os, 'geteuid', return_value=0), \
patch.object(deploy, 'run', side_effect=subprocess.CalledProcessError(1, 'openssl')), \
patch.object(deploy, 'replace_file') as replace, \
self.assertRaises(subprocess.CalledProcessError):
deploy.main()
replace.assert_not_called()
def test_mismatched_private_key_never_replaces_files(self):
def run(*command, **kwargs):
return b'private-public-key' if command[1] == 'pkey' else b'certificate-public-key'
with patch.object(deploy.os, 'geteuid', return_value=0), \
patch.object(deploy, 'run', side_effect=run), \
patch.object(deploy, 'replace_file') as replace, \
self.assertRaisesRegex(RuntimeError, '不匹配'):
deploy.main()
replace.assert_not_called()
if __name__ == '__main__':
unittest.main(verbosity=2)
+88
View File
@@ -0,0 +1,88 @@
"""仅检查远程传输层,不登录、不发信、不读写业务数据库。"""
from datetime import datetime, timezone
import hashlib
import http.client
import json
from pathlib import Path
import smtplib
import socket
import ssl
import subprocess
HOST = 'mail.solit.cn'
CONTEXT = ssl.create_default_context()
def request(port, path='/', host=HOST, tls=True):
raw = socket.create_connection(('127.0.0.1', port), timeout=10)
stream = CONTEXT.wrap_socket(raw, server_hostname=host) if tls else raw
try:
stream.sendall(f'GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n'.encode())
response = http.client.HTTPResponse(stream)
response.begin()
body = response.read()
return response.status, dict(response.getheaders()), body
finally:
stream.close()
def main():
results = {'time': datetime.now(timezone.utc).isoformat(), 'checks': []}
leaf = subprocess.run(['openssl', 'x509', '-in', '/opt/smail/ssl/custom.crt', '-outform', 'DER'],
check=True, capture_output=True).stdout
expected = hashlib.sha256(leaf).hexdigest()
for port, host in [(443, HOST), (8002, HOST), (465, 'smtp.solit.cn'),
(993, 'imap.solit.cn'), (995, 'pop.solit.cn')]:
with socket.create_connection(('127.0.0.1', port), timeout=10) as raw:
with CONTEXT.wrap_socket(raw, server_hostname=host) as stream:
actual = hashlib.sha256(stream.getpeercert(binary_form=True)).hexdigest()
assert actual == expected, (port, 'certificate mismatch')
results['checks'].append({'port': port, 'hostname': host, 'tls': stream.version(),
'systemTrust': True, 'sameCertificate': True})
for port in (25, 587):
with smtplib.SMTP(timeout=10) as client:
assert client.connect('127.0.0.1', port)[0] == 220
client._host = 'smtp.solit.cn'
assert client.ehlo('localhost')[0] == 250
assert not client.has_extn('auth'), 'plaintext AUTH advertised'
assert client.has_extn('starttls')
assert client.starttls(context=CONTEXT)[0] == 220
assert hashlib.sha256(client.sock.getpeercert(binary_form=True)).hexdigest() == expected
assert client.ehlo('localhost')[0] == 250
results['checks'].append({'port': port, 'systemTrust': True, 'starttls': True,
'plaintextAuthHidden': True})
for port in (443, 8002):
status, headers, body = request(port)
assert status == 200 and b'<html' in body.lower(), (port, status)
assert 'Content-Security-Policy' in headers
results['checks'].append({'port': port, 'pageStatus': status, 'pageBytes': len(body)})
status, _, body = request(port, '/api/ping')
assert status == 200
for port in (80, 8001):
status, headers, _ = request(port, '/acceptance?x=1', tls=False)
assert status == 308
location = headers['Location']
if port == 80:
assert location == 'https://mail.solit.cn/acceptance?x=1'
results['checks'].append({'port': port, 'redirect': location})
assert request(80, host='untrusted.invalid', tls=False)[0] == 404
results['checks'].append({'unknownHttpHost': 'rejected'})
try:
with socket.create_connection(('127.0.0.1', 443), timeout=10) as raw:
CONTEXT.wrap_socket(raw, server_hostname='untrusted.invalid')
except ssl.SSLError:
results['checks'].append({'unknownSNI': 'rejected'})
else:
raise AssertionError('unknown SNI accepted')
root = json.loads(Path('/opt/smail/config/config.json').read_text())
assert root['http']['port'] == 8001 and root['http']['httpsPort'] == 8002
assert root['security']['webAuthnRpOrigins'] == ['https://mail.solit.cn']
results['fingerprintSHA256'] = expected
results['status'] = 'passed'
print(json.dumps(results, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()