添加GC-SAVEDOG项目,降低隐患
This commit is contained in:
1 parent
791db4fe12
commit
2f3a8682c9
54 files changed
+3642
-320
No files matched your search
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 规范化 JSON:签名与验签必须对完全相同的字节做运算,
|
||||
/// 否则「同一份内容、不同缩进/键序」会得出不同签名。
|
||||
///
|
||||
/// 规则(写进 README,第三方可复现):
|
||||
/// 1. 对象键按 Unicode 码点升序递归排序
|
||||
/// 2. 无缩进、无多余空白,UTF-8 编码,不带 BOM
|
||||
/// 3. 数字沿用源文本(不做浮点重排)
|
||||
/// 4. 非 ASCII 字符不转义(Encoder = UnsafeRelaxedJsonEscaping)
|
||||
/// 5. 签名时先移除根级 <c>signature</c> 字段
|
||||
/// </summary>
|
||||
public static class CanonicalJson
|
||||
{
|
||||
private static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
WriteIndented = false,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
|
||||
/// <summary>把 JSON 文本规范化;解析失败返回 null。</summary>
|
||||
public static byte[]? Normalize(string text, bool dropSignatureField)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
try
|
||||
{
|
||||
var node = JsonNode.Parse(text);
|
||||
if (node is not JsonObject obj) return null;
|
||||
if (dropSignatureField) obj.Remove("signature");
|
||||
var sorted = SortNode(obj);
|
||||
return Encoding.UTF8.GetBytes(sorted?.ToJsonString(Options) ?? "{}");
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode? SortNode(JsonNode? node)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case JsonObject obj:
|
||||
var result = new JsonObject();
|
||||
foreach (var pair in obj.OrderBy(p => p.Key, StringComparer.Ordinal))
|
||||
result[pair.Key] = SortNode(pair.Value);
|
||||
return result;
|
||||
|
||||
case JsonArray array:
|
||||
var list = new JsonArray();
|
||||
foreach (var item in array) list.Add(SortNode(item));
|
||||
return list;
|
||||
|
||||
default:
|
||||
return node?.DeepClone();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 内容哈希(可复现的指纹算法)。
|
||||
///
|
||||
/// 算法固定如下,构建端与客户端必须完全一致,否则会误判为「被篡改」:
|
||||
/// <code>
|
||||
/// fileHash = SHA256(文件字节)
|
||||
/// dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接
|
||||
/// "<相对路径>\0<fileHash>\n" )
|
||||
/// </code>
|
||||
/// 相对路径统一用 <c>/</c> 分隔;跳过以 <c>.</c> 开头的文件、<c>bin/</c>、<c>obj/</c>、
|
||||
/// <c>*.user</c>;不包含时间戳、权限位、文件顺序等元数据 —— 同样内容必然同样哈希。
|
||||
/// </summary>
|
||||
public static class ContentHash
|
||||
{
|
||||
public static string Sha256Hex(byte[] data)
|
||||
=> Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant();
|
||||
|
||||
public static string Sha256Hex(string text)
|
||||
=> Sha256Hex(Encoding.UTF8.GetBytes(text));
|
||||
|
||||
public static string Sha256File(string path)
|
||||
{
|
||||
using var stream = File.OpenRead(path);
|
||||
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>目录内所有参与分发的文件 -> { 相对路径 : sha256 }。</summary>
|
||||
public static Dictionary<string, string> MapFiles(string directory)
|
||||
{
|
||||
var map = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
if (!Directory.Exists(directory)) return map;
|
||||
|
||||
foreach (var file in Directory.GetFiles(directory, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var rel = Path.GetRelativePath(directory, file).Replace('\\', '/');
|
||||
if (!Distributable(rel)) continue;
|
||||
map[rel] = Sha256File(file);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/// <summary>按上述算法计算目录指纹。</summary>
|
||||
public static string DirectoryHash(string directory)
|
||||
=> DirectoryHash(MapFiles(directory));
|
||||
|
||||
public static string DirectoryHash(IReadOnlyDictionary<string, string> files)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
foreach (var pair in files.OrderBy(p => p.Key, StringComparer.Ordinal))
|
||||
builder.Append(pair.Key).Append('\0').Append(pair.Value).Append('\n');
|
||||
|
||||
return Sha256Hex(Encoding.UTF8.GetBytes(builder.ToString()));
|
||||
}
|
||||
|
||||
/// <summary>目录指纹;目录不存在时返回空串(区别于空目录的哈希)。</summary>
|
||||
public static string DirectoryHashOrEmpty(string directory)
|
||||
=> Directory.Exists(directory) ? DirectoryHash(directory) : "";
|
||||
|
||||
public static bool Distributable(string relativePath)
|
||||
{
|
||||
var rel = relativePath.Replace('\\', '/');
|
||||
if (rel.StartsWith('.')) return false;
|
||||
if (rel.Contains("/.")) return false;
|
||||
if (rel.StartsWith("bin/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.StartsWith("obj/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.Contains("/bin/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.Contains("/obj/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.EndsWith(".user", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 把「远端拿到的清单文本」变成 <see cref="RepoVersion"/>,同时带上验签结论。
|
||||
///
|
||||
/// 设计上把「验签」和「允不允许用」分开:
|
||||
/// · 本方法只负责**如实报告**信任状态;
|
||||
/// · 允不允许安装由 <c>UpdateService</c> / <c>LauncherUpdater</c> 按策略决定。
|
||||
/// 这样开发态可以「警告但继续」,发布版可以「直接拒绝」,而解析逻辑只有一份。
|
||||
/// </summary>
|
||||
public static class ManifestLoader
|
||||
{
|
||||
public static RepoVersion? Parse(string? text, out ManifestVerification verification)
|
||||
{
|
||||
verification = ManifestSignature.Verify(text, requireSignature: true);
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
|
||||
RepoVersion? version;
|
||||
try
|
||||
{
|
||||
version = JsonSerializer.Deserialize<RepoVersion>(text!, Json.Options);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"版本清单解析失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (version == null) return null;
|
||||
|
||||
// 平台键回填:RepoPackage 自己要能说出「我属于哪个 RID」,
|
||||
// 否则下载端无法推导 dist/<系统>-<架构> 这类兜底路径。
|
||||
foreach (var pair in version.Launcher.Packages)
|
||||
if (pair.Value != null) pair.Value.Rid = pair.Key;
|
||||
|
||||
version.SignatureTrust = verification.Trust.ToString();
|
||||
version.SignatureKeyId = verification.KeyId;
|
||||
version.SignatureError = verification.Error;
|
||||
return version;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>清单可信度。</summary>
|
||||
public enum ManifestTrust
|
||||
{
|
||||
/// <summary>签名有效,且密钥在受信任列表里。</summary>
|
||||
Verified,
|
||||
/// <summary>本机构建没有配置受信任密钥 —— 只能跳过验签(会打警告)。</summary>
|
||||
Skipped,
|
||||
/// <summary>清单没有签名,但客户端要求签名。</summary>
|
||||
Unsigned,
|
||||
/// <summary>有签名但验证失败:内容被改过 / 密钥不对 / 结构损坏。</summary>
|
||||
Invalid
|
||||
}
|
||||
|
||||
public sealed record ManifestVerification(ManifestTrust Trust, string? KeyId, string? Error)
|
||||
{
|
||||
public bool IsTrusted => Trust is ManifestTrust.Verified or ManifestTrust.Skipped;
|
||||
public bool IsRejected => Trust is ManifestTrust.Unsigned or ManifestTrust.Invalid;
|
||||
|
||||
public static ManifestVerification Ok(string keyId) => new(ManifestTrust.Verified, keyId, null);
|
||||
public static ManifestVerification Skip() => new(ManifestTrust.Skipped, null,
|
||||
"未配置受信任公钥,已跳过验签");
|
||||
public static ManifestVerification Bad(string error) => new(ManifestTrust.Invalid, null, error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 版本清单签名(ECDSA P-256 / SHA-256)。
|
||||
///
|
||||
/// 为什么不用 sha256 了事:sha256 只能证明「下载没坏」,不能证明「这份清单是我发的」。
|
||||
/// 仓库被入侵时攻击者可以同时改清单和 sha256 —— 只有签名需要**没有放进仓库**的私钥,
|
||||
/// 才能把「篡改清单」这条路堵死。
|
||||
///
|
||||
/// 为什么不自己实现 Ed25519:手写椭圆曲线实现出错就是静默失效。.NET 8 自带
|
||||
/// ECDSA P-256,跨平台、无第三方依赖,安全性等价于工程需要。
|
||||
///
|
||||
/// 信任链:内置公钥 → 验证 version.json → 得到各发布包的 sha256 → 校验下载到的 zip
|
||||
/// → 校验解压出的模型文件 → 加载 dll。
|
||||
/// </summary>
|
||||
public static class ManifestSignature
|
||||
{
|
||||
public const string Algorithm = "ECDSA-P256-SHA256";
|
||||
|
||||
private static readonly JsonSerializerOptions WriteOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ 验签
|
||||
|
||||
/// <summary>
|
||||
/// 校验清单文本的签名。<paramref name="requireSignature"/> 为 true 时,
|
||||
/// 无签名视为失败;为 false 时无签名只返回 <see cref="ManifestTrust.Unsigned"/>,
|
||||
/// 由调用方决定是否放行(开发态用)。
|
||||
/// </summary>
|
||||
public static ManifestVerification Verify(string? text, bool requireSignature)
|
||||
{
|
||||
if (SignatureKeyring.Keys.Count == 0) return ManifestVerification.Skip();
|
||||
if (string.IsNullOrWhiteSpace(text)) return ManifestVerification.Bad("清单内容为空");
|
||||
|
||||
JsonObject root;
|
||||
try
|
||||
{
|
||||
root = JsonNode.Parse(text!) as JsonObject ?? throw new JsonException("根节点不是对象");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return ManifestVerification.Bad("清单不是合法 JSON: " + ex.Message);
|
||||
}
|
||||
|
||||
if (root["signature"] is not JsonObject signature)
|
||||
return requireSignature
|
||||
? new ManifestVerification(ManifestTrust.Unsigned, null, "清单缺少签名")
|
||||
: new ManifestVerification(ManifestTrust.Unsigned, null, "清单未签名");
|
||||
|
||||
var keyId = signature["keyId"]?.GetValue<string>() ?? "";
|
||||
var value = signature["value"]?.GetValue<string>() ?? "";
|
||||
var alg = signature["alg"]?.GetValue<string>() ?? Algorithm;
|
||||
|
||||
if (!string.Equals(alg, Algorithm, StringComparison.OrdinalIgnoreCase))
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, $"不支持的签名算法: {alg}");
|
||||
if (value.Length == 0)
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, "签名为空");
|
||||
|
||||
var key = SignatureKeyring.Find(keyId);
|
||||
if (key == null)
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, $"未知签名密钥: {keyId}");
|
||||
|
||||
var payload = CanonicalJson.Normalize(text!, dropSignatureField: true);
|
||||
if (payload == null)
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, "无法规范化清单");
|
||||
|
||||
try
|
||||
{
|
||||
var sig = Convert.FromBase64String(value);
|
||||
using var ecdsa = ECDsa.Create();
|
||||
ecdsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(key.PublicKeyBase64), out _);
|
||||
var ok = ecdsa.VerifyData(payload, sig, HashAlgorithmName.SHA256,
|
||||
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
return ok
|
||||
? ManifestVerification.Ok(key.KeyId)
|
||||
: new ManifestVerification(ManifestTrust.Invalid, keyId, "签名与内容不符");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, "验签异常: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 签名
|
||||
|
||||
/// <summary>用私钥给清单签名,返回写入了 <c>signature</c> 字段的新清单文本。</summary>
|
||||
public static string SignDocument(string text, ECDsa key, string keyId)
|
||||
{
|
||||
var payload = CanonicalJson.Normalize(text, dropSignatureField: true)
|
||||
?? throw new InvalidOperationException("清单不是合法 JSON,无法签名");
|
||||
|
||||
var signature = key.SignData(payload, HashAlgorithmName.SHA256,
|
||||
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
var contentHash = Convert.ToHexString(SHA256.HashData(payload)).ToLowerInvariant();
|
||||
|
||||
var root = JsonNode.Parse(text) as JsonObject
|
||||
?? throw new InvalidOperationException("清单根节点不是对象");
|
||||
|
||||
root["signature"] = new JsonObject
|
||||
{
|
||||
["alg"] = Algorithm,
|
||||
["keyId"] = keyId,
|
||||
["value"] = Convert.ToBase64String(signature),
|
||||
["contentSha256"] = contentHash,
|
||||
["signedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||
};
|
||||
|
||||
return root.ToJsonString(WriteOptions) + "\n";
|
||||
}
|
||||
|
||||
/// <summary>从 PEM 文件加载私钥(PKCS#8 或 SEC1 均可)。</summary>
|
||||
public static ECDsa? TryLoadPrivateKey(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) return null;
|
||||
var pem = File.ReadAllText(path);
|
||||
if (pem.Contains("BEGIN", StringComparison.Ordinal) == false) return null;
|
||||
var key = ECDsa.Create();
|
||||
key.ImportFromPem(pem);
|
||||
return key;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>导出公钥(SPKI / Base64),用于写入客户端受信任列表。</summary>
|
||||
public static string ExportPublicKeyBase64(ECDsa key)
|
||||
=> Convert.ToBase64String(key.ExportSubjectPublicKeyInfo());
|
||||
|
||||
/// <summary>公钥指纹,便于人工核对两边的公钥是否一致。</summary>
|
||||
public static string PublicKeyFingerprint(string publicKeyBase64)
|
||||
=> Convert.ToHexString(SHA256.HashData(Convert.FromBase64String(publicKeyBase64)))
|
||||
.ToLowerInvariant()[..16];
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>模型安装后落盘的完整性记录。</summary>
|
||||
public sealed class ModelIntegrityFile
|
||||
{
|
||||
public int Schema { get; set; } = 1;
|
||||
public string Id { get; set; } = "";
|
||||
public string Version { get; set; } = "";
|
||||
/// <summary>模型清单文件的 sha256。</summary>
|
||||
public string ManifestSha256 { get; set; } = "";
|
||||
/// <summary><id>.model 目录的目录指纹。</summary>
|
||||
public string FilesSha256 { get; set; } = "";
|
||||
/// <summary>关键文件(dll / json)逐文件哈希,用于加载前快速校验。</summary>
|
||||
public Dictionary<string, string> Files { get; set; } = new();
|
||||
public string InstalledAt { get; set; } = "";
|
||||
/// <summary>来源(远端源名 / 本地目录),便于排查。</summary>
|
||||
public string Source { get; set; } = "";
|
||||
}
|
||||
|
||||
public sealed record IntegrityResult(bool Ok, bool Present, string Message)
|
||||
{
|
||||
public static readonly IntegrityResult Missing =
|
||||
new(true, false, "没有完整性记录(本地/开发模型),跳过校验");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模型包完整性校验:下载后复算、安装后落盘、加载前抽查。
|
||||
///
|
||||
/// 威胁模型:模型 dll 会被 <c>AssemblyLoadContext</c> 直接执行,等于任意代码。
|
||||
/// 如果版本清单被篡改(或本地文件被替换),攻击者就能让启动器加载他的 dll。
|
||||
/// 因此:
|
||||
/// 1. version.json(已签名)里带 manifestSha256 / filesSha256;
|
||||
/// 2. 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装;
|
||||
/// 3. 安装成功后写 <c><id>.integrity.json</c>;
|
||||
/// 4. 每次加载 dll 前抽查 dll / json 的哈希。
|
||||
/// </summary>
|
||||
public static class ModelIntegrity
|
||||
{
|
||||
public const string FileNameSuffix = ".integrity.json";
|
||||
|
||||
public static string IntegrityPath(string modelDirectory, string id)
|
||||
=> Path.Combine(modelDirectory, id + FileNameSuffix);
|
||||
|
||||
public static ModelIntegrityFile? Read(string modelDirectory, string id)
|
||||
=> Json.Read<ModelIntegrityFile>(IntegrityPath(modelDirectory, id));
|
||||
|
||||
public static void Write(string modelDirectory, string id, ModelIntegrityFile data)
|
||||
=> Json.Write(IntegrityPath(modelDirectory, id), data);
|
||||
|
||||
/// <summary>
|
||||
/// 计算某个模型包(清单 + 数据目录)的哈希。
|
||||
/// <paramref name="packageDirectory"/> 是包含 <c><id>.json</c> 与
|
||||
/// <c><id>.model/</c> 的那一层。
|
||||
/// </summary>
|
||||
public static (string ManifestSha256, string FilesSha256, Dictionary<string, string> Files)
|
||||
Compute(string packageDirectory, string id)
|
||||
{
|
||||
var manifestPath = Path.Combine(packageDirectory, id + ".json");
|
||||
var dataDir = Path.Combine(packageDirectory, id + ".model");
|
||||
|
||||
var manifestSha = File.Exists(manifestPath) ? ContentHash.Sha256File(manifestPath) : "";
|
||||
var files = ContentHash.MapFiles(dataDir);
|
||||
var filesSha = ContentHash.DirectoryHash(files);
|
||||
|
||||
var critical = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var pair in files)
|
||||
{
|
||||
if (!IsCritical(pair.Key)) continue;
|
||||
critical[id + ".model/" + pair.Key] = pair.Value;
|
||||
}
|
||||
if (manifestSha.Length > 0) critical[id + ".json"] = manifestSha;
|
||||
|
||||
return (manifestSha, filesSha, critical);
|
||||
}
|
||||
|
||||
/// <summary>加载前校验:只查会被执行 / 解析的文件,保证 <c>OpenModel</c> 不被明显拖慢。</summary>
|
||||
public static IntegrityResult VerifyForLoad(string packageDirectory, string id)
|
||||
{
|
||||
var record = Read(packageDirectory, id);
|
||||
if (record == null) return IntegrityResult.Missing;
|
||||
|
||||
if (!string.Equals(record.Id, id, StringComparison.Ordinal))
|
||||
return new IntegrityResult(false, true, $"完整性记录与模型 id 不符: {record.Id}");
|
||||
|
||||
foreach (var pair in record.Files)
|
||||
{
|
||||
var path = Path.Combine(packageDirectory, pair.Key.Replace('/', Path.DirectorySeparatorChar));
|
||||
if (!File.Exists(path))
|
||||
return new IntegrityResult(false, true, $"缺少文件: {pair.Key}");
|
||||
|
||||
var actual = ContentHash.Sha256File(path);
|
||||
if (!string.Equals(actual, pair.Value, StringComparison.OrdinalIgnoreCase))
|
||||
return new IntegrityResult(false, true, $"文件已被修改: {pair.Key}");
|
||||
}
|
||||
|
||||
return new IntegrityResult(true, true, "完整性校验通过");
|
||||
}
|
||||
|
||||
private static bool IsCritical(string relativePath)
|
||||
{
|
||||
var rel = relativePath.Replace('\\', '/');
|
||||
return rel.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.EndsWith(".dylib", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.EndsWith(".so", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 安全解压:更新包来自网络,必须当成不可信输入处理。
|
||||
///
|
||||
/// 拦截:
|
||||
/// · zip slip(<c>../</c>、绝对路径、盘符、UNC)
|
||||
/// · 符号链接 / 硬链接条目(解压后可指向系统任意文件)
|
||||
/// · zip 炸弹(条目数过多、解压后总体积过大、压缩比异常)
|
||||
/// 逐条校验通过后**自己写文件**,不使用 <see cref="ZipFile.ExtractToDirectory(string,string)"/>,
|
||||
/// 避免框架在写入阶段才发现问题、留下半成品。
|
||||
/// </summary>
|
||||
public static class SafeArchive
|
||||
{
|
||||
/// <summary>单个包最多条目数。</summary>
|
||||
public const int MaxEntries = 20000;
|
||||
|
||||
/// <summary>解压后总体积上限(2 GiB)。</summary>
|
||||
public const long MaxUncompressedBytes = 2L * 1024 * 1024 * 1024;
|
||||
|
||||
/// <summary>单个条目解压上限(1 GiB)。</summary>
|
||||
public const long MaxSingleEntryBytes = 1L * 1024 * 1024 * 1024;
|
||||
|
||||
/// <summary>压缩比上限:超过视为 zip 炸弹。</summary>
|
||||
public const int MaxCompressionRatio = 200;
|
||||
|
||||
public sealed record Inspection(int Entries, long UncompressedBytes, long CompressedBytes)
|
||||
{
|
||||
public double Ratio => CompressedBytes <= 0 ? 0 : (double)UncompressedBytes / CompressedBytes;
|
||||
}
|
||||
|
||||
/// <summary>只检查不解压:条目数、体积、路径、链接。发现问题抛异常。</summary>
|
||||
public static Inspection Inspect(string zipPath)
|
||||
{
|
||||
using var archive = ZipFile.OpenRead(zipPath);
|
||||
long total = 0;
|
||||
var count = 0;
|
||||
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
count++;
|
||||
if (count > MaxEntries)
|
||||
throw new InvalidOperationException($"压缩包条目过多(>{MaxEntries}),疑似恶意包");
|
||||
|
||||
ValidateName(entry.FullName);
|
||||
AssertNotLink(entry);
|
||||
|
||||
if (entry.Length > MaxSingleEntryBytes)
|
||||
throw new InvalidOperationException($"条目过大: {entry.FullName}");
|
||||
|
||||
total += entry.Length;
|
||||
if (total > MaxUncompressedBytes)
|
||||
throw new InvalidOperationException("解压后体积超出上限,疑似 zip 炸弹");
|
||||
}
|
||||
|
||||
var compressed = new FileInfo(zipPath).Length;
|
||||
var inspection = new Inspection(count, total, compressed);
|
||||
if (compressed > 0 && inspection.Ratio > MaxCompressionRatio && total > 64L * 1024 * 1024)
|
||||
throw new InvalidOperationException($"压缩比异常({inspection.Ratio:0.#}:1),疑似 zip 炸弹");
|
||||
|
||||
return inspection;
|
||||
}
|
||||
|
||||
public static void ExtractToDirectory(string zipPath, string destination)
|
||||
{
|
||||
Inspect(zipPath);
|
||||
|
||||
Directory.CreateDirectory(destination);
|
||||
var destFull = Path.GetFullPath(destination)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
|
||||
using var archive = ZipFile.OpenRead(zipPath);
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
var name = entry.FullName.Replace('\\', '/');
|
||||
if (name.EndsWith("/", StringComparison.Ordinal))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetFullPath(Path.Combine(destFull, name)));
|
||||
continue;
|
||||
}
|
||||
|
||||
var target = Path.GetFullPath(Path.Combine(destFull, name));
|
||||
if (!target.StartsWith(destFull, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}");
|
||||
|
||||
var dir = Path.GetDirectoryName(target);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
|
||||
using (var source = entry.Open())
|
||||
using (var output = new FileStream(target, FileMode.Create, FileAccess.Write,
|
||||
FileShare.None, 81920, FileOptions.None))
|
||||
{
|
||||
source.CopyTo(output);
|
||||
}
|
||||
|
||||
TryApplyUnixMode(entry, target);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>校验条目名,拒绝一切能逃出目标目录的写法。</summary>
|
||||
public static void ValidateName(string fullName)
|
||||
{
|
||||
var name = fullName.Replace('\\', '/');
|
||||
if (name.Length == 0) throw new InvalidOperationException("压缩包含空文件名条目");
|
||||
if (name.StartsWith('/')) throw new InvalidOperationException($"压缩包含绝对路径: {fullName}");
|
||||
if (name.StartsWith("//")) throw new InvalidOperationException($"压缩包含 UNC 路径: {fullName}");
|
||||
if (name.Length >= 2 && name[1] == ':')
|
||||
throw new InvalidOperationException($"压缩包含盘符路径: {fullName}");
|
||||
|
||||
foreach (var segment in name.Split('/'))
|
||||
{
|
||||
if (segment == "..")
|
||||
throw new InvalidOperationException($"压缩包含父目录穿越: {fullName}");
|
||||
}
|
||||
|
||||
if (name.Contains('\0'))
|
||||
throw new InvalidOperationException($"压缩包含非法字符: {fullName}");
|
||||
}
|
||||
|
||||
/// <summary>Unix 模式下 S_IFLNK = 0xA000,符号链接条目一律拒绝。</summary>
|
||||
private static void AssertNotLink(ZipArchiveEntry entry)
|
||||
{
|
||||
var mode = (entry.ExternalAttributes >> 16) & 0xF000;
|
||||
if (mode == 0xA000)
|
||||
throw new InvalidOperationException($"压缩包含符号链接条目: {entry.FullName}");
|
||||
}
|
||||
|
||||
private static void TryApplyUnixMode(ZipArchiveEntry entry, string target)
|
||||
{
|
||||
if (OperatingSystem.IsWindows()) return;
|
||||
try
|
||||
{
|
||||
var mode = (UnixFileMode)((entry.ExternalAttributes >> 16) & 0x1FF);
|
||||
if (mode == 0) return;
|
||||
File.SetUnixFileMode(target, mode);
|
||||
}
|
||||
catch { /* 权限位设置失败不影响文件内容 */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器 ↔ GC-SAVEDOG 的握手协议(都在 <c>.GC/update/</c> 下,全部相对路径)。
|
||||
///
|
||||
/// 流程:
|
||||
/// <code>
|
||||
/// launcher 下载并校验更新包
|
||||
/// -> 解压到 update/payload/
|
||||
/// -> 写 apply-request.json + 已验签的 version.json 副本
|
||||
/// -> 启动 GC-SAVEDOG apply --wait-pid <自己>
|
||||
/// -> 自己退出
|
||||
///
|
||||
/// GC-SAVEDOG
|
||||
/// -> 等父进程退出
|
||||
/// -> 重验签名 + 包 sha256 + 解压安全性
|
||||
/// -> 把 payload 移到安装目录(绝不覆盖已有版本)
|
||||
/// -> 启动新版,等 update/health.json
|
||||
/// -> 健康:删同平台旧版本;不健康:删新版、重启旧版
|
||||
/// -> 写 state.json(applied / rolledback / failed)
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public static class SavedogFiles
|
||||
{
|
||||
public const string ApplyRequest = "apply-request.json";
|
||||
public const string State = "state.json";
|
||||
public const string Log = "savedog.log";
|
||||
public const string Health = StartupHealth.FileName;
|
||||
public const string LastGood = "last-good.json";
|
||||
|
||||
/// <summary>SAVEDOG 可执行文件名(各平台一致,Windows 带 .exe)。</summary>
|
||||
public static string ExecutableName =>
|
||||
OperatingSystem.IsWindows() ? "GC-SAVEDOG.exe" : "GC-SAVEDOG";
|
||||
}
|
||||
|
||||
/// <summary>启动器写入的更新申请。</summary>
|
||||
public sealed class SavedogRequest
|
||||
{
|
||||
public int Schema { get; set; } = 1;
|
||||
|
||||
/// <summary>新版本号,如 1.0.8。</summary>
|
||||
public string Version { get; set; } = "";
|
||||
|
||||
public string Rid { get; set; } = "";
|
||||
|
||||
/// <summary>文件名里的平台标签,如 mac-arm64。</summary>
|
||||
public string PlatformLabel { get; set; } = "";
|
||||
|
||||
/// <summary>payload 里的新版本包名(GC-1.0.8-mac-arm64.app / .exe)。</summary>
|
||||
public string PackageName { get; set; } = "";
|
||||
|
||||
/// <summary>payload 目录(相对 update 目录)。</summary>
|
||||
public string PayloadDir { get; set; } = "payload";
|
||||
|
||||
/// <summary>已验签清单的副本(相对 update 目录),用于二次验签。</summary>
|
||||
public string ManifestPath { get; set; } = "version.json";
|
||||
|
||||
/// <summary>更新包 zip 路径(相对 update 目录),SAVEDOG 自己解压,不信任预解压目录。</summary>
|
||||
public string PackageZip { get; set; } = "package.zip";
|
||||
|
||||
/// <summary>更新包 sha256(来自已验签清单)。</summary>
|
||||
public string? PackageSha256 { get; set; }
|
||||
|
||||
public long PackageSize { get; set; }
|
||||
|
||||
/// <summary>是否强制要求清单签名。</summary>
|
||||
public bool RequireSignature { get; set; } = true;
|
||||
|
||||
/// <summary>安装目录(相对 update 目录),由启动器按实际路径算出。</summary>
|
||||
public string InstallRelative { get; set; } = "../..";
|
||||
|
||||
public string CreatedAt { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||
}
|
||||
|
||||
/// <summary>SAVEDOG 的执行结果,写入 state.json 供界面显示。</summary>
|
||||
public sealed class SavedogState
|
||||
{
|
||||
public string Status { get; set; } = "unknown"; // applied | rolledback | failed | refused
|
||||
public string Version { get; set; } = "";
|
||||
public string? PreviousVersion { get; set; }
|
||||
public string PackageName { get; set; } = "";
|
||||
public string Message { get; set; } = "";
|
||||
public string At { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||
public bool Verified { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>上次成功启动的版本信息,回滚时用。</summary>
|
||||
public sealed class LastGoodVersion
|
||||
{
|
||||
public string Version { get; set; } = "";
|
||||
public string PackageName { get; set; } = "";
|
||||
public string At { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 受信任的签名公钥。
|
||||
///
|
||||
/// 公钥是公开的,写在源码里没有问题;**私钥永远不进仓库**
|
||||
/// (放在仓库根 <c>.signing/</c>,已在 .gitignore 中)。
|
||||
///
|
||||
/// 轮换密钥:用 <c>GC-SAVEDOG keygen</c> 生成新的一对,把新公钥追加到这里,
|
||||
/// 旧公钥保留一个版本周期,避免老客户端直接失效。
|
||||
/// 也可用环境变量临时注入(测试 / 私有构建):
|
||||
/// <c>GC_TRUSTED_KEYS="id1:base64;id2:base64"</c>
|
||||
/// </summary>
|
||||
public static class SignatureKeyring
|
||||
{
|
||||
public sealed record KeyEntry(string KeyId, string PublicKeyBase64, string? Note = null);
|
||||
|
||||
private static readonly List<KeyEntry> KeysInternal = new()
|
||||
{
|
||||
// 生产密钥(2026-11 生成)。指纹 b41b1dd6259ea9ed
|
||||
new KeyEntry(
|
||||
"gc-2026-11",
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEny5YKVBZUzOyRcSiuutlGmBb4+xm" +
|
||||
"PrNDGshilBlpmFyWu5Atq+FGP2tn+8Or8V7OH+/7lhCmXu8jZuC5/5CWSw==",
|
||||
"GC 主发布密钥")
|
||||
};
|
||||
|
||||
static SignatureKeyring() => LoadFromEnvironment();
|
||||
|
||||
public static IReadOnlyList<KeyEntry> Keys => KeysInternal;
|
||||
|
||||
/// <summary>是否配置了受信任密钥(配置了就必须验签)。</summary>
|
||||
public static bool Enforced => KeysInternal.Count > 0;
|
||||
|
||||
public static KeyEntry? Find(string? keyId)
|
||||
{
|
||||
if (KeysInternal.Count == 0) return null;
|
||||
foreach (var key in KeysInternal)
|
||||
if (string.Equals(key.KeyId, keyId, StringComparison.Ordinal))
|
||||
return key;
|
||||
// 未写 keyId 且只有一个密钥时容忍(早期构建产物)
|
||||
if (string.IsNullOrWhiteSpace(keyId) && KeysInternal.Count == 1) return KeysInternal[0];
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>测试 / 私有分发用:追加一个受信任公钥。</summary>
|
||||
public static void Add(KeyEntry key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key.KeyId) || string.IsNullOrWhiteSpace(key.PublicKeyBase64)) return;
|
||||
if (Find(key.KeyId) != null) return;
|
||||
KeysInternal.Add(key);
|
||||
}
|
||||
|
||||
/// <summary>测试用:替换整个密钥环。</summary>
|
||||
public static void ReplaceAll(IEnumerable<KeyEntry> keys)
|
||||
{
|
||||
KeysInternal.Clear();
|
||||
foreach (var key in keys) KeysInternal.Add(key);
|
||||
}
|
||||
|
||||
private static void LoadFromEnvironment()
|
||||
{
|
||||
var raw = Environment.GetEnvironmentVariable("GC_TRUSTED_KEYS");
|
||||
if (string.IsNullOrWhiteSpace(raw)) return;
|
||||
foreach (var part in raw!.Split(';', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var idx = part.IndexOf(':');
|
||||
if (idx <= 0 || idx >= part.Length - 1) continue;
|
||||
var keyId = part[..idx].Trim();
|
||||
var value = part[(idx + 1)..].Trim();
|
||||
if (keyId.Length == 0 || value.Length == 0) continue;
|
||||
if (Find(keyId) != null) continue;
|
||||
KeysInternal.Add(new KeyEntry(keyId, value, "来自 GC_TRUSTED_KEYS"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动成功的健康标记。
|
||||
///
|
||||
/// 新版启动器启动后写这个文件;GC-SAVEDOG 在替换完程序后会等它出现,
|
||||
/// 等不到就回滚到旧版本 —— 这样「新版本一启动就崩」不会把用户卡死。
|
||||
/// </summary>
|
||||
public static class StartupHealth
|
||||
{
|
||||
public const string FileName = "health.json";
|
||||
|
||||
public static string PathFor(string updateRoot) => Path.Combine(updateRoot, FileName);
|
||||
|
||||
/// <summary>主窗口显示后调用:证明本次启动真的跑起来了。</summary>
|
||||
public static void MarkHealthy(string updateRoot, string version)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(updateRoot);
|
||||
Json.Write(PathFor(updateRoot), new HealthRecord
|
||||
{
|
||||
Version = version,
|
||||
Pid = Environment.ProcessId,
|
||||
At = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
|
||||
Ok = true
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"写入健康标记失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static HealthRecord? Read(string updateRoot)
|
||||
=> Json.Read<HealthRecord>(PathFor(updateRoot));
|
||||
|
||||
public static void Clear(string updateRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
var path = PathFor(updateRoot);
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public sealed class HealthRecord
|
||||
{
|
||||
public string Version { get; set; } = "";
|
||||
public int Pid { get; set; }
|
||||
public string At { get; set; } = "";
|
||||
public bool Ok { get; set; }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user