fix(security): 加固模型安装与本地目录源,防止同机后端伪装

- ModelInstaller: 模型 Id 限定为单段安全名称,拒绝路径分隔符/绝对路径/
  符号链接,源目录枚举跳过重解析点,防止写到模型库外
- DirectoryRemote: 清单验签失败如实记录;包 URL 仅允许 http(s) 公网地址,
  拦截 file:/私有 IP/环回/元数据地址(SSRF);SafePath 逐级解析符号链接
  并确认仍在根目录内
- 本机后端健康检查改为一次性会话令牌双向校验(/api/health 返回指纹),
  同机伪造服务无法通过身份确认;所有 /api 请求需带令牌,封面图走 query

只含 7 个安全文件,基于最新 origin2/main(含已合入的 #32 课件)。
This commit is contained in:
Morris committed 2026-11-21 07:43:59 +08:00
1 parent 1dd3b40cb6
commit 46ed84475d
7 files changed
+305 -34

No files matched your search

+31
View File
@@ -172,6 +172,16 @@ public static class GcUiContract
/// <summary>传给后端与前端的环境变量名。</summary>
public const string PortEnvVar = "GC_UI_PORT";
/// <summary>
/// 启动器为本次会话生成的一次性令牌,经环境变量同时传给进程内后端与 Flutter 前端。
/// 前端每个请求都要带该令牌,后端据此确认对方是自己拉起的那个前端;
/// 同机伪装进程即便占了端口,也没有令牌,无法被前端当成后端复用。
/// </summary>
public const string TokenEnvVar = "GC_UI_TOKEN";
/// <summary>前端携带一次性令牌的请求头。</summary>
public const string TokenHeader = "X-GC-UI-Token";
/// <summary>读取环境变量里指定的端口;非法或未设置时返回 <see cref="DefaultPort"/>。</summary>
public static int PortFromEnvironment()
{
@@ -180,4 +190,25 @@ public static class GcUiContract
? port
: DefaultPort;
}
/// <summary>生成 256 位会话令牌(hex);cryptographically random,无法预测。</summary>
public static string NewSessionToken()
{
var bytes = new byte[32];
System.Security.Cryptography.RandomNumberGenerator.Fill(bytes);
return Convert.ToHexString(bytes).ToLowerInvariant();
}
/// <summary>
/// 由令牌派生一段短指纹,后端在 /api/health 里回给启动器用于身份确认。
/// 回指纹而非令牌本身,避免会话令牌出现在明文 HTTP 响应体里;启动器用同一函数
/// 算期望值比对,不匹配的「健康」响应一律视为伪装服务。
/// </summary>
public static string DeriveSessionProof(string? token)
{
if (string.IsNullOrEmpty(token)) return "";
var bytes = System.Text.Encoding.UTF8.GetBytes("gc-health-proof:" + token);
var hash = System.Security.Cryptography.SHA256.HashData(bytes);
return Convert.ToHexString(hash.AsSpan(0, 16)).ToLowerInvariant();
}
}