norain 0.2.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- norain/__init__.py +3 -0
- norain/__main__.py +5 -0
- norain/block.py +281 -0
- norain/boot.py +142 -0
- norain/cli.py +748 -0
- norain/control.py +703 -0
- norain/defaults.py +42 -0
- norain/generate.py +264 -0
- norain/install.py +312 -0
- norain/maintain.py +313 -0
- norain/model.py +409 -0
- norain/monitor.py +314 -0
- norain/paths.py +124 -0
- norain/probe.py +158 -0
- norain/proxy.py +136 -0
- norain/repair.py +278 -0
- norain/routing.py +332 -0
- norain/rules.py +214 -0
- norain/runner.py +59 -0
- norain-0.2.0.dev0.dist-info/METADATA +99 -0
- norain-0.2.0.dev0.dist-info/RECORD +53 -0
- norain-0.2.0.dev0.dist-info/WHEEL +5 -0
- norain-0.2.0.dev0.dist-info/entry_points.txt +3 -0
- norain-0.2.0.dev0.dist-info/licenses/LICENSE +21 -0
- norain-0.2.0.dev0.dist-info/top_level.txt +3 -0
- norain_core/__init__.py +4 -0
- norain_core/apply.py +70 -0
- norain_core/atomic.py +80 -0
- norain_core/cliutil.py +68 -0
- norain_core/daemonctl.py +192 -0
- norain_core/errors.py +60 -0
- norain_core/fetch.py +158 -0
- norain_core/log.py +104 -0
- norain_core/migrate.py +86 -0
- norain_core/osutil.py +332 -0
- norain_core/redact.py +60 -0
- norain_core/secrets.py +87 -0
- norain_core/singbox.py +93 -0
- norain_core/state.py +97 -0
- norain_core/supervisor.py +352 -0
- norain_core/sysproxy.py +112 -0
- norain_core/tomlio.py +86 -0
- norain_server/__init__.py +3 -0
- norain_server/__main__.py +5 -0
- norain_server/cert.py +276 -0
- norain_server/cli.py +477 -0
- norain_server/deploy.py +604 -0
- norain_server/firewall.py +226 -0
- norain_server/generate.py +112 -0
- norain_server/model.py +272 -0
- norain_server/paths.py +101 -0
- norain_server/runner.py +123 -0
- norain_server/service.py +83 -0
norain_core/sysproxy.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Windows 系统代理(WinINET)的注册表快照与还原。
|
|
2
|
+
|
|
3
|
+
sing-box 的 inbound 支持 `set_system_proxy`,但它自己管不好这件事(2026-11-15 用
|
|
4
|
+
sing-box 1.14.4 实测):
|
|
5
|
+
|
|
6
|
+
* 运行期写 `ProxyEnable=1`、`ProxyServer="http://127.0.0.1:<port>"`;
|
|
7
|
+
* 被**硬终止**(Windows 上是 TerminateProcess,norain 停子进程就用 `terminate()`)时
|
|
8
|
+
什么都不还原——系统代理留在死端口,整机浏览器随即断网;
|
|
9
|
+
* 正常退出(Ctrl+Break)也只把 `ProxyEnable` 置 0,**不回填原来的 `ProxyServer`**。
|
|
10
|
+
|
|
11
|
+
所以客户端在启动 sing-box 之前自己快照注册表,停止之后再原样写回。快照落盘
|
|
12
|
+
(`paths.sysproxy_state`),进程被强杀后下次启动会先还原它,避免残留。
|
|
13
|
+
|
|
14
|
+
测试里 `NORAIN_NO_SYSTEM_CHANGES=1` 会让 `supported()` 返回 False,本模块整体变成空操作;
|
|
15
|
+
需要断言逻辑的用例用 monkeypatch 替换 `read`/`write`/`notify`。
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
from . import osutil
|
|
24
|
+
|
|
25
|
+
KEY = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings"
|
|
26
|
+
FIELDS = ("ProxyEnable", "ProxyServer", "ProxyOverride", "AutoConfigURL")
|
|
27
|
+
# INTERNET_OPTION_SETTINGS_CHANGED = 39, INTERNET_OPTION_REFRESH = 37
|
|
28
|
+
_REFRESH_OPTIONS = (39, 37)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def supported() -> bool:
|
|
32
|
+
"""只有 Windows 且允许改系统设置时才生效。"""
|
|
33
|
+
return osutil.IS_WINDOWS and not osutil.system_changes_disabled()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def read() -> dict | None:
|
|
37
|
+
"""当前注册表值。缺失的值记为 None;不在 Windows 或禁止改动时返回 None。"""
|
|
38
|
+
if not supported():
|
|
39
|
+
return None
|
|
40
|
+
import winreg
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, KEY) as k:
|
|
44
|
+
values: dict = {}
|
|
45
|
+
for name in FIELDS:
|
|
46
|
+
try:
|
|
47
|
+
values[name] = winreg.QueryValueEx(k, name)[0]
|
|
48
|
+
except OSError:
|
|
49
|
+
values[name] = None
|
|
50
|
+
return values
|
|
51
|
+
except OSError:
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def notify() -> None:
|
|
56
|
+
"""告诉正在运行的程序重新读取代理设置。失败不影响主流程。"""
|
|
57
|
+
if not osutil.IS_WINDOWS or osutil.system_changes_disabled():
|
|
58
|
+
return
|
|
59
|
+
try:
|
|
60
|
+
import ctypes
|
|
61
|
+
|
|
62
|
+
wininet = ctypes.windll.wininet
|
|
63
|
+
for option in _REFRESH_OPTIONS:
|
|
64
|
+
wininet.InternetSetOptionW(0, option, 0, 0)
|
|
65
|
+
except Exception: # noqa: BLE001 通知失败不能让停止流程失败
|
|
66
|
+
pass
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def write(values: dict) -> bool:
|
|
70
|
+
"""把快照写回注册表。值为 None 的项删除(例如原本没有 AutoConfigURL)。"""
|
|
71
|
+
if not supported():
|
|
72
|
+
return False
|
|
73
|
+
import winreg
|
|
74
|
+
|
|
75
|
+
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, KEY, 0, winreg.KEY_SET_VALUE) as k:
|
|
76
|
+
for name in FIELDS:
|
|
77
|
+
if name not in values:
|
|
78
|
+
continue
|
|
79
|
+
value = values[name]
|
|
80
|
+
if value is None:
|
|
81
|
+
try:
|
|
82
|
+
winreg.DeleteValue(k, name)
|
|
83
|
+
except OSError:
|
|
84
|
+
pass
|
|
85
|
+
elif name == "ProxyEnable":
|
|
86
|
+
winreg.SetValueEx(k, name, 0, winreg.REG_DWORD, int(value))
|
|
87
|
+
else:
|
|
88
|
+
winreg.SetValueEx(k, name, 0, winreg.REG_SZ, str(value))
|
|
89
|
+
notify()
|
|
90
|
+
return True
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def save(path: Path, values: dict) -> None:
|
|
94
|
+
from .state import write_json
|
|
95
|
+
|
|
96
|
+
write_json(path, {"saved_at": __import__("time").time(), "values": values})
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def load(path: Path) -> dict | None:
|
|
100
|
+
try:
|
|
101
|
+
obj = json.loads(path.read_text(encoding="utf-8"))
|
|
102
|
+
except (OSError, ValueError):
|
|
103
|
+
return None
|
|
104
|
+
values = obj.get("values") if isinstance(obj, dict) else None
|
|
105
|
+
return values if isinstance(values, dict) else None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def discard(path: Path) -> None:
|
|
109
|
+
try:
|
|
110
|
+
path.unlink(missing_ok=True)
|
|
111
|
+
except OSError:
|
|
112
|
+
pass
|
norain_core/tomlio.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""最小的 TOML 写出器(标准库只有读取)。只支持 Norain 配置用到的类型:
|
|
2
|
+
字符串、整数、浮点数、布尔、标量列表、表、表数组。注释不会保留,改写前调用方要先备份。"""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
_BARE = re.compile(r"^[A-Za-z0-9_-]+$")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _key(k: str) -> str:
|
|
13
|
+
return k if _BARE.match(k) else json.dumps(k, ensure_ascii=False)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _scalar(v) -> str:
|
|
17
|
+
if isinstance(v, bool):
|
|
18
|
+
return "true" if v else "false"
|
|
19
|
+
if isinstance(v, int):
|
|
20
|
+
return str(v)
|
|
21
|
+
if isinstance(v, float):
|
|
22
|
+
return repr(v)
|
|
23
|
+
if isinstance(v, str):
|
|
24
|
+
return json.dumps(v, ensure_ascii=False) # JSON 字符串转义是 TOML 基本字符串的子集
|
|
25
|
+
if isinstance(v, (list, tuple)):
|
|
26
|
+
return "[" + ", ".join(_scalar(x) for x in v) + "]"
|
|
27
|
+
if isinstance(v, dict):
|
|
28
|
+
return "{ " + ", ".join(f"{_key(k)} = {_scalar(x)}" for k, x in v.items()) + " }"
|
|
29
|
+
raise TypeError(f"TOML 不支持的类型:{type(v).__name__}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _is_table_array(v) -> bool:
|
|
33
|
+
return isinstance(v, list) and bool(v) and all(isinstance(x, dict) for x in v)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _emit(table: dict, prefix: str, out: list[str]) -> None:
|
|
37
|
+
for k, v in table.items():
|
|
38
|
+
if v is None or isinstance(v, dict) or _is_table_array(v):
|
|
39
|
+
continue
|
|
40
|
+
out.append(f"{_key(k)} = {_scalar(v)}")
|
|
41
|
+
for k, v in table.items():
|
|
42
|
+
name = f"{prefix}.{_key(k)}" if prefix else _key(k)
|
|
43
|
+
if isinstance(v, dict):
|
|
44
|
+
out.append("")
|
|
45
|
+
out.append(f"[{name}]")
|
|
46
|
+
_emit(v, name, out)
|
|
47
|
+
elif _is_table_array(v):
|
|
48
|
+
for item in v:
|
|
49
|
+
out.append("")
|
|
50
|
+
out.append(f"[[{name}]]")
|
|
51
|
+
_emit(item, name, out)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def dumps(doc: dict) -> str:
|
|
55
|
+
out: list[str] = []
|
|
56
|
+
_emit(doc, "", out)
|
|
57
|
+
return "\n".join(out).strip("\n") + "\n"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def parse_value(text: str):
|
|
61
|
+
"""把命令行上的值按 TOML 字面量解析;不是合法字面量时当作字符串。"""
|
|
62
|
+
import tomllib
|
|
63
|
+
try:
|
|
64
|
+
return tomllib.loads(f"v = {text}")["v"]
|
|
65
|
+
except tomllib.TOMLDecodeError:
|
|
66
|
+
return text
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def set_path(doc: dict, dotted: str, value) -> None:
|
|
70
|
+
keys = dotted.split(".")
|
|
71
|
+
node = doc
|
|
72
|
+
for k in keys[:-1]:
|
|
73
|
+
nxt = node.setdefault(k, {})
|
|
74
|
+
if not isinstance(nxt, dict):
|
|
75
|
+
raise KeyError(dotted)
|
|
76
|
+
node = nxt
|
|
77
|
+
node[keys[-1]] = value
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def get_path(doc: dict, dotted: str, default=None):
|
|
81
|
+
node = doc
|
|
82
|
+
for k in dotted.split("."):
|
|
83
|
+
if not isinstance(node, dict) or k not in node:
|
|
84
|
+
return default
|
|
85
|
+
node = node[k]
|
|
86
|
+
return node
|
norain_server/cert.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""证书检查和自签证书生成。规则见 docs/decisions/0015。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime as dt
|
|
6
|
+
import ipaddress
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from cryptography import x509
|
|
14
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
15
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
16
|
+
from cryptography.x509.oid import NameOID
|
|
17
|
+
|
|
18
|
+
from norain_core.errors import BIZ_CERT, EXIT_CONFIG, EXIT_CONFLICT, FieldError, NorainError
|
|
19
|
+
|
|
20
|
+
WARN_DAYS = 14
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class CertStatus:
|
|
25
|
+
certificate: str
|
|
26
|
+
private_key: str
|
|
27
|
+
errors: list[str] = field(default_factory=list)
|
|
28
|
+
warnings: list[str] = field(default_factory=list)
|
|
29
|
+
not_after: str | None = None
|
|
30
|
+
days_left: int | None = None
|
|
31
|
+
fingerprint_sha256: str | None = None
|
|
32
|
+
self_signed: bool | None = None
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def ok(self) -> bool:
|
|
36
|
+
return not self.errors
|
|
37
|
+
|
|
38
|
+
def as_dict(self) -> dict:
|
|
39
|
+
return {"ok": self.ok, **self.__dict__}
|
|
40
|
+
|
|
41
|
+
def raise_if_invalid(self, *, message: str = "证书无效", hint: str = "") -> None:
|
|
42
|
+
if self.errors:
|
|
43
|
+
raise NorainError(
|
|
44
|
+
message, exit_code=EXIT_CONFIG, business_code=BIZ_CERT, module="cert",
|
|
45
|
+
field_errors=[FieldError("tls", e) for e in self.errors],
|
|
46
|
+
hint=hint or "manual 模式检查证书路径;自用可运行 cert self-signed --domain <域名>")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def raise_for_mode(mode: str, status: CertStatus) -> None:
|
|
50
|
+
"""按证书模式抛出「无效」错误。
|
|
51
|
+
|
|
52
|
+
acme 的失败多是环境前置条件(域名、80/tcp、构建标签),不能沿用 manual 模式
|
|
53
|
+
的「检查证书路径 / 生成自签证书」提示;报错文案也要区分开,否则调用方拿着
|
|
54
|
+
BIZ_CERT 去看一个根本不存在的证书文件。
|
|
55
|
+
"""
|
|
56
|
+
if mode == "acme":
|
|
57
|
+
status.raise_if_invalid(
|
|
58
|
+
message="ACME 前置条件不满足",
|
|
59
|
+
hint="检查域名解析、80/tcp 是否可用、sing-box 是否带 with_acme 构建标签;"
|
|
60
|
+
"启用 Trojan 且监听 443/tcp 可改用 TLS-ALPN-01")
|
|
61
|
+
else:
|
|
62
|
+
status.raise_if_invalid()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _matches(domain: str, cert: x509.Certificate) -> bool:
|
|
66
|
+
try:
|
|
67
|
+
san = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
|
|
68
|
+
except x509.ExtensionNotFound:
|
|
69
|
+
return False
|
|
70
|
+
try:
|
|
71
|
+
ip = ipaddress.ip_address(domain)
|
|
72
|
+
return ip in san.get_values_for_type(x509.IPAddress)
|
|
73
|
+
except ValueError:
|
|
74
|
+
pass
|
|
75
|
+
domain = domain.lower().rstrip(".")
|
|
76
|
+
for name in san.get_values_for_type(x509.DNSName):
|
|
77
|
+
name = name.lower().rstrip(".")
|
|
78
|
+
if name == domain:
|
|
79
|
+
return True
|
|
80
|
+
if name.startswith("*.") and "." in domain and domain.split(".", 1)[1] == name[2:]:
|
|
81
|
+
return True
|
|
82
|
+
return False
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def check(cert_path: Path, key_path: Path, domain: str, *, now: dt.datetime | None = None) -> CertStatus:
|
|
86
|
+
st = CertStatus(str(cert_path), str(key_path))
|
|
87
|
+
now = now or dt.datetime.now(dt.timezone.utc)
|
|
88
|
+
cert = key = None
|
|
89
|
+
try:
|
|
90
|
+
cert = x509.load_pem_x509_certificate(cert_path.read_bytes())
|
|
91
|
+
except FileNotFoundError:
|
|
92
|
+
st.errors.append(f"证书文件不存在:{cert_path}")
|
|
93
|
+
except PermissionError:
|
|
94
|
+
st.errors.append(f"无权读取证书文件:{cert_path}")
|
|
95
|
+
except ValueError:
|
|
96
|
+
st.errors.append(f"证书文件不是有效的 PEM 证书:{cert_path}")
|
|
97
|
+
try:
|
|
98
|
+
key = serialization.load_pem_private_key(key_path.read_bytes(), password=None)
|
|
99
|
+
if os.name == "posix" and key_path.stat().st_mode & 0o077:
|
|
100
|
+
# ADR 0014:私钥必须只有属主可读。以前只警告,服务照样起来用 0644 的私钥
|
|
101
|
+
st.errors.append(f"私钥文件权限过宽:{key_path},执行 chmod 600 后重试")
|
|
102
|
+
except FileNotFoundError:
|
|
103
|
+
st.errors.append(f"私钥文件不存在:{key_path}")
|
|
104
|
+
except PermissionError:
|
|
105
|
+
st.errors.append(f"无权读取私钥文件:{key_path}")
|
|
106
|
+
except (ValueError, TypeError):
|
|
107
|
+
st.errors.append(f"私钥文件不是有效的未加密 PEM 私钥:{key_path}")
|
|
108
|
+
if cert is None:
|
|
109
|
+
return st
|
|
110
|
+
|
|
111
|
+
st.fingerprint_sha256 = cert.fingerprint(hashes.SHA256()).hex()
|
|
112
|
+
st.self_signed = cert.issuer == cert.subject
|
|
113
|
+
st.not_after = cert.not_valid_after_utc.isoformat()
|
|
114
|
+
st.days_left = (cert.not_valid_after_utc - now).days
|
|
115
|
+
if now < cert.not_valid_before_utc:
|
|
116
|
+
st.errors.append("证书尚未生效")
|
|
117
|
+
if now >= cert.not_valid_after_utc:
|
|
118
|
+
st.errors.append(f"证书已过期({st.not_after})")
|
|
119
|
+
elif st.days_left < WARN_DAYS:
|
|
120
|
+
st.warnings.append(f"证书将在 {st.days_left} 天后过期")
|
|
121
|
+
if not _matches(domain, cert):
|
|
122
|
+
st.errors.append(f"证书的 SAN 不包含 {domain}")
|
|
123
|
+
if key is not None:
|
|
124
|
+
def pub(k):
|
|
125
|
+
return k.public_bytes(serialization.Encoding.DER,
|
|
126
|
+
serialization.PublicFormat.SubjectPublicKeyInfo)
|
|
127
|
+
if pub(cert.public_key()) != pub(key.public_key()):
|
|
128
|
+
st.errors.append("证书与私钥不匹配")
|
|
129
|
+
if st.self_signed:
|
|
130
|
+
st.warnings.append("自签证书,仅限自用;客户端需要显式信任这张证书")
|
|
131
|
+
return st
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _san(domain: str) -> str:
|
|
135
|
+
try:
|
|
136
|
+
ipaddress.ip_address(domain)
|
|
137
|
+
return f"IP:{domain}"
|
|
138
|
+
except ValueError:
|
|
139
|
+
return f"DNS:{domain}"
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _generate_openssl(domain: str, cert_path: Path, key_path: Path, days: int) -> bool:
|
|
143
|
+
exe = shutil.which("openssl")
|
|
144
|
+
if not exe:
|
|
145
|
+
return False
|
|
146
|
+
try:
|
|
147
|
+
proc = subprocess.run(
|
|
148
|
+
[exe, "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes",
|
|
149
|
+
"-days", str(days), "-subj", f"/CN={domain}", "-addext", f"subjectAltName={_san(domain)}",
|
|
150
|
+
"-keyout", str(key_path), "-out", str(cert_path)],
|
|
151
|
+
capture_output=True, text=True, timeout=30,
|
|
152
|
+
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)
|
|
153
|
+
except (OSError, subprocess.SubprocessError):
|
|
154
|
+
# An executable can be present in PATH but still fail to start or time
|
|
155
|
+
# out. The cryptography implementation is the supported offline fallback.
|
|
156
|
+
return False
|
|
157
|
+
return proc.returncode == 0
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _generate_python(domain: str, cert_path: Path, key_path: Path, days: int) -> None:
|
|
161
|
+
key = ec.generate_private_key(ec.SECP256R1())
|
|
162
|
+
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, domain)])
|
|
163
|
+
try:
|
|
164
|
+
alt: x509.GeneralName = x509.IPAddress(ipaddress.ip_address(domain))
|
|
165
|
+
except ValueError:
|
|
166
|
+
alt = x509.DNSName(domain)
|
|
167
|
+
now = dt.datetime.now(dt.timezone.utc)
|
|
168
|
+
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
|
|
169
|
+
.public_key(key.public_key()).serial_number(x509.random_serial_number())
|
|
170
|
+
.not_valid_before(now - dt.timedelta(minutes=5))
|
|
171
|
+
.not_valid_after(now + dt.timedelta(days=days))
|
|
172
|
+
.add_extension(x509.SubjectAlternativeName([alt]), critical=False)
|
|
173
|
+
.sign(key, hashes.SHA256()))
|
|
174
|
+
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM,
|
|
175
|
+
serialization.PrivateFormat.PKCS8,
|
|
176
|
+
serialization.NoEncryption()))
|
|
177
|
+
cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def self_signed(domain: str, cert_path: Path, key_path: Path, *, days: int = 365,
|
|
181
|
+
force: bool = False) -> tuple[CertStatus, str]:
|
|
182
|
+
"""生成自签证书。优先用 openssl(最初目标),没有时用 cryptography。返回(状态,生成方式)。"""
|
|
183
|
+
if not domain.strip():
|
|
184
|
+
raise NorainError("--domain 不能为空", exit_code=2, module="cert")
|
|
185
|
+
if days <= 0:
|
|
186
|
+
# 不拦的话 --days 0 会生成一张「已过期」的证书并以成功退出
|
|
187
|
+
raise NorainError("--days 必须是正整数", exit_code=2, module="cert")
|
|
188
|
+
if (cert_path.exists() or key_path.exists()) and not force:
|
|
189
|
+
raise NorainError(f"{cert_path} 或 {key_path} 已存在。确认要覆盖时加 --force",
|
|
190
|
+
exit_code=EXIT_CONFLICT, module="cert")
|
|
191
|
+
cert_path.parent.mkdir(parents=True, exist_ok=True)
|
|
192
|
+
os.chmod(cert_path.parent, 0o700)
|
|
193
|
+
if force: # 先清掉旧文件,避免 openssl 失败时留下新旧混杂的一对
|
|
194
|
+
cert_path.unlink(missing_ok=True)
|
|
195
|
+
key_path.unlink(missing_ok=True)
|
|
196
|
+
old_umask = os.umask(0o077)
|
|
197
|
+
try:
|
|
198
|
+
method = "openssl"
|
|
199
|
+
if not _generate_openssl(domain, cert_path, key_path, days):
|
|
200
|
+
method = "cryptography"
|
|
201
|
+
_generate_python(domain, cert_path, key_path, days)
|
|
202
|
+
finally:
|
|
203
|
+
os.umask(old_umask)
|
|
204
|
+
os.chmod(key_path, 0o600)
|
|
205
|
+
os.chmod(cert_path, 0o644)
|
|
206
|
+
return check(cert_path, key_path, domain), method
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# ---- acme ----------------------------------------------------------------------
|
|
210
|
+
|
|
211
|
+
def _port80_busy() -> bool:
|
|
212
|
+
import socket
|
|
213
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
214
|
+
if os.name == "posix":
|
|
215
|
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
216
|
+
try:
|
|
217
|
+
s.bind(("0.0.0.0", 80))
|
|
218
|
+
except PermissionError:
|
|
219
|
+
return False # 没有权限探测,不下结论
|
|
220
|
+
except OSError:
|
|
221
|
+
return True
|
|
222
|
+
return False
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def acme_status(domain: str, acme_dir: Path, *, tags: frozenset[str] | None = None,
|
|
226
|
+
tags_unknown: bool = False,
|
|
227
|
+
service_running: bool = False, tls_alpn01: bool = False,
|
|
228
|
+
now: dt.datetime | None = None) -> CertStatus:
|
|
229
|
+
"""acme 模式的检查。证书由 sing-box 内置 ACME 申请和续期,Norain 只检查前置条件;
|
|
230
|
+
在数据目录里找到已签发的证书时报告有效期。
|
|
231
|
+
|
|
232
|
+
``tls_alpn01`` 表示 443/tcp 上有一个 TLS 监听(Trojan),此时 TLS-ALPN-01 与
|
|
233
|
+
HTTP-01 互为备份(ADR 0015),80/tcp 被占用只降级为警告。
|
|
234
|
+
"""
|
|
235
|
+
st = CertStatus("(acme)", "(acme)")
|
|
236
|
+
now = now or dt.datetime.now(dt.timezone.utc)
|
|
237
|
+
if not domain.strip():
|
|
238
|
+
st.errors.append("acme 模式需要域名(server.domain)")
|
|
239
|
+
if tags_unknown:
|
|
240
|
+
# 拿不到标签不等于「带 with_acme」:找不到二进制时不能报前置条件通过
|
|
241
|
+
st.errors.append("找不到 sing-box,无法确认 with_acme 构建标签")
|
|
242
|
+
elif tags is not None and "with_acme" not in tags:
|
|
243
|
+
st.errors.append("当前 sing-box 不带 with_acme 构建标签,无法使用 acme 模式")
|
|
244
|
+
if not service_running and _port80_busy():
|
|
245
|
+
if tls_alpn01:
|
|
246
|
+
st.warnings.append("80/tcp 已被其他程序占用,HTTP-01 挑战不可用;"
|
|
247
|
+
"将依赖 443/tcp 上的 TLS-ALPN-01 挑战")
|
|
248
|
+
else:
|
|
249
|
+
st.errors.append("80/tcp 已被其他程序占用,HTTP-01 挑战无法使用;"
|
|
250
|
+
"启用 Trojan 并监听 443/tcp 可改用 TLS-ALPN-01,或后续配置 DNS-01")
|
|
251
|
+
issued = None
|
|
252
|
+
try:
|
|
253
|
+
for f in acme_dir.rglob("*.crt"):
|
|
254
|
+
if f.stem == domain:
|
|
255
|
+
issued = f
|
|
256
|
+
break
|
|
257
|
+
except OSError:
|
|
258
|
+
pass
|
|
259
|
+
if issued is None:
|
|
260
|
+
st.warnings.append("还没有签发的证书:首次启动后 sing-box 会自动申请,需要 80/tcp 可从公网访问")
|
|
261
|
+
return st
|
|
262
|
+
try:
|
|
263
|
+
cert = x509.load_pem_x509_certificate(issued.read_bytes())
|
|
264
|
+
except (OSError, ValueError):
|
|
265
|
+
st.warnings.append(f"无法读取已签发的证书:{issued}")
|
|
266
|
+
return st
|
|
267
|
+
st.certificate = str(issued)
|
|
268
|
+
st.self_signed = False
|
|
269
|
+
st.fingerprint_sha256 = cert.fingerprint(hashes.SHA256()).hex()
|
|
270
|
+
st.not_after = cert.not_valid_after_utc.isoformat()
|
|
271
|
+
st.days_left = (cert.not_valid_after_utc - now).days
|
|
272
|
+
if now >= cert.not_valid_after_utc:
|
|
273
|
+
st.errors.append(f"ACME 证书已过期({st.not_after}),续期失败,检查 80/tcp 和域名解析")
|
|
274
|
+
elif st.days_left < WARN_DAYS:
|
|
275
|
+
st.warnings.append(f"ACME 证书将在 {st.days_left} 天后过期,自动续期可能没有成功")
|
|
276
|
+
return st
|