AIGC标识 【AI】IDA Pro 9.5.261026 许可验证机制

IDA Pro 9.5.261026 许可验证机制

Version 9.5.261026.365f1f33 Windows x64

1 结论与分析对象

1.1 核心结论

# 结论 依据 佐证
1 许可证是 JSON 文本文件,由引擎按模式串定位、读取并解析,根节点必须是 object。 实测 sub_1004734E0 @0x1004734E0;sub_1004797D0 @0x1004797D0,v24 == 3
2 签名覆盖范围是顶层对象去掉 signature 与 header 后重新规范化序列化的文本,再做 SHA-256,得到 32 B 摘要。 静态确认 sub_10047A700 @0x10047A700;sha256_init/update/final @0x10047A932 至 0x10047A952
3 规范化序列化输出无空白,键名按 strcmp 字典序排序,字符串按引擎自身的转义规则编码。 静态确认 sub_10047B210 @0x10047B210 → serialize_json(mode=2)
4 signature 是十六进制字符串,按 %02X 每 2 字符解 1 字节,必须整串消费。 静态确认 sub_1004799C0 @0x1004799C0,qsscanf(v18, "%02X", &v44) @0x100479AF9
5 模数不存明文,128 B 混淆种子由 64 个 16-bit 小端字经固定置换与 XOR 流还原为 64 个 16-bit limb。 静态确认 sub_10047AAD0 @0x10047AAD0,种子表 word_101A3F3B0 @0x101A3F3B0
6 公钥指数 e = 19,写入派生结构 +0xA0 的首个 16-bit limb,其余 limb 为 0。 静态确认 0x10047AE29:a1[0x50] = 0x13
7 派生结构长 0x160:+0x00 为 N 占 128 B、+0x80 为零区占 32 B、+0xA0 为指数区占 160 B、+0x140 为 SHA-256 摘要占 32 B。 静态确认 sub_10047AAD0 的 memset 与 sha256_final(a1 + 0xA0)@0x10047AEFB
8 验签前有 5 道门限,全部读取 +0x140 摘要字节,任一不满足即返回 0 并输出 Invalid input data。 静态确认 sub_1004780B0 @0x1004781B5、0x1004782F2
8a 模数与私钥按 16-bit limb 小端存放,数值等价于 int.from_bytes(blob, "little")。 实测 sub_100480C20 的 limb 加法与乘法;pow(pow(m, d, N), 19, N) == m 成立
9 pow(sig, 19, N) 的结果经去前缀、尾零检查、去掩码后得到 off 字节前缀加 32 B 摘要,off = digest[7] ^ 0xEF,块长 v9 = off + 0x20。 静态确认 0x1004781C8 尾零循环、0x100478288 掩码、a2[0] = (v8, off)、a2[1] = (0x20, v9)
10 去掩码中 0x1B873593 * k 按 32-bit 截断,掩码字节为 digest[i & 31] ^ byte_101A3F430[i & 31] ^ 流字节。 静态确认 0x100478288 的 imul;byte_101A3F430 = ff47838c…678e88
11 最终比较为 32 字节无分支比较,不一致返回非 0。 静态确认 sub_100478330 @0x100478330
12 验签通过后才解析 payload;payload 必含 name、email、licenses,每个 license 条目必须是 object。 静态确认 sub_100477B70 @0x100477B70 的调用顺序;sub_100479CC0 @0x100479CC0
13 add-on 必含 id、code、owner、start_date、end_date;日期按 %d-%d-%d 解析并经 qtimegm 转为 UTC 时间戳。 静态确认 sub_100478530 @0x100478530;sub_10047B5C0 @0x10047B5C0;sub_10047B680 @0x10047B680
14 4 份种子整块替换为 PATCH_REPLACE,derive 得到 C_MODULUS,配 e=19 私钥签发的许可证可被 idat.exe -A 接受,退出码 0。 实测 进程内接受,退出码 0
15 许可证身份显示只有两处:License info: %s 取 licenses[].id 即记录 +0x00 的 6 字节,Licensed to: %s 与 %s <%s> 取 payload.name 与 payload.email;owner 不出现在任何格式串。 静态确认 sub_10005E3F0 @0x10005E3F0 的 0x10005E5CA、0x10005E5E4、0x10005E6E4、0x10005EB55;get_license_id_buf @0x101658300
16 主许可 owner 只要求键存在且类型为 string,原样存入记录 +0x20,无格式校验、无读取点;add-on 的 owner 经 sub_1000646A0 校验,必须为 6 段十六进制 ID,否则报 Invalid owner license ID。 静态确认 sub_100478940 @0x100479567;sub_100478530 @0x100478813;sub_1000646A0 @0x1000646A0

1.2 分析对象与地址约定

文件 架构 大小 SHA-256
ida.dll AMD64 / PE32+ 35007488 B 16666d2ec8346531ae4cd12a1a6e1b1dff0a126f726425d303a2c78f5f2059b5
ida32.dll AMD64 / PE32+ 6467584 B f1fd2708d3192652e65bb851b4438f3c1a1b2dd4bf81964eb43a461c29330f87

VA 以镜像基址 0x100000000 表示,VA = RVA + 0x100000000。两个 DLL 的文件偏移与 RVA 相等,种子副本文件偏移 0x1A3E7B0 对应 VA 0x101A3F3B0。正文代码为各函数节选。

2 验证流程

2.1 执行顺序

步骤 动作 函数与地址
1 按模式串定位许可证文件,逐候选加载 sub_1004734E0 @0x1004734E0 → sub_100474800
2 文本转 JSON,校验根节点为 object(3) sub_1004797D0 @0x1004797D0
3 取 signature 并按十六进制解码 sub_1004799C0 @0x1004799C0
4 规范化序列化,排除 signature 与 header,再做 SHA-256 sub_10047A700 @0x10047A700 → sub_10047B210 → serialize_json
5 种子派生密钥结构:N、e=19、+0x140 摘要 sub_10047AAD0 @0x10047AAD0
6 5 道门限,检查摘要字节、长度与范围 sub_1004780B0 @0x1004781B5
7 模幂 sig^19 mod N sub_100480A10 → sub_100480C20
8 去前缀、尾零检查、去掩码、取 off 处 32 B sub_1004780B0 @0x1004781BB 至 0x1004782D6
9 32 B 摘要比较 sub_100478330 @0x100478330
10 解析 payload、licenses、add-on 与日期 sub_100479CC0 @0x100479CC0、sub_100478940、sub_100478530

2.2 总流程图

flowchart TD L["定位 idapro*.hexlic"] --> R["读取文件内容"] R --> J["JSON 解析与根节点类型校验"] J -->|根节点非 object| E0["拒绝:返回 0"] J --> S["提取 signature 字符串"] S -->|十六进制未整串消费| E9["拒绝:返回 9"] S --> H["去掉 header 与 signature 后规范化序列化"] H --> D["SHA-256,32 B"] D --> K["种子派生模数与指数 e=19"] K --> G["5 道门限校验"] G -->|失败| EG["拒绝:返回 0,Invalid input data"] G -->|通过| M["模幂 sig^19 mod N"] M --> U["去填充与掩码,取 off 处 32 B"] U --> C["32 字节摘要比较"] C -->|不一致| E10["拒绝:返回 0xA"] C -->|一致| P["payload、add-on 与日期校验"] P -->|校验失败| E2["拒绝:返回 2"] P --> OK["通过,许可证生效"]

图 1 的节点与 2.1 节步骤一一对应,拒绝分支的返回码 0、9、0xA、2 与 6.4 节失败分支表一致。

2.3 流程文本版与调用先后

1. 定位许可证文件,模式串加目录列表
   └─ 2. 读取文件内容
      └─ 3. JSON 解析
         ├─ 4. 根节点类型 ≠ object(3) ───────────────► 拒绝:返回 0
         └─ 5. 提取 signature 字符串
            ├─ 6. 十六进制未整串消费 ────────────────► 拒绝:返回 9
            └─ 7. 规范化序列化,排除 header 与 signature
               └─ 8. SHA-256,32 B
                  └─ 9. 种子派生,得到 N、e=19 与门限摘要
                     ├─ 10. 5 道门限任一失败 ────────► 拒绝:返回 0,Invalid input data
                     └─ 11. 模幂 sig^19 mod N
                        └─ 12. 去填充,尾零检查、去掩码、取 32 B
                           ├─ 13. 32 B 摘要不一致 ──► 拒绝:返回 0xA
                           └─ 14. payload 校验,name、email、licenses
                              └─ 15. add-on 与日期校验
                                 └─ 接受:许可证生效
/* sub_100477B70 @0x100477B70 */
if ( (unsigned __int8)sub_1004797D0((__int64 *)&Block, a3, a4, a5, a6) )   /* 先验签 */
    v9 = sub_100479CC0(a1, a2, (unsigned int)&Block, a4, 0, a5);          /* 后解析 payload */
else
    v9 = 2;

签名校验失败时不会进入 payload 字段校验。payload 报 Missing "…" entry 说明验签已经通过。

3 许可证文件与解析

3.1 文件定位与读取

/* sub_1004734E0 @0x1004734E0 */
v10 = a3[1] ? *a3 : String1;
sub_100477620(a1[4], "Looking for file with pattern \"%s\"\n", v10);  /* 0x10047354A */
if ( (unsigned __int64)a3[1] <= 1 ) return 0;
if ( qisabspath(*a3) ) {                                             /* 绝对路径 */
    if ( !(unsigned __int8)sub_100474800(a1, a2, &v27, a3, a4) ) {
        sub_10002CED0(v23, "The file \"%s\" does not contain a valid license", *a3);
    }
} else {                                                             /* 目录加模式串 */
    for ( 每个目录项 v12 ) {
        qmakepath(Str, 0x104, v14, v13, 0);                          /* 0x10047361B */
        if ( sub_100474800(v31, a2, &v27, Block, v30) ) {
            sub_100477620(v17[4], "Found license at path: \"%s\"\n", v9);
            break;
        }
    }
    sub_10002CED0(v23, "No valid license file could be found matching pattern \"%s\"", v9);
}

文件定位不硬编码路径,采用模式串加目录列表,模式串由调用方经 a3 传入。单个文件是否可用由 sub_100474800 判定,该函数读取内容并进入解析链。成功时打印 Found license at path: "%s",路径发现与内容校验在同一函数内完成。

3.2 JSON 结构与根节点

/* sub_1004797D0 @0x1004797D0 */
v13 = parse_json_string(&v24, v12, a4, a5);   /* 0x10047987D */
v29 = 1;
if ( v13 || v24 != 3 ) goto LABEL_20;         /* 解析失败或根不是 object(3) 则返回 0 */
v14 = sub_1004799C0(&v29, v25, a3, a4);       /* 0x1004798AE */

parse_json_string 的类型码 3 表示 object。根节点类型不符时直接返回 0,不进入签名校验。

失败路径另有一个与验签无关的副作用,顶层入口对 payload 首字节做异或,仅用于标记失败:

/* sub_1004797D0 */
v15 = (v29 | BYTE2(v29) | ((unsigned __int16)(v29 | HIWORD(v29)) >> 8) | 1) * (v29 < 0 || v29 > 0);
...
if ( *(_QWORD *)(v17 + 8) > 1u )
    **(_BYTE **)v17 ^= v15;                   /* 0x10047990A */

3.3 signature 提取与十六进制解码

/* sub_1004799C0 @0x1004799C0 */
v8     = sub_10047B2C0();                       /* 运行时拼出 "signature" */
result = sub_100063D00(a2, v8, 2);              /* 必须在顶层,且类型为 string(2) */
sub_10047A700(v42, a2);                         /* 先算规范化摘要 */
if ( *(_DWORD *)v10 != 2 ) { ... interr(0x657); }
v14 = *(_QWORD **)(v10 + 8);
v15 = v14[1];                                   /* 字符串长度,含结尾 NUL */
v17 = (v15 - 1) >> 1;                           /* 字节数 = (len - 1) / 2 */
...
do {
    v44 = 0;
    if ( (unsigned int)qsscanf(v18, "%02X", &v44) != 1 ) break;   /* 0x100479AF9 */
    if ( v44 > 0xFF ) break;
    *v19 = v44; v18 += 2; ++v19;                                /* 每 2 字符 1 字节 */
} while ( v19 != v20 );
if ( v18 == *v14 + v22 ) { ... } else { v13 = 9; }              /* 必须整串消费 */
  • 键名 "signature" 在二进制中无明文字面量,由 sub_10047B2C0 逐字节拼出,strings 搜不到。
  • 支持大小写十六进制,%02X 按值解析;每对字符必须是合法 hex,中途失败或长度不足均落到 v13 = 9。
  • 解码后的字节数作为门限 #5 的右操作数,即 *(a3 + 8)。

4 规范化与摘要

4.1 覆盖范围

/* sub_10047A700 @0x10047A700 */
v5 = (const char *)sub_10047B2C0();             /* "signature" */
if ( strcmp(v7, v5) ) {                         /* 跳过 signature */
    if ( strcmp(v8, "header") ) {               /* 跳过 header */
        /* 其余键值对按键名排序去重收集进 qvector,元素 0x28 B */
        jvalue_t_copy(v10, v3 + 0x18);          /* 0x10047A894 */
    }
}
sub_10047B210(&Src, &v27);                      /* 0x10047A8B7 */
sha256_init(v36); sha256_update(v36, Block, v25); sha256_final(v37, v36);  /* 0x10047A932 至 0x10047A952 */

序列化结果以 NUL 结尾,长度取 v31 - 1 后拷入 Block,SHA-256 输入不含结尾 NUL。

4.2 序列化器与键排序

/* sub_10047B210 @0x10047B210 */
v5 = 3; v6 = a2;
v3 = serialize_json(a1, &v5, 2);                /* 0x10047B258,mode=2 */
if ( v5 != 3 ) { ... interr(0x658); }
if ( v3 ) return a1;
... interr(0xC48);

mode = 2 的语义由递归序列化器 sub_1003B6F70 实现:

方面 行为
键排序 mode 的 bit1 置位时,对键索引数组调用 sub_1003B5FA0,按 strcmp 字典序排序
空白 不输出空格与换行,只有 { } [ ] , : "
整数 "%lld"
浮点 "%lf",并把 locale 的 , 换回 .
布尔与 null true、false、null
对象与数组 递归输出,逗号分隔

4.3 字符串转义规则

/* sub_1003B68B0 @0x1003B68B0 */
switch ( cp ) {
  case 8:  \\b ;  case 9: \\t ;  case 0xA: \\n ;  case 0xC: \\f ;
  case 0xD: \\r ; case 0x22: \\" ; case 0x5C: \\\\ ;
  default:
    if ( is_cp_graphical(cp) )  v11 = v15 - v6;                 /* 原样 UTF-8 字节 */
    else                        qsnprintf(&v16, 0x10, "\\u%04X", cp);  /* 大写 4 位 */
}

可显示字符,含 CJK、emoji 与拉丁扩展,按 UTF-8 原样输出;不可显示字符转 \uXXXX,十六进制大写。外部序列化器必须复现该规则,否则摘要不同。

5 密钥派生与模幂

5.1 种子与派生结构布局

/* sub_10047AAD0 @0x10047AAD0 */
memset(a1, 0, 0xA0u);  memset(a1 + 0x51, 0, 0xBEu);      /* 0x10047AB05 / 0x10047AB19 */
v4 = 0xFFFFFFFFFFFFFFBAuLL;                              /* -70 */
do {
    a1[((_BYTE)v4 + 0x11) & 0x3F] = word_101A3F3B0[v3]
        ^ (0x9F3B * v3) ^ (0xEB2D * (((_BYTE)v4 + 0x11) & 0x3F)) ^ 0x79B9
        ^ (((0x45D9F3B * (_DWORD)v3)
            ^ (0x27D4EB2D * (((_BYTE)v4 + 0x11) & 0x3F)) ^ 0x9E3779B9) >> 0x10);
    /* 15 个常规 lane 加 1 个特例 lane,参数在 5.2 节 */
    v4 -= 0x1B0; v3 += 0x10;
} while ( v3 < 0x40 );
a1[0x50] = 0x13;                                         /* 0x10047AE29,e = 19 */
qmemcpy(v13, "hexrays-local-license-rsa-v1", 0x1C);      /* 0x10047AE32 */
sha256_init(v12, ...);
sha256_update(v12, v13, 0x1C);
for ( i = 0; i < 0x50; ++i ) { v10 = a1[i + 0x50]; sha256_update(v12, &v10, 2); }
do { v10 = a1[v2]; sha256_update(v12, &v10, 2); ++v2; } while ( v2 < 0x50 );
return sha256_final(a1 + 0xA0, v12);                     /* 0x10047AEFB,字节 +0x140 */
偏移 长度 内容 写入点
+0x00 128 B N:64 个 16-bit limb,小端存放,a1[0] 为最低 16 位 4 × 16 lane 循环
+0x80 32 B 全 0 0x10047AB05 的 memset
+0xA0 160 B 指数区:a1[0x50] = 0x13,其余全 0,即 e = 19 0x10047AE29
+0x140 32 B SHA-256 摘要,门限数据源 0x10047AEFB
flowchart TB subgraph S1["0x160 派生结构"] A0["+0x00:128 B 模数 N"] A80["+0x80:32 B 零区"] AA0["+0xA0:160 B 指数 limb,a1[0x50]=0x13,e=19"] A140["+0x140:32 B 门限摘要"] A0 --> A80 --> AA0 --> A140 end subgraph S2["127 B 签名块"] B0["[0..95):95 B 掩码区"] B1["[95..127):32 B payload 摘要"] B0 --> B1 end subgraph S3["348 B 门限摘要输入"] C1["28 B 前缀字符串 hexrays-local-license-rsa-v1"] C2["160 B struct[0xA0:0x140)"] C3["160 B struct[0x00:0xA0)"] C1 --> C2 --> C3 end C3 -->|SHA-256| A140

图 2 的三个分区分别对应 0x160 派生结构、127 B 签名块与 348 B 门限摘要输入。+0x140 摘要由 348 B 输入按 SHA-256 得到;签名块 [95..127) 的 32 B 是规范化 payload 的摘要,与 +0x140 门限摘要不同源。

结构文本版,偏移自低到高:

+0x00   ┌──────────────────────────────────────────┐
        │ 128 B  模数 N,64 个 16-bit 小端 limb     │
+0x80   ├──────────────────────────────────────────┤
        │  32 B  保留区,全 0,memset @0x10047AB05  │
+0xA0   ├──────────────────────────────────────────┤
        │ 160 B  指数 limb 区,首 limb 0x0013,e=19 │
+0x140  ├──────────────────────────────────────────┤
        │  32 B  门限摘要,SHA-256 @0x10047AEFB     │
+0x160  └──────────────────────────────────────────┘

摘要输入共 348 B:"hexrays-local-license-rsa-v1" 占 28 B,加 struct[0xA0:0x140) 共 160 B,加 struct[0x00:0xA0) 共 160 B。

两种种子的复算结果:

种子 派生 N 前 8 字节 +0x140 摘要 digest[3] ^ 0xFB digest[7] ^ 0xEF digest[0x13] ^ 0xC2
PATCH_SEARCH edfd425cf978546e… 94da4a7b764b08cf0a87ec7f45a0ffd1d0e84d82d77cde24baa4f28bfff09178 128 32 64
PATCH_REPLACE 3f0307607fed562f… 767d897ba9877fb08332997f9db5e3ae613136bd486bddb78bb6c645146ea602 128 95 127

5.2 lane 参数

每轮 v3 以 16 递增,v4 以 -0x1B0 递减;索引为 idx = ((v4 & 0xFF) + delta) & 0x3F。

lane j delta 常数 A 符号
0 0x11 0x0000 +
1 -0x0A 0x60C5 −
2 0x1B 0x3E76 +
3 0x00 0x224F −
4 -0x1B 0x7CEC +
5 0x0A 0x1C27 +
6 -0x11 0x449E −
7 0x14 0x5A9D +
8 -0x07 0x0628 −
9 0x1E 0x66ED −
10 0x03 0x384E +
11 -0x18 0x2877 −
12 0x0D 0x76C4 +
13 -0x0E 0x15FF +
14 0x17 0x4AC6 +
15 -0x04 0x5475 特例公式

特例 lane 的实现不是同一模板:

/* 0x10047ADED 附近 */
v6 = ((_BYTE)v4 - 4) & 0x3F;
v7 = word_101A3F3B0[v3 + 0xF]
   ^ (((0x27D4EB2D * (_DWORD)v6) ^ ((_DWORD)v5 + 0x417C5475) ^ 0x9E3779B9) >> 0x10);
a1[v6] = (0xEB2D * v6) ^ (v5 + 0x5475) ^ 0x79B9 ^ v7;

5.3 e=19 的来源与断言

/* 0x10047AE29 */
a1[0x50] = 0x13;

a1 为 _WORD *,a1[0x50] 即派生结构 +0xA0 的首个 16-bit limb,写入 0x0013;其余指数 limb 由 memset 清零,因此公钥指数为 19。复算断言:pow(pow(m, d, N), 19, N) == m 对多个 m 成立,N 与 d 均按小端解释;换成 e=65537 不成立。

5.4 模幂调用与参数

/* sub_1004780B0,调用点 0x1004781A2 */
v10 = sub_100480A10(Src, (__int64)v25, (__int64)v24);

v25 位于 rbp + 0x10,即派生结构 +0xA0 的指数区;v24 是派生结构基址,+0x00 为 N。函数原型为 6 参数,Hex-Rays 在调用点只显式给出 3 个表达式,其余寄存器实参未展开。

/* sub_100480A10 @0x100480A10 */
__int64 __fastcall sub_100480A10(void *a1, unsigned __int64 a2, const void *a3,
                                 size_t a4, __int64 a5, __int64 a6)
{
  qmutex_lock(qword_102048B08);
  word_1020488D0 = 0x50;                         /* 工作精度 80 limb,160 B */
  memset(Src, 0, sizeof(Src));
  memset(v25, 0, sizeof(v25));
  if ( a4 > 0xA0 ) { ... interr(0xCAD); }        /* 输入块上限 160 B */
  memcpy(v25, a3, a4);
  v11 = sub_100480C20(v24, v25);                 /* 16-bit limb 平方乘 */
  ...
  v16 = 2 * word_1020488D0;                      /* 160 B */
  v18 = sub_1004809B0(a6);                       /* 模数位长 */
  v20 = v19 - ((v18 + 7) >> 3) + 1;              /* 160 - ceil(bits/8) + 1 */
  v21 = &v24[v20];
  if ( &v24[v16] >= &v24[v20] ) { memcpy(...); } /* 右对齐截取 */
}
  • 该运算为标准 RSA 公钥模幂,不是椭圆曲线签名。
  • 工作缓冲固定 160 B,按 16-bit limb 计算;指数为 19,即 0b10011,平方乘只需 5 轮。
  • 输出按 160 - ceil(bits(N)/8) + 1 字节右对齐,多出的高位字节在 6.1 做尾零检查。

6 去填充与门限

6.1 掩码几何与 127 字节块布局

/* sub_1004780B0 @0x1004780B0 */
v10 = sub_100480A10(Src, (__int64)v25, (__int64)v24);  /* 0x1004781A2 */
v11 = v10;                                           /* 0x1004781B7 */
if ( v10 < 0 || v10 < v9 ) goto LABEL_19;
if ( v10 > v9 ) {                                    /* 0x1004781BB,尾零检查 */
    v12 = v9;
    while ( !Src[v12] ) { if ( ++v12 >= v11 ) goto LABEL_12; }
    goto LABEL_19;                                   /* [v9, v10) 内出现非零则失败 */
}
LABEL_12:
memcpy(v19, Src, v9);                                /* 0x100478230,只取前 v9 字节 */
for ( ... ) {                                        /* 0x100478288,去掩码 */
    *((_BYTE *)v19 + v14) ^= v25[(v14 & 0x1F) + 0xA0]
                           ^ byte_101A3F430[v14 & 0x1F]
                           ^ (((0x1B873593 * (v14 & 0x1F)) ^ 0xA5C35A71
                               ^ (((0x1B873593 * (v14 & 0x1F)) ^ 0xA5C35A71) >> 0xD))
                              >> (8 * ((unsigned __int8)v14 & 3u)));
}
*a2 = v22;  a2[1] = v23;                             /* 0x1004782CD/D6,返回 (v8, off, 0x20, v9) */
LABEL_19:
sub_10002B750(a4, "Invalid input data", 0x12);       /* 0x1004782F2 */
return 0;                                            /* 0x100478307 */
  • v25 基址是 struct + 0xA0,因此 v25[(i & 0x1F) + 0xA0] 等于 struct + 0x140 + (i & 0x1F),即 digest[i & 0x1F]。
  • 掩码第 3 项 ((0x1B873593 * k) ^ 0xA5C35A71) >> 13 中,0x1B873593 * k 是 32-bit imul,必须截断到 32 位;不截断时高位参与右移,得到的掩码字节不同。
  • 去掩码后 v19 的前 v9 字节为 off 字节前缀加 32 B 摘要,off = digest[7] ^ 0xEF,门限 #2 强制 v9 = off + 0x20。
  • 掩码常量:byte_101A3F430 为 ff47838cb779e0aa34af62f47e4259e8118d0d2c417d84f8716a89c9ce678e88;PADKEY 为 e2a7c300dfcc777f89b57500d8151c7fb1d97b3f9f170393311234ceeb9e377a,32 B 重复 3 次后接前 31 B,共 127 B。
  • PATCH_REPLACE 种子给出 off = 95、v9 = 127,mask(digest) == PADKEY[:127];原版 PATCH_SEARCH 给出 off = 32、v9 = 64,mask(digest) == 0。
  • 127 B 签名块由 [0..95) 的 95 B 掩码区与 [95..127) 的 32 B payload 摘要区构成,两段布局在图 2 给出。

调用者取摘要:

/* sub_1004799C0 */
if ( sub_1004780B0((__int64)Block, &v39, (__int64)&v32, v45) ) {
    v24 = (char *)Block[0] + *((_QWORD *)&v39 + 1);   /* Block[0] + off */
    memcpy(v29, v24, Size);                           /* Size = 0x20,32 B 摘要 */
} else { v13 = 0xA; }

6.2 摘要比较

/* sub_100478330 @0x100478330 */
v5 = v4 ^ v2;                                    /* 先异或长度 */
for ( i = 0; i < 0x20; i += 8 ) {                /* 32 B,每 8 字节一组 */
    /* 逐字节:越界取 0 或 ~0,异或后 OR 进 v5,无分支 */
    v5 |= ...;
}
return v5;                                       /* 0 表示完全一致 */

长度不同或任一字节不同均返回非 0,比较过程无短路分支。

6.3 五道门限

/* sub_1004780B0,0x1004781B5 */
v8 = v26 ^ 0xFBLL;                                   /* digest[3] ^ 0xFB */
v9 = v29 ^ 0xC2LL;                                   /* digest[0x13] ^ 0xC2 */
if ( v28 != 0x7F                                     /* #1 digest[0x0B] == 0x7F */
  || (v27 ^ 0xEFLL) + 0x20 != v9                     /* #2 off + 0x20 == v9 */
  || v9 > 0xA0                                       /* #3 块长 <= 160 */
  || v8 > 0xA0                                       /* #4 签名长度 <= 160 */
  || *(_QWORD *)(a3 + 8) != v8 )                     /* #5 签名字节数 == v8 */
    goto LABEL_19;
# 条件 数据来源 性质
1 v28 == 0x7F,即 digest[0x0B] == 0x7F +0x14B 固定常量,8 bit
2 (v27 ^ 0xEF) + 0x20 == v9 digest[7]、digest[0x13] 摘要内关系式,8 bit
3 v9 <= 0xA0 digest[0x13] ^ 0xC2 范围,明文缓冲 160 B
4 v8 <= 0xA0 digest[3] ^ 0xFB 范围,签名缓冲 160 B
5 *(a3 + 8) == v8 signature 解码字节数 可自洽,hex 长度可控

6.4 失败分支与返回码

位置 条件 行为与返回
sub_1004780B0 @0x1004782F2 任一门限失败、sub_100480A10 返回小于 0、返回长度小于 v9、尾零检查失败 写 Invalid input data,返回 0
sub_1004799C0 @0x100479B2E hex 未整串消费 v13 = 9
sub_1004799C0 @0x100479B7D sub_1004780B0 返回 0 v13 = 0xA
sub_1004799C0 @0x100479C2A sub_100478330 返回非 0 *a1 置非 0,与 v13 合并,`v28
sub_1004799C0 @0x100479A33 找不到 signature 且未置可选标志 写 Invalid input data,返回 9
sub_1004797D0 LABEL_20 JSON 解析失败或根不是 object 返回 0
sub_100479CC0 各分支 payload 缺键、类型错误、版本不支持 返回 2,并写 Missing … 或 Missing, or unsupported version: %lld

Invalid input data 在两处被引用,即 0x1004782F2 与 0x100479A33;仅凭该文案不能区分缺 signature 与验签失败。

7 字段与显示

7.1 payload 骨架与容器字段

/* sub_100479CC0 @0x100479CC0 */
/* header 必须是 object(3) */
if ( *(_DWORD *)(v11 + 0x28 * v10 + 0x18) != 3 )
    { sub_10002B750(v77, "Missing \"header\" entry", 0x16); return 2; }
/* header.version 必须是 int(1) */
if ( *(_DWORD *)(v17 + 0x28 * v15 + 0x18) != 1 )
    { sub_10002B750(v77, "Missing \"version\" entry", 0x17); return 2; }
v20 = *(_QWORD *)(v17 + 0x28 * v15 + 0x20);
v21 = v20 == 1;
if ( v20 != 1 && a4 < 0 ) { v21 = (v20 == 0); v8 = (v20 == 0); }
if ( !v21 ) { sub_10002CED0(v77, "Missing, or unsupported version: %lld", v20); return 2; }
/* 版本 1 走 payload,版本 0 且 a4 < 0 走旧 data 分支 */
/* payload 内 name 与 email 必须为 string(2) */
/* payload 内 licenses 必须为 array(4),每项为 object(3) */
if ( !strcmp(v62, "licenses") ) break;
if ( *v63 != 4 ) { sub_10002B750(v77, "Missing \"licenses\" entry", 0x18); return 2; }

每个 license 条目在循环内解析并拷贝到 0x98 字节记录:

/* sub_100479CC0 */
if ( *(_DWORD *)v65 != 3 ) { sub_10002B750(v67, "Badly formatted license entry", 0x1D); ... }
if ( sub_100478940(&v77, &v93, *(_QWORD *)(v65 + 8), v67) ) {
    ... qvector_reserve(..., 0x98) ...
    sub_10047B440(v70, &v93);      /* 0x10047A3CE */
} else { v71 = v77; if ( v71 ) break; }
层级 键 类型 必需 读取与校验 报错文案 约束与行为
根 header object(3) 是 sub_100479CC0 Missing "header" entry payload-only 模式 a5 != 0 时跳过
根 header.version int(1) 是 值必须为 1;a4 < 0 时允许 0 并转旧 data 分支 Missing "version" entry;Missing, or unsupported version: %lld 9.5 固定写 1
根 payload object(3) 是 sub_100479CC0 Missing "payload" entry v1 容器的正文
根 signature string 是 sub_100477B70 → sub_1004799C0 Invalid input data;文件报 doesn't appear to be a valid license file 每 2 字符 %02X 解 1 字节,整串消费
payload name string(2) 是 仅作为被许可人显示 Missing "name" entry,类型不符也报此文案 用户可见,Licensed to:
payload email string(2) 是 仅作为被许可人显示 Missing "email" entry,类型不符也报此文案 用户可见,<…>
payload licenses array(4) 是 逐项 sub_100478940 Missing "licenses" entry;Badly formatted license entry 元素必须为 object(3),空数组合法
payload product string 否 无读取点 — 模板残留,对引擎无作用

7.2 license 与 add-on 字段

/* sub_100478530 @0x100478530 */
v27 = sub_1000647C0(v44);
if ( !(unsigned __int8)sub_1000646A0(a2, v28) )
    { sub_10002CED0(a4, "Invalid license ID: \"%s\"", v28); *a1 = 2; return 0; }
v31 = sub_100477C70(v30);  *(_DWORD *)(a2 + 8) = v31;  if ( !v31 ) return 0;   /* 0x1004787F0,无文案 */
if ( !(unsigned __int8)sub_1000646A0(a2 + 0xC, v33) )
    { sub_10002CED0(a4, "Invalid owner license ID: \"%s\"", v33); *a1 = 2; return 0; }
v37 = sub_10047B5C0(a2 + 0x18, Block);            /* start_date */
if ( !v37 ) { sub_10002CED0(a4, "Invalid start date: \"%s\"", v10); *a1 = 2; return 0; }
if ( sub_10047B680(a2 + 0x20, v26) ) return 1;    /* end_date */
sub_10002CED0(a4, "Invalid end date"); *a1 = 2; return 0;

add-on 的 5 个键全部必需;id、code、owner、start_date 必须为 string,end_date 允许 string 或 null。code 经 sub_100477C70 解析为数值写入 a2 + 8,解析为 0 时无文案直接失败,位置在 0x1004787F0。

记录 键 类型 必需 校验与消费 报错文案 记录偏移 行为与约束
license id string(2) 是 sub_1000646A0 Invalid license ID: "%s" +0x00,6 B 6 段十六进制,License info: 显示源
license license_type string(2) 是 字符串映射 Invalid license type: "%s" +0x08 named=1、computer=2、floating=3;floating 影响 is_floating_license
license product_id string(2) 是 字符串映射 未知值无文案,直接失败 +0x0C IDA 视作 IDAPRO;IDAPRO=1、IDAHOME=2、IDAFREE=3、TEAMS_SERVER=4、LUMINA_SERVER=5、LICENSE_SERVER=6
license edition_id string(2) 是 字符串映射与 Home 约束 Invalid edition: "%s";Invalid IDA Home edition +0x10 ida-pro=1、ida-pro-classroom=2、ida-home-pc=3、ida-home-arm=4、ida-home-mips=5、ida-home-ppc=6、ida-home-riscv=7、ida-free=8、teams-server=9、lumina-server=10、license-server=11、ida-home=12;product_id == 2 时只允许 3 至 7 或 12
license product_version string(2) 是 %d.%d%n 整串消费 Invalid product version: "%s" +0x14 major * 100 + minor,经 get_license_product_version 暴露
license description string(2) 是 复制 Wrong data for "%s";Missing "%s" key +0x80 经 get_license_description 暴露
license seats int(1) 是 JSON 整数转 qword Wrong data for "%s" +0x18 原样存储,本地校验路径未使用
license start_date string(2) 是 %d-%d-%d Invalid start date: "%s" +0x68 UTC 时间戳,经 get_license_start 暴露
license end_date string(2) 或 null(6) 是 %d-%d-%d,null 记 0 Invalid end date +0x70 null 表示无到期时间
license issued_on string(2) 是 %d-%d-%d %d:%d:%d,必须 6 段 Invalid issued timestamp: "%s" +0x78 仅存储与暴露,get_license_issued_on;未见有效性比较分支
license owner string(2) 是 仅复制,无校验 类型不符报 Wrong data for "owner" +0x20 不显示、不参与任何判定,7.4 节给出语义
license add_ons array(4) 否 逐项 sub_100478530 Invalid add-on entry +0x38,vector,stride 0x28 见下方 add-on 行
license features array(4) 否 逐项必须 string(2) Features should only be strings +0x50,vector 空数组合法;非空时 has_valid_feature 按名匹配
add-on id string(2) 是 sub_1000646A0 Invalid license ID: "%s" +0x00,6 B 6 段十六进制
add-on code string(2) 是 sub_100477C70 解析为 0 时无文案直接失败 +0x08 受支持的 add-on 名称枚举
add-on owner string(2) 是 sub_1000646A0 Invalid owner license ID: "%s" +0x0C,6 B 必须为 6 段十六进制 ID,惯例填父许可的 id
add-on start_date string(2) 是 sub_10047B5C0 Invalid start date: "%s" +0x18 %d-%d-%d
add-on end_date string(2) 或 null(6) 是 sub_10047B680 Invalid end date +0x20 null 表示无到期时间

7.3 记录布局与日期解析

偏移 内容 导出访问器与使用点
+0x00,6 B id get_license_id_buf @0x101658300、get_license_ids_buf;sub_10005E3F0 的 License info:
+0x08 license_type,1 至 3 is_floating_license,== 3
+0x0C product_id,1 至 6 get_license_product
+0x10 edition_id,1 至 12 get_license_edition
+0x14 product_version get_license_product_version
+0x18 seats 无导出访问器
+0x20,0x18 B owner,std::string 无访问器、无读取点
+0x38,0x18 B add_ons,vector,stride 0x28 get_valid_add_ons_buf、has_valid_add_on
+0x50,0x18 B features,vector get_valid_features_buf、has_valid_feature
+0x68 start_date get_license_start
+0x70 end_date get_license_end
+0x78 issued_on get_license_issued_on
+0x80,0x18 B description,std::string get_license_description

sub_10047B440 @0x10047B440 只做记录字段交换,对 +0x20、+0x38、+0x50、+0x80 调用 std::swap,不含语义判断。

/* sub_10047B5C0 @0x10047B5C0,start_date */
if ( (unsigned int)qsscanf(v3, "%d-%d-%d", &v5, &v6, &v7) != 3 ) return 0;
Tm.tm_year = v5 - 0x76C;  Tm.tm_mon = v6 - 1;  Tm.tm_mday = v7;
*a1 = qtimegm(&Tm);       /* 0x10047B660,按 UTC 解释 */
return 1;
/* sub_10047B680 @0x10047B680,end_date */
if ( *(_DWORD *)a2 == 2 ) {                        /* string */
    if ( qsscanf(v5, "%d-%d-%d", &v12, &v13, &v14) == 3 ) {
        ... *a1 = qtimegm(&Tm); v11 = 1;
    } else v11 = 0;
    return v11;
} else if ( *(_DWORD *)a2 == 6 ) {                 /* null,视为无到期时间 */
    *a1 = 0; return 1;
} else return 0;                                   /* 其它类型非法 */
  • 日期只接受 YYYY-MM-DD,即 %d-%d-%d,并经 qtimegm 转为 UTC 时间戳。
  • 主许可 end_date 同样只按 %d-%d-%d 解析,字符串中的时间部分被忽略,例如 2099-12-31 23:59:59 只取日期。
  • end_date 允许为 null,类型 6,表示无到期时间。
  • features 为空数组合法,引擎仍读取该键并得到空集合;非空时按字符串精确匹配。
  • issued_on 必须可解析为 YYYY-MM-DD HH:MM:SS,仅存储与暴露。
  • 这两个日期函数只做格式到时间戳的解析;到期比较不在这两个函数内。

7.4 owner 与 id 的显示语义

licenses[].owner 不出现在任何用户可见文本。身份显示只由 sub_10005E3F0 @0x10005E3F0 生成,共有三处格式串:

/* sub_10005E3F0 */
/* 1) 在许可记录向量中按 6 字节 id 匹配,记录 stride 0x98 */
while ( *(_DWORD *)v9 != v6 || *((_WORD *)v9 + 2) != v7 ) v9 += 0x98;   /* 0x10005E559 */
/* 2) 用匹配记录的前 6 字节 record + 0x00 格式化 License info */
sub_10002CED0(Block, "%02X-%02X%02X-%02X%02X-%02X", *v8, v8[1], v8[2], v8[3], v8[4], v8[5]); /* 0x10005E5CA */
qsnprintf(v69, 0x400, "License info: %s", v13);                        /* 0x10005E5E4 */
/* 3) 被许可人来自 licenses 解析输出的 name 与 email,即 payload.name 与 payload.email */
qsnprintf(v69, 0x400, "%s <%s>", v12, v22);                            /* 0x10005E6E4 */

回退路径在 netnode $ original user 只有字符串建议值时使用,由 sub_1004819B0 填出的用户信息结构提供数据:+0x1C 的 6 字节 id 走 License info: %s,+0x22 的文本走 Licensed to: %s,位置 0x10005EB55。两条路径都不读取记录 +0x20。

导出访问器侧同样没有 owner:get_license_id_buf 用 record + 0x00 格式化为 %02X-%02X%02X-%02X%02X-%02X,位置 0x101658300;get_license_description、edition、end、issued_on、product、product_version、start 分别读 +0x80、+0x10、+0x70、+0x78、+0x0C、+0x14、+0x68。ida.dll 未导出任何 owner 访问器。

位置 语义 校验 安全取值
licenses[].owner 自由字符串元数据,被许可方备注 只要求键存在且为 string,原样存入 +0x20 任意字符串,包括 auth、自定义文本、空串;不会因取值被拒
add_ons[].owner 该 add-on 归属的许可 ID sub_1000646A0,格式 %02X-%02X%02X-%02X%02X-%02X,sscanf 必须返回 6 必须为 6 段十六进制 ID,惯例等于父许可 id,如 14-0000-FFFF-88;auth 报 Invalid owner license ID
  • licenses[].owner 位于签名覆盖的 payload 内,改动后必须重新签名,否则验签失败。
  • 模板 idapro.hexlic 中 payload.name 与 licenses[0].owner 同为 auth;实际显示取 payload.name。
  • add-on 校验层未把 owner 与父许可 id 做一致性比较;get_valid_add_ons_buf @0x101658690 只按 code 与起止时间判定,owner 仅被解析存储。

8 签发与补丁

8.1 可签发方案

4 份 128 B 种子整块替换为 PATCH_REPLACE,其 derive 结果为 C_MODULUS,配同一派生结构中的 e=19 与对应私钥签发许可证。PATCH_REPLACE 前 8 字节为 a107b71c8a08ba53…,C_MODULUS 前 8 字节为 3f0307607fed562f…;其余字节由派生与签发计算确定,正文不展开全量十六进制。

C_MODULUS 的 +0x140 摘要为 767d897ba9877fb08332997f9db5e3ae613136bd486bddb78bb6c645146ea602,满足全部 5 道门限:v8 = 128、off = 95、v9 = 127。私钥与模数按小端解释,pow(pow(m, d, N), 19, N) == m 成立;pow(sig, 19, N) 去掩码后得到 127 B 明文,[0:95) 全 0,[95:127) 等于 SHA-256(canonical payload),digest_match = True。

8.2 4 处种子偏移与补丁

DLL 副本 文件偏移 VA
ida.dll #1 0x1A3E7B0 0x101A3F3B0
ida.dll #2 0x1A3F640 0x101A40240
ida32.dll #1 0x5453F0 0x1005463F0
ida32.dll #2 0x546280 0x100547280

四处各写入同一份 128 B PATCH_REPLACE,其余字节不动。

keygen

alt text

"""IDA Pro 9.5 license key generator and DLL seed patcher.

The generated ``idapro.hexlic`` file is signed exactly the way the IDA
verifier expects:

  * canonical JSON: sorted keys, no whitespace, compact "," / ":" separators,
    graphical code points emitted as raw UTF-8, everything else as \\uXXXX
    (upper case),
  * SHA-256 over the payload is expanded into a 127-byte block: the first
    95 bytes are PADKEY, bytes 95..126 are PADKEY XOR digest,
  * RSA over that block with PRIVATE_KEY and C_MODULUS, ``pow(m, d, n)``,
  * the public exponent hard-coded by the verifier is 19 (0x13), not 65537.

The patch page locates the 128-byte seed blobs inside ``ida.dll`` / ``ida32.dll``
by re-running the verifier's own derivation over every window and comparing the
derived modulus with C_MODULUS (and with the factory modulus derived from the
shipped seed).  Only a window that derives to one of those moduli is accepted as
a seed copy, so nothing is patched on a literal match alone.

Usage:
  python keygen_gui.py              launch the GUI
"""

import calendar
import datetime as _dt
import hashlib
import json
import os
import re
import shutil
import sys
import unicodedata

# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
PRODUCT_VERSION = '9.5'          # display label; only licenses[0].product_version carries it
START_TIME = '00:00:00'
END_TIME = '23:59:59'
DATE_FMT = '%Y-%m-%d %H:%M:%S'

SEAT_MIN = 1
SEAT_MAX = 1000
OWNER_MAX = 64
EMAIL_MAX = 254
YEAR_MIN = 2000
YEAR_MAX = 2099

LICENSE_ID = '14-0000-FFFF-88'
ADDON_ID_FMT = '48-1337-B00B-%02d'
ADDON_MAX = 64
PRESET_YEARS = (1, 3, 5)
PRESET_FIXED_DATE = (2099, 12, 31)

# ---------------------------------------------------------------------------
# Runtime locations.  No absolute path is hard-coded anywhere: the script
# directory comes from ``__file__`` and the IDA directory is auto-detected or
# chosen by the user.  Change nothing here unless the file names change.
# ---------------------------------------------------------------------------
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
LICENSE_OUTPUT_NAME = 'idapro.hexlic'
CONFIG_FILE_NAME = 'keygen_config.json'
LOG_FILE_NAME = 'keygen.log'
FALLBACK_STATE_DIR_NAME = '.keygen'
TARGET_IDA_VERSION = (9, 5)

CONTAINER_VERSION = 1

# Strict identifier shape accepted by the engine for license and add-on IDs.
LICENSE_ID_PATTERN = r'^[0-9A-Fa-f]{2}(?:-[0-9A-Fa-f]{4}){2}-[0-9A-Fa-f]{2}$'
LICENSE_ID_RE = re.compile(LICENSE_ID_PATTERN)

# Single-valued fields are rendered read-only; multi-valued ones stay dropdowns.
FIXED_PRODUCT = 'IDA'
PRODUCT_ID_CHOICES = ('IDAPRO', 'IDAHOME', 'IDAFREE', 'TEAMS_SERVER',
                      'LUMINA_SERVER', 'LICENSE_SERVER')
EDITION_CHOICES = ('ida-pro', 'ida-pro-classroom', 'ida-home-pc', 'ida-home-arm',
                   'ida-home-mips', 'ida-home-ppc', 'ida-home-riscv', 'ida-free',
                   'teams-server', 'lumina-server', 'license-server', 'ida-home')
LICENSE_TYPE_CHOICES = ('named', 'computer', 'floating')
TEXT_FIELD_MAX = 64
DESCRIPTION_MAX = 64
FEATURE_MAX_ITEMS = 32
FEATURE_MAX_LEN = 64

C_MODULUS = bytes.fromhex(
    "3f0307607fed562fd5a163adc40fcc603373caa28414e64cdc4552a555b13ad4b"
    "3ad0a812800a03195300fd71634b90edb0d69ea710efebb2b0b9e72da2effb149de7"
    "0bcbfa94b86af01ce455dbbd5fa987207651c7b60c2e4cafd0654188d98c30f64dc"
    "084d8547f0ac32db91124af82b3b15bf922a31f1d5e332f27615cea7"
)

PRIVATE_KEY = bytes.fromhex(
    "8b3f5fdfad7f87239734c530e2ecebeb4fa48d79518756c15fd54636801cf7ea6"
    "367100566bf8b52b16bec05258d8426ea94c15841ab2d37802c07349df4c208584"
    "e86d25a6bfb82966cb2ddcd3d654e9994e814ca470577362a937cc984e404a0b68"
    "d173aab3180130118e1b03ed209a9d8757560a85a3c9b0d3380e7907c4f"
)

PADKEY = bytes.fromhex(
    "e2a7c300dfcc777f89b57500d8151c7fb1d97b3f9f170393311234ceeb9e377a"
    "e2a7c300dfcc777f89b57500d8151c7fb1d97b3f9f170393311234ceeb9e377a"
    "e2a7c300dfcc777f89b57500d8151c7fb1d97b3f9f170393311234ceeb9e377a"
    "e2a7c300dfcc777f89b57500d8151c7fb1d97b3f9f170393311234ceeb9e37"
)

E_PUBLIC = 19                    # verifier hard-codes 0x13 at +0x50 of its seed struct

# Seed blobs and patch bookkeeping -----------------------------------------
PATCH_SEARCH = bytes.fromhex(
    "29f4481f796f9f66f2ff13cc4ab5b54f60845db603ba2c0bac8a9bc4b6cbdefc"
    "5c62bfc2f5ee850ac45ea97ad347e8b56dba5085af8c8aad9cc2ec626ca78a068"
    "006d658f68651da31a0a77c65a70ed73a40d53b08edd403c095aa0bcffa52f313"
    "ebcacaaa2ce5024a4e2b9aa70fc6092f38ae094d71e43f7690b5ddd3e9e4f7"
)

PATCH_REPLACE = bytes.fromhex(
    "a107b71c8a08ba5350934f7cf6e81be3a24dc2e35f7200d80cbd70b37ed6811d"
    "d2146d3cb7e20ad19b2544c0ef14c5c66ffbbdf226ec3f3d544c04385303ca4a"
    "7179299340022f5d50948bcf8a60307e2c196329e51a5296dc419e40fef3ef7c"
    "6f015a09ebd979e79615338985643e666c14897f9f597e11f44341f496d56861"
)

SEED_SIZE = 128                  # one seed copy is exactly 128 bytes

PATCH_FILE_NAMES = ('ida.dll', 'ida32.dll')
BACKUP_DIR_NAME = 'backup'
MANIFEST_SUFFIX = '.json'

STATE_TARGET = 'target'
STATE_FACTORY = 'factory'
STATE_UNKNOWN = 'unknown'
STATE_LABELS = {
    STATE_TARGET: '已是目标种子',
    STATE_FACTORY: '原厂种子(需替换)',
    STATE_UNKNOWN: '未识别',
}
STATE_TAGS = {
    STATE_TARGET: 'state_target',
    STATE_FACTORY: 'state_factory',
    STATE_UNKNOWN: 'state_unknown',
}

# The affine scan key is a slice of the reconstructed preimage; the slice
# offsets are derived, not copied from a literal.
_SEED_FILTER_START = 56
_SEED_FILTER_LEN = 8

DEFAULT_ADDONS = [
    'LUMINA', 'TEAMS', 'HEXX86', 'HEXX64', 'HEXARM', 'HEXARM64',
    'HEXMIPS', 'HEXMIPS64', 'HEXPPC', 'HEXPPC64', 'HEXRV', 'HEXRV64',
    'HEXARC', 'HEXARC64', 'HEXV850', 'HEXDALVIK', 'HEXTRICORE',
    'HEXQDSP6', 'MALWARE',
]

PALETTE = {
    'window': '#eef1f6',
    'panel': '#ffffff',
    'text': '#171b24',
    'muted': '#4c5566',
    'border': '#c4cedb',
    'accent': '#1b4f8a',
    'accent_hover': '#2a6bb0',
    'chip': '#e7eef7',
    'error': '#a3122b',
    'error_bg': '#fdf0f2',
    'ok': '#16603a',
    'warn': '#8a5300',
    'status_bg': '#dfe5ee',
    'log_bg': '#f8fafc',
}

FIELD_ORDER = ('name', 'owner', 'email', 'license_id', 'product', 'product_id',
               'edition_id', 'license_type', 'description', 'issued_on',
               'seats', 'start', 'end', 'features', 'addons', 'install_dir', 'path')
FIELD_LABELS = {
    'name': '名称 (payload.name)',
    'owner': '所有者 (licenses[0].owner)',
    'email': '邮箱',
    'license_id': '许可证 ID',
    'product': '产品',
    'product_id': '产品 ID',
    'edition_id': '版本 ID',
    'license_type': '许可证类型',
    'description': '描述',
    'issued_on': '签发时间',
    'seats': '席位数',
    'start': '生效日期',
    'end': '到期日期',
    'features': '特性',
    'addons': '附加组件',
    'install_dir': 'IDA 安装目录',
    'path': '输出路径',
}

# Editable UI presets.  Users may change them; invalid edits are still rejected.
SHELL_DEFAULTS = {
    'name': 'ikun',
    'email': 'kunkun@ikun.com',
    'license_id': LICENSE_ID,
    'product': FIXED_PRODUCT,
    'product_id': 'IDAPRO',
    'edition_id': 'ida-pro',
    'license_type': 'named',
    'description': 'license',
}

# ---------------------------------------------------------------------------
# Canonical JSON (byte-identical with IDA)
# ---------------------------------------------------------------------------
_NON_GRAPHICAL_CATEGORIES = {'Cc', 'Cf', 'Cs', 'Co', 'Cn', 'Zl', 'Zp'}
_FORBIDDEN_CATEGORIES = {'Cc', 'Cf', 'Cs', 'Co', 'Cn'}
_CONTROL_ESCAPES = {8: '\\b', 9: '\\t', 10: '\\n', 12: '\\f', 13: '\\r', 0x22: '\\"', 0x5C: '\\\\'}


def ida_escape_string(value):
    """Quote a string the way IDA does: raw UTF-8 unless the code point is not graphical."""
    out = []
    for ch in value:
        code_point = ord(ch)
        if code_point in _CONTROL_ESCAPES:
            out.append(_CONTROL_ESCAPES[code_point])
        elif unicodedata.category(ch) in _NON_GRAPHICAL_CATEGORIES:
            out.append('\\u%04X' % code_point)
        else:
            out.append(ch)
    return '"' + ''.join(out) + '"'


def canonical_json(obj):
    """Serialize with sorted keys and no whitespace."""
    if isinstance(obj, list):
        return '[' + ','.join(canonical_json(item) for item in obj) + ']'
    if isinstance(obj, dict):
        return '{' + ','.join('"' + key + '":' + canonical_json(obj[key])
                             for key in sorted(obj.keys())) + '}'
    if isinstance(obj, str):
        return ida_escape_string(obj)
    if isinstance(obj, bool):
        return 'true' if obj else 'false'
    if obj is None:
        return 'null'
    if isinstance(obj, int):
        return '%d' % obj
    raise TypeError('unsupported JSON value type: %s' % type(obj).__name__)


# ---------------------------------------------------------------------------
# Signing and verification
# ---------------------------------------------------------------------------
def _payload_digest(payload):
    """SHA-256 of the canonical {"payload": ...} object."""
    return hashlib.sha256(canonical_json({'payload': payload}).encode('utf-8')).digest()


def _padded_block(payload):
    """Build the 127-byte masked block: PADKEY for the first 95 bytes, XOR digest after."""
    digest = _payload_digest(payload)
    block = bytearray(PADKEY[:127])
    for index, byte in enumerate(digest):
        block[95 + index] ^= byte
    if block[0] == 0:            # the block is fed to RSA as a non-zero integer
        block[0] ^= 1
    return bytes(block)


def sign_payload(payload):
    """Return the 128-byte signature as upper-case hex."""
    block = _padded_block(payload)
    modulus = int.from_bytes(C_MODULUS, 'little')
    exponent = int.from_bytes(PRIVATE_KEY, 'little')
    value = pow(int.from_bytes(block, 'big') % modulus, exponent, modulus)
    raw = bytearray()
    while value:
        raw.append(value & 0xFF)
        value >>= 8
    out = bytearray(128)
    out[:len(raw)] = raw        # little-endian byte order, zero padded to 128 bytes
    return out.hex().upper()


def back_verify_public(payload, signature_hex):
    """Rebuild the digest with the verifier's public exponent.

    ``pow(signature, 19, N)`` must yield the 127-byte block whose first 95 bytes
    equal PADKEY and whose last 32 bytes XOR PADKEY equal the payload digest.
    Returns ``(ok, detail)``.
    """
    try:
        signature = bytes.fromhex(signature_hex)
    except (TypeError, ValueError):
        return False, 'signature is not valid hex'
    if len(signature) != 128:
        return False, 'signature length is %d, expected 128' % len(signature)
    modulus = int.from_bytes(C_MODULUS, 'little')
    recovered = pow(int.from_bytes(signature, 'little'), E_PUBLIC, modulus)
    if recovered >= 1 << 1016:
        return False, 'recovered block exceeds 127 bytes'
    block = recovered.to_bytes(127, 'big')
    if block[:95] != PADKEY[:95]:
        return False, 'padding mismatch'
    digest = bytes(left ^ right for left, right in zip(block[95:], PADKEY[95:]))
    if digest != _payload_digest(payload):
        return False, 'digest mismatch'
    return True, 'padding ok, digest ok'


# ---------------------------------------------------------------------------
# Field validation
# ---------------------------------------------------------------------------
class ValidationError(Exception):
    """Raised by the individual validators; the GUI turns it into a field hint."""


_LOCAL_RE = re.compile(r'^[A-Za-z0-9_%+-]+(?:\.[A-Za-z0-9_%+-]+)*$')
_LABEL_RE = re.compile(r'^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$')


def _reject_forbidden_code_points(text, label):
    for ch in text:
        if unicodedata.category(ch) in _FORBIDDEN_CATEGORIES:
            raise ValidationError('%s含不可接受的字符(控制/格式/代理/私用/未分配码位)。' % label)


def validate_email(value):
    email = (value or '').strip()
    if not email:
        raise ValidationError('邮箱不能为空。')
    if len(email) > EMAIL_MAX:
        raise ValidationError('邮箱过长(最多 %d 个字符)。' % EMAIL_MAX)
    _reject_forbidden_code_points(email, '邮箱')
    if email.count('@') != 1:
        raise ValidationError('邮箱必须且只能包含一个 @。')
    local, domain = email.split('@')
    if not local or len(local) > 64:
        raise ValidationError('邮箱 @ 前的本地部分长度必须在 1..64。')
    if not _LOCAL_RE.match(local):
        raise ValidationError('邮箱本地部分含非法字符或点号位置错误。')
    labels = domain.split('.')
    if len(labels) < 2:
        raise ValidationError('邮箱域名必须至少包含一个点(如 example.com)。')
    for label in labels:
        if not label or len(label) > 63:
            raise ValidationError('邮箱域名段长度必须在 1..63。')
        if not _LABEL_RE.match(label):
            raise ValidationError('邮箱域名段只能包含字母/数字/连字符,且不能以连字符开头或结尾。')
    if not re.match(r'^[A-Za-z]{2,}$', labels[-1]):
        raise ValidationError('邮箱顶级域名必须为至少 2 个字母。')
    return email


def validate_owner(value, label='用户名'):
    owner = (value or '').strip()
    if not owner:
        raise ValidationError('%s不能为空。' % label)
    if len(owner) > OWNER_MAX:
        raise ValidationError('%s过长(最多 %d 个字符)。' % (label, OWNER_MAX))
    _reject_forbidden_code_points(owner, label)
    return owner


def validate_seats(value):
    text = str(value).strip()
    if not text:
        raise ValidationError('席位数量不能为空。')
    if not re.match(r'^[0-9]+$', text):
        raise ValidationError('席位数量必须是正整数。')
    seats = int(text)
    if seats < SEAT_MIN or seats > SEAT_MAX:
        raise ValidationError('席位数量必须在 %d..%d 之间。' % (SEAT_MIN, SEAT_MAX))
    return seats


def days_in_month(year, month):
    """Number of days in the given month (leap years handled by calendar)."""
    return calendar.monthrange(int(year), int(month))[1]


def build_day_values(year, month):
    """Day strings selectable for a year/month pair."""
    return [str(day) for day in range(1, days_in_month(year, month) + 1)]


def clamp_day(year, month, day):
    """Clamp a day string into the valid range of the given month."""
    max_day = days_in_month(year, month)
    try:
        value = int(day)
    except (TypeError, ValueError):
        return '1'
    return str(max(1, min(max_day, value)))


def add_years(base_date, years):
    """Shift a date by whole years, clamping Feb 29 to Feb 28."""
    year = min(max(base_date.year + years, YEAR_MIN), YEAR_MAX)
    day = min(base_date.day, days_in_month(year, base_date.month))
    return year, base_date.month, day


def validate_date_parts(year, month, day, whole_label, time_text):
    try:
        year_value, month_value, day_value = int(year), int(month), int(day)
    except (TypeError, ValueError):
        raise ValidationError('%s必须选择完整的年/月/日。' % whole_label)
    if not (YEAR_MIN <= year_value <= YEAR_MAX):
        raise ValidationError('%s年份必须在 %d..%d。' % (whole_label, YEAR_MIN, YEAR_MAX))
    if not (1 <= month_value <= 12):
        raise ValidationError('%s月份必须为 1..12。' % whole_label)
    if not (1 <= day_value <= days_in_month(year_value, month_value)):
        raise ValidationError('%s日期无效:%d 年 %d 月没有 %d 日。'
                              % (whole_label, year_value, month_value, day_value))
    try:
        moment = _dt.datetime.strptime('%04d-%02d-%02d %s' % (year_value, month_value, day_value, time_text),
                                       DATE_FMT)
    except ValueError:
        raise ValidationError('%s不是合法日期。' % whole_label)
    return moment.strftime(DATE_FMT)


def validate_date_range(start_text, end_text):
    start = _dt.datetime.strptime(start_text, DATE_FMT)
    end = _dt.datetime.strptime(end_text, DATE_FMT)
    if end <= start:
        raise ValidationError('到期时间必须晚于生效时间。')
    return start, end


def _is_writable_dir(directory):
    """True when a real file can be created inside ``directory``."""
    try:
        os.makedirs(directory, exist_ok=True)
    except OSError:
        return False
    probe = os.path.join(directory, '.__keygen_write_probe__')
    try:
        with open(probe, 'w', encoding='utf-8') as handle:
            handle.write('')
        os.remove(probe)
        return True
    except OSError:
        try:
            if os.path.exists(probe):
                os.remove(probe)
        except OSError:
            pass
        return False


def read_file_version(path):
    """Return ``(major, minor, build, revision)`` from a PE, or ``None``.

    Best effort: a missing API or an unversioned file yields ``None`` so the
    caller can report "未确认版本" instead of failing.
    """
    if os.name != 'nt' or not os.path.isfile(path):
        return None
    try:
        import ctypes
        api = ctypes.WinDLL('version', use_last_error=True)
        ignored = ctypes.c_uint32()
        size = api.GetFileVersionInfoSizeW(ctypes.c_wchar_p(path), ctypes.byref(ignored))
        if not size:
            return None
        buffer = ctypes.create_string_buffer(size)
        if not api.GetFileVersionInfoW(ctypes.c_wchar_p(path), 0, size, buffer):
            return None
        pointer = ctypes.c_void_p()
        length = ctypes.c_uint32()
        if not api.VerQueryValueW(buffer, ctypes.c_wchar_p('\\'),
                                  ctypes.byref(pointer), ctypes.byref(length)):
            return None
        if not length.value or not pointer.value:
            return None
        word_count = max(4, int(length.value) // 4)
        words = ctypes.cast(pointer, ctypes.POINTER(ctypes.c_uint32 * word_count)).contents
        version_ms = int(words[2])
        version_ls = int(words[3])
        return (version_ms >> 16, version_ms & 0xFFFF,
                version_ls >> 16, version_ls & 0xFFFF)
    except Exception:
        return None


def inspect_install_dir(directory, source='用户选择'):
    """Validate one directory and describe it; raises ``ValidationError``."""
    text = (directory or '').strip()
    if not text:
        raise ValidationError('请先自动检测或选择 IDA Pro 安装目录。')
    absolute = os.path.abspath(text)
    if not os.path.isdir(absolute):
        raise ValidationError('IDA 安装目录不存在: %s\n请浏览并选择正确目录,或点击“重新检测”。' % absolute)
    dll_path = os.path.join(absolute, 'ida.dll')
    if not os.path.isfile(dll_path):
        raise ValidationError('目录下未找到 ida.dll,无法确认这是 IDA Pro 安装目录: %s\n'
                              '请浏览并选择正确目录,或点击“重新检测”。' % absolute)
    version = read_file_version(dll_path)
    version_text = '.'.join(str(part) for part in version) if version else None
    version_ok = None if version is None else version[:2] == TARGET_IDA_VERSION
    return {
        'dir': absolute,
        'source': source,
        'has_ida32': os.path.isfile(os.path.join(absolute, 'ida32.dll')),
        'version': version,
        'version_text': version_text,
        'version_ok': version_ok,
    }


def validate_install_dir(directory):
    """Accept a directory only when it holds ``ida.dll`` and is IDA 9.5."""
    profile = inspect_install_dir(directory)
    if profile['version_ok'] is False:
        raise ValidationError('所选目录的 ida.dll 版本为 %s,需要 %s:%s'
                              % (profile['version_text'],
                                 '.'.join(str(part) for part in TARGET_IDA_VERSION),
                                 profile['dir']))
    return profile['dir']


def _registry_candidates():
    """Read install locations from ``Software\\Hex-Rays\\IDA`` (probe, not assume)."""
    candidates = []
    if os.name != 'nt':
        return candidates
    try:
        import winreg
    except ImportError:
        return candidates
    key_path = r'Software\Hex-Rays\IDA'

    def values_of(handle):
        index = 0
        while True:
            try:
                name, value, _kind = winreg.EnumValue(handle, index)
            except OSError:
                return
            index += 1
            if isinstance(value, str) and value.strip():
                yield name, value.strip().strip('"')

    for hive, hive_name in ((winreg.HKEY_CURRENT_USER, 'HKCU'),
                            (winreg.HKEY_LOCAL_MACHINE, 'HKLM')):
        try:
            with winreg.OpenKey(hive, key_path) as key:
                for name, value in values_of(key):
                    candidates.append((value, '注册表 %s\\%s' % (hive_name, name)))
                index = 0
                while True:
                    try:
                        subkey_name = winreg.EnumKey(key, index)
                    except OSError:
                        break
                    index += 1
                    try:
                        with winreg.OpenKey(key, subkey_name) as subkey:
                            for name, value in values_of(subkey):
                                candidates.append((value, '注册表 %s\\%s\\%s'
                                                   % (hive_name, subkey_name, name)))
                    except OSError:
                        continue
        except OSError:
            continue
    return candidates


def _program_files_candidates():
    """Common installation folder names under the Program Files roots."""
    folders = []
    for name in ('ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432'):
        value = os.environ.get(name)
        if value and os.path.isdir(value):
            folders.append(value)
    names = []
    for minor in range(5, -1, -1):
        for base in ('IDA Professional', 'IDA Pro', 'IDA'):
            names.append('%s 9.%d' % (base, minor))
    names.extend(('IDA Professional', 'IDA Pro', 'IDA'))
    candidates = []
    for folder in folders:
        for name in names:
            candidates.append((os.path.join(folder, name), 'Program Files 目录'))
    return candidates


def _env_candidates():
    """``IDA_PATH`` plus any ``PATH`` entry that actually holds an IDA executable."""
    candidates = []
    ida_path = os.environ.get('IDA_PATH')
    if ida_path:
        cleaned = ida_path.strip().strip('"')
        candidates.append((os.path.dirname(cleaned) if os.path.isfile(cleaned) else cleaned,
                           '环境变量 IDA_PATH'))
    for entry in (os.environ.get('PATH') or '').split(os.pathsep):
        if not entry:
            continue
        if any(os.path.isfile(os.path.join(entry, exe))
               for exe in ('ida.exe', 'idat.exe', 'idat64.exe')):
            candidates.append((entry, '环境变量 PATH'))
    return candidates


def _script_candidates():
    """The script directory itself and its immediate sub-directories."""
    candidates = [(SCRIPT_DIR, '脚本所在目录')]
    try:
        for entry in os.scandir(SCRIPT_DIR):
            if entry.is_dir():
                candidates.append((entry.path, '脚本子目录'))
    except OSError:
        pass
    return candidates


def detect_install_dirs(*, extra_dirs=None, include_registry=True,
                        include_program_files=True, include_env=True,
                        include_script=True):
    """Return verified IDA candidates, most reliable first.

    Every candidate must exist and contain ``ida.dll``; version information is
    recorded but never guessed.  Confirmed 9.5 directories come first, then
    unreadable versions, then directories known to be a different version.
    """
    sources = []
    if include_registry:
        sources.extend(_registry_candidates())
    if include_program_files:
        sources.extend(_program_files_candidates())
    if include_env:
        sources.extend(_env_candidates())
    if include_script:
        sources.extend(_script_candidates())
    for directory in (extra_dirs or []):
        sources.append((directory, '指定目录'))

    result = []
    seen = set()
    for directory, source in sources:
        try:
            profile = inspect_install_dir(directory, source)
        except ValidationError:
            continue
        key = os.path.normcase(profile['dir'])
        if key in seen:
            continue
        seen.add(key)
        result.append(profile)
    rank = {True: 0, None: 1, False: 2}
    result.sort(key=lambda item: rank[item['version_ok']])
    return result


def config_path(folder=None):
    return os.path.join(folder or SCRIPT_DIR, CONFIG_FILE_NAME)


def load_config(path=None):
    """Read ``keygen_config.json``; a missing or corrupt file yields ``{}``."""
    path = path or config_path()
    try:
        with open(path, 'r', encoding='utf-8') as handle:
            data = json.load(handle)
    except (OSError, ValueError, TypeError):
        return {}
    if not isinstance(data, dict):
        return {}
    return data


def _write_config_to(folder, config):
    path = os.path.join(folder, CONFIG_FILE_NAME)
    try:
        os.makedirs(folder, exist_ok=True)
        temp_path = path + '.tmp'
        with open(temp_path, 'w', encoding='utf-8') as handle:
            json.dump(config, handle, ensure_ascii=False, indent=2)
        os.replace(temp_path, path)
        return path
    except OSError:
        return None


def save_config(config, install_dir=None):
    """Persist to the script directory; fall back to ``<IDA>\\.keygen``."""
    folders = [SCRIPT_DIR]
    if install_dir:
        folders.append(os.path.join(install_dir, FALLBACK_STATE_DIR_NAME))
    for folder in folders:
        path = _write_config_to(folder, config)
        if path:
            return path
    raise ValidationError('脚本目录与 IDA 安装目录均不可写,无法保存配置。')


def write_log_line(text, install_dir=None):
    """Append one timestamped line to ``keygen.log``; never raises."""
    line = '[%s] %s\n' % (_dt.datetime.now().strftime(DATE_FMT), text)
    folders = [SCRIPT_DIR]
    if install_dir:
        folders.append(os.path.join(install_dir, FALLBACK_STATE_DIR_NAME))
    for folder in folders:
        try:
            os.makedirs(folder, exist_ok=True)
            with open(os.path.join(folder, LOG_FILE_NAME), 'a', encoding='utf-8') as handle:
                handle.write(line)
            return True
        except OSError:
            continue
    return False


def resolve_backup_root(install_dir, script_dir=None):
    """Backups live under the script directory, falling back to the IDA dir."""
    script_dir = SCRIPT_DIR if script_dir is None else script_dir
    primary = os.path.join(script_dir, BACKUP_DIR_NAME)
    if _is_writable_dir(primary):
        return primary
    if install_dir:
        fallback = os.path.join(install_dir, BACKUP_DIR_NAME)
        if _is_writable_dir(fallback):
            return fallback
    raise ValidationError('脚本目录与 IDA 安装目录均不可写,无法创建补丁备份。')


def validate_output_path(path):
    text = (path or '').strip()
    if not text:
        raise ValidationError('输出路径不能为空:请先选择 IDA 安装目录或指定另存位置。')
    absolute = os.path.abspath(text)
    if not absolute.lower().endswith('.hexlic'):
        raise ValidationError('输出文件名必须以 .hexlic 结尾。')
    if os.path.isdir(absolute):
        raise ValidationError('输出路径指向目录,请填写 .hexlic 文件名。')
    folder = os.path.dirname(absolute)
    if not os.path.isdir(folder):
        raise ValidationError('输出目录不存在: %s\n请重新选择 IDA 安装目录或另存位置。' % folder)
    if not _is_writable_dir(folder):
        raise ValidationError('输出目录不可写: %s\n请重新选择 IDA 安装目录或另存位置。' % folder)
    return absolute


def validate_identifier(value, label):
    """Strict engine ID shape: XX-XXXX-XXXX-XX using hex digits."""
    text = (value or '').strip()
    if not text:
        raise ValidationError('%s不能为空。' % label)
    if not LICENSE_ID_RE.match(text):
        raise ValidationError('%s必须形如 XX-XXXX-XXXX-XX(十六进制,例:14-0000-FFFF-88)。' % label)
    return text


def validate_owner_value(value, label='所有者'):
    """licenses[0].owner: stored verbatim and never displayed by the engine.

    The engine only requires the key to exist and be a string, so any non-empty
    text is safe.  Keep the generic length / code-point checks only; add-on
    owners are validated separately with the strict ID shape.
    """
    return validate_owner(value, label)


def validate_name(value):
    """payload.name: 1..64 characters, no control/surrogate/private code points."""
    return validate_owner(value, '名称')


def _validate_printable(value, label, max_len=TEXT_FIELD_MAX):
    text = (value or '').strip()
    if not text:
        raise ValidationError('%s不能为空。' % label)
    if len(text) > max_len:
        raise ValidationError('%s过长(最多 %d 个字符)。' % (label, max_len))
    for ch in text:
        if not (0x20 <= ord(ch) <= 0x7E):
            raise ValidationError('%s只能包含 ASCII 可打印字符。' % label)
    return text


def validate_product(value):
    """``product`` has no engine read point; keep it pinned to the fixed value."""
    text = _validate_printable(value, '产品')
    if text != FIXED_PRODUCT:
        raise ValidationError('产品固定为 %s(引擎不读取该字段)。' % FIXED_PRODUCT)
    return text


def validate_choice(value, choices, label):
    text = _validate_printable(value, label)
    if text not in choices:
        raise ValidationError('%s必须是以下之一:%s。' % (label, '、'.join(choices)))
    return text


def validate_product_id(value):
    return validate_choice(value, PRODUCT_ID_CHOICES, '产品 ID')


def validate_edition_id(value):
    return validate_choice(value, EDITION_CHOICES, '版本 ID')


def validate_license_type(value):
    return validate_choice(value, LICENSE_TYPE_CHOICES, '许可证类型')


def validate_description(value):
    return _validate_printable(value, '描述', DESCRIPTION_MAX)


def validate_datetime_text(value, label):
    """Strict ``YYYY-MM-DD HH:MM:SS`` date-time."""
    text = (value or '').strip()
    if not text:
        raise ValidationError('%s不能为空。' % label)
    if not re.match(r'^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$', text):
        raise ValidationError('%s必须为 YYYY-MM-DD HH:MM:SS。' % label)
    try:
        moment = _dt.datetime.strptime(text, DATE_FMT)
    except ValueError:
        raise ValidationError('%s不是合法日期。' % label)
    if not (YEAR_MIN <= moment.year <= YEAR_MAX):
        raise ValidationError('%s年份必须在 %d..%d。' % (label, YEAR_MIN, YEAR_MAX))
    return moment.strftime(DATE_FMT)


def validate_issued_on(value):
    return validate_datetime_text(value, '签发时间')


def validate_features(value):
    """Comma separated or list input; trims, de-duplicates and bounds items."""
    if isinstance(value, (list, tuple)):
        items = list(value)
    else:
        text = (value or '').strip()
        items = text.split(',') if text else []
    result = []
    for item in items:
        item = (item or '').strip()
        if not item or item in result:
            continue
        if len(item) > FEATURE_MAX_LEN:
            raise ValidationError('特性「%s」过长(最多 %d 个字符)。' % (item, FEATURE_MAX_LEN))
        for ch in item:
            if not (0x20 <= ord(ch) <= 0x7E):
                raise ValidationError('特性只能包含 ASCII 可打印字符:%s' % item)
        result.append(item)
    if len(result) > FEATURE_MAX_ITEMS:
        raise ValidationError('特性最多 %d 项。' % FEATURE_MAX_ITEMS)
    return result


def validate_addon_row(row, start_text=None, end_text=None):
    """Validate one add-on entry and return its normalized form."""
    if not isinstance(row, dict):
        raise ValidationError('组件条目格式无效。')
    code = (row.get('code') or '').strip()
    if code not in DEFAULT_ADDONS:
        raise ValidationError('未知组件: %s' % (code or '(空)'))
    identifier = validate_identifier(row.get('id'), '组件 ID')
    owner = validate_identifier(row.get('owner'), '组件所有者')
    start = validate_datetime_text(row.get('start_date'), '组件生效时间')
    end = validate_datetime_text(row.get('end_date'), '组件到期时间')
    if end <= start:
        raise ValidationError('组件到期时间必须晚于生效时间。')
    if start_text and end_text:
        if not (start_text <= start and end <= end_text):
            raise ValidationError('组件有效期必须落在主许可周期内。')
    return {'id': identifier, 'code': code, 'owner': owner,
            'start_date': start, 'end_date': end}


def validate_addon_rows(rows, start_text=None, end_text=None):
    entries = list(rows or [])
    if not entries:
        raise ValidationError('至少添加一个组件 (add-on)。')
    if len(entries) > ADDON_MAX:
        raise ValidationError('组件最多 %d 项。' % ADDON_MAX)
    normalized = []
    for index, row in enumerate(entries, 1):
        try:
            normalized.append(validate_addon_row(row, start_text, end_text))
        except ValidationError as exc:
            raise ValidationError('第 %d 个组件:%s' % (index, exc))
    return normalized


def validate_fields(owner, email, seats, start_parts, end_parts, addons, out_path,
                    *, name=None, license_id=None, product=None, product_id=None,
                    edition_id=None, license_type=None, description=None,
                    issued_on=None, features=None, addon_rows=None,
                    install_dir=None):
    """Single source of truth for validation.

    Returns ``(values, errors)``: ``errors`` maps a field key from FIELD_ORDER
    to a message, ``values`` maps it to the normalized value (``None`` when
    invalid). Every shell value is taken from the arguments, never substituted
    during signing.
    """
    values = {}
    errors = {}

    def run(key, func, *args):
        try:
            values[key] = func(*args)
        except ValidationError as exc:
            values[key] = None
            errors[key] = str(exc)
        except Exception as exc:                     # never let a validator crash the caller
            values[key] = None
            errors[key] = '校验时发生内部错误: %s' % exc

    if name is None:
        name = owner
    if license_id is None:
        license_id = LICENSE_ID
    if product is None:
        product = SHELL_DEFAULTS['product']
    if product_id is None:
        product_id = SHELL_DEFAULTS['product_id']
    if edition_id is None:
        edition_id = SHELL_DEFAULTS['edition_id']
    if license_type is None:
        license_type = SHELL_DEFAULTS['license_type']
    if description is None:
        description = SHELL_DEFAULTS['description']
    if issued_on is None:
        issued_on = _dt.datetime.now().strftime(DATE_FMT)
    if features is None:
        features = ''

    run('name', validate_name, name)
    run('owner', validate_owner_value, owner)
    run('email', validate_email, email)
    run('license_id', validate_identifier, license_id, '许可证 ID')
    run('product', validate_product, product)
    run('product_id', validate_product_id, product_id)
    run('edition_id', validate_edition_id, edition_id)
    run('license_type', validate_license_type, license_type)
    run('description', validate_description, description)
    run('issued_on', validate_issued_on, issued_on)
    run('features', validate_features, features)
    run('seats', validate_seats, seats)
    run('start', validate_date_parts, start_parts[0], start_parts[1], start_parts[2],
        '生效日期', START_TIME)
    run('end', validate_date_parts, end_parts[0], end_parts[1], end_parts[2],
        '到期日期', END_TIME)
    run('path', validate_output_path, out_path)
    if install_dir is not None:
        run('install_dir', validate_install_dir, install_dir)

    if values.get('start') and values.get('end'):
        try:
            validate_date_range(values['start'], values['end'])
        except ValidationError as exc:               # the range problem belongs to the end date
            errors['end'] = str(exc)

    if addon_rows is None:
        base_owner = values.get('license_id') or LICENSE_ID
        base_start = values.get('start')
        base_end = values.get('end')
        addon_rows = [{
            'id': ADDON_ID_FMT % (index + 1),
            'code': code,
            'owner': base_owner,
            'start_date': base_start,
            'end_date': base_end,
        } for index, code in enumerate(addons or [])]
    run('addons', validate_addon_rows, addon_rows, values.get('start'), values.get('end'))
    if values.get('addons'):
        values['addon_rows'] = values['addons']
        values['addons'] = [row['code'] for row in values['addons']]

    values['version'] = PRODUCT_VERSION
    return values, errors


def format_error_summary(errors):
    """Render every field error as a bullet list for the summary panel and dialogs."""
    lines = ['- %s:%s' % (FIELD_LABELS[key], errors[key])
             for key in FIELD_ORDER if errors.get(key)]
    return '\n'.join(lines)


# ---------------------------------------------------------------------------
# License construction
# ---------------------------------------------------------------------------
def build_license(fields):
    """Assemble and sign the license from already-validated field values."""
    addon_rows = fields.get('addon_rows')
    if addon_rows is None:
        addon_rows = [{
            'id': ADDON_ID_FMT % (index + 1),
            'code': addon,
            'owner': fields['license_id'],
            'start_date': fields['start'],
            'end_date': fields['end'],
        } for index, addon in enumerate(fields['addons'])]
    license_obj = {
        # The engine requires the integer 1 here; writing "9.5" makes it report
        # a missing version entry.  The product version lives in product_version.
        'header': {'version': CONTAINER_VERSION},
        'payload': {
            'name': fields['name'],
            'email': fields['email'],
            'licenses': [
                {
                    'description': fields['description'],
                    'edition_id': fields['edition_id'],
                    'id': fields['license_id'],
                    'license_type': fields['license_type'],
                    'product': fields['product'],
                    'seats': fields['seats'],
                    'start_date': fields['start'],
                    'end_date': fields['end'],
                    'issued_on': fields['issued_on'],
                    'owner': fields['owner'],
                    'product_id': fields['product_id'],
                    'product_version': fields.get('version', PRODUCT_VERSION),
                    'add_ons': [dict(row) for row in addon_rows],
                    'features': list(fields.get('features') or []),
                }
            ],
        },
    }
    license_obj['signature'] = sign_payload(license_obj['payload'])
    return license_obj


def load_license_file(path):
    """Parse an existing .hexlic into UI/validation field values (read only)."""
    with open(path, 'r', encoding='utf-8') as handle:
        license_obj = json.load(handle)
    payload = license_obj.get('payload')
    if not isinstance(payload, dict) or not isinstance(payload.get('licenses'), list) \
            or not payload['licenses']:
        raise ValidationError('许可证缺少 payload.licenses。')
    entry = payload['licenses'][0]
    if not isinstance(entry, dict):
        raise ValidationError('licenses[0] 格式无效。')
    if entry.get('product_version') != PRODUCT_VERSION:
        raise ValidationError('该许可证的产品版本为 %r,本工具仅支持 %s。'
                              % (entry.get('product_version'), PRODUCT_VERSION))
    addon_rows = []
    for row in entry.get('add_ons') or []:
        if not isinstance(row, dict):
            raise ValidationError('add_ons 条目格式无效。')
        addon_rows.append({
            'id': row.get('id', ''),
            'code': row.get('code', ''),
            'owner': row.get('owner', ''),
            'start_date': row.get('start_date', ''),
            'end_date': row.get('end_date', ''),
        })
    features = entry.get('features')
    if not isinstance(features, list):
        features = []
    return {
        'name': payload.get('name', ''),
        'email': payload.get('email', ''),
        'license_id': entry.get('id', ''),
        'owner': entry.get('owner', ''),
        'product': entry.get('product', ''),
        'product_id': entry.get('product_id', ''),
        'product_version': entry.get('product_version', ''),
        'edition_id': entry.get('edition_id', ''),
        'license_type': entry.get('license_type', ''),
        'description': entry.get('description', ''),
        'issued_on': entry.get('issued_on', ''),
        'start_date': entry.get('start_date', ''),
        'end_date': entry.get('end_date', ''),
        'seats': str(entry.get('seats', '')),
        'features': list(features),
        'addon_rows': addon_rows,
    }


def write_license(license_obj, out_path):
    text = canonical_json(license_obj)
    with open(out_path, 'w', encoding='utf-8') as handle:
        handle.write(text)
    return text


def _shorten_path(path, limit=64):
    if len(path) <= limit:
        return path
    return '…' + path[-(limit - 1):]


# ---------------------------------------------------------------------------
# Seed derivation (the verifier turns a 128-byte seed into an RSA modulus)
# ---------------------------------------------------------------------------
# 64 little-endian 16-bit source words are permuted and XOR-masked into 64
# output words over four rounds of 16.  The transformation is affine and
# bijective per word, so it can be inverted: the unique blob deriving to a
# given modulus is reconstructed at import time and used as the scan key.
_DERIVE_DELTAS = (0x11, -0x0A, 0x1B, 0, -0x1B, 0x0A, -0x11, 0x14,
                  -7, 0x1E, 3, -0x18, 0x0D, -0x0E, 0x17, -4)
_DERIVE_PARAMS = (
    (0x0000, 0x00000000), (0x60C5, 0x045D9F3B), (0x3E76, 0x08BB3E76),
    (0x224F, 0x0D18DDB1), (0x7CEC, 0x11767CEC), (0x1C27, 0x15D41C27),
    (0x449E, 0x1A31BB62), (0x5A9D, 0x1E8F5A9D), (0x0628, 0x22ECF9D8),
    (0x66ED, 0x274A9913), (0x384E, 0x2BA8384E), (0x2877, 0x3005D789),
    (0x76C4, 0x346376C4), (0x15FF, 0x38C115FF), (0x4AC6, 0x3D1EB53A),
)
_DERIVE_SUB = frozenset((1, 3, 6, 8, 9, 0x0B, 0x0E))


def derive_words(blob):
    """Apply the verifier's word permutation to a 128-byte seed blob."""
    src = [int.from_bytes(blob[index * 2:index * 2 + 2], 'little') for index in range(64)]
    out = [0] * 64
    rotate = -70
    for iteration in range(4):
        base = iteration * 16
        scale = 0x45D9F3B * base
        low = rotate & 0xFF
        for step in range(15):
            target = (low + _DERIVE_DELTAS[step]) & 0x3F
            addend, delta = _DERIVE_PARAMS[step]
            term = 0x9F3B * base - addend if step in _DERIVE_SUB else 0x9F3B * base + addend
            mix = ((0x45D9F3B * base + delta) & 0xFFFFFFFF) ^ (0x27D4EB2D * target) ^ 0x9E3779B9
            out[target] = (src[base + step] ^ (term & 0xFFFF) ^ (0xEB2D * target)
                           ^ 0x79B9 ^ ((mix & 0xFFFFFFFF) >> 16)) & 0xFFFF
        last = (low - 4) & 0x3F
        mix = ((0x27D4EB2D * last) ^ ((scale + 0x417C5475) & 0xFFFFFFFF) ^ 0x9E3779B9) & 0xFFFFFFFF
        out[last] = ((0xEB2D * last) ^ ((scale + 0x5475) & 0xFFFFFFFF) ^ 0x79B9
                     ^ (src[base + 0xF] ^ (mix >> 16))) & 0xFFFF
        rotate -= 0x1B0
    return out


def derive_modulus(blob):
    """Return the 128-byte modulus region the verifier derives from ``blob``."""
    return b''.join(word.to_bytes(2, 'little') for word in derive_words(blob))


def _build_affine_map():
    """Recover ``out[i] = src[perm[i]] ^ mask[i]`` by probing the derivation.

    One input word XORs exactly one output word, so the 64x16 basis probes give
    the permutation and the all-zero blob gives the XOR stream.  This also
    proves the map is bijective; a non-bijective map raises immediately.
    """
    mask = derive_words(bytes(SEED_SIZE))
    perm = [0] * 64
    for source_index in range(64):
        for bit in range(16):
            blob = bytearray(SEED_SIZE)
            blob[source_index * 2:source_index * 2 + 2] = (1 << bit).to_bytes(2, 'little')
            words = derive_words(bytes(blob))
            changed = [index for index in range(64) if words[index] ^ mask[index]]
            if len(changed) != 1 or (words[changed[0]] ^ mask[changed[0]]) != (1 << bit):
                raise RuntimeError('seed derivation is not an affine word permutation')
            perm[changed[0]] = source_index
    return tuple(perm), tuple(mask)


_AFFINE_PERM, _AFFINE_MASK = _build_affine_map()


def seed_preimage(modulus):
    """Return the unique seed blob whose derived modulus equals ``modulus``."""
    target = [int.from_bytes(modulus[index * 2:index * 2 + 2], 'little') for index in range(64)]
    source = [0] * 64
    for index in range(64):
        source[_AFFINE_PERM[index]] = target[index] ^ _AFFINE_MASK[index]
    return b''.join(word.to_bytes(2, 'little') for word in source)


PATCH_REPLACE_BLOB = seed_preimage(C_MODULUS)
FACTORY_MODULUS = derive_modulus(PATCH_SEARCH)
SEED_MODULI = ((C_MODULUS, STATE_TARGET, PATCH_REPLACE_BLOB),
               (FACTORY_MODULUS, STATE_FACTORY, PATCH_SEARCH))


# ---------------------------------------------------------------------------
# Seed scanning and PE address translation
# ---------------------------------------------------------------------------
def _candidate_offsets(data, blob):
    """Yield offsets where a slice of ``blob`` occurs, at any byte alignment.

    The slice is taken from the reconstructed preimage, so the key itself is a
    product of the inverse derivation.  Every candidate is confirmed by a full
    derivation pass before it is reported.
    """
    needle = blob[_SEED_FILTER_START:_SEED_FILTER_START + _SEED_FILTER_LEN]
    position = 0
    while True:
        hit = data.find(needle, position)
        if hit < 0:
            return
        offset = hit - _SEED_FILTER_START
        if offset >= 0:
            yield offset
        position = hit + 1


def scan_seeds(data):
    """Return every seed copy found by derivation, sorted by file offset."""
    found = []
    seen = set()
    for expected_modulus, state, blob in SEED_MODULI:
        for offset in _candidate_offsets(data, blob):
            if offset in seen or offset + SEED_SIZE > len(data):
                continue
            if derive_modulus(data[offset:offset + SEED_SIZE]) != expected_modulus:
                continue
            seen.add(offset)
            found.append({'offset': offset, 'state': state})
    found.sort(key=lambda item: item['offset'])
    return found


def _pe_layout(data):
    """Parse the PE headers just enough to map a file offset to a virtual address."""
    if len(data) < 0x40 or data[:2] != b'MZ':
        return None
    try:
        pe_offset = int.from_bytes(data[0x3C:0x40], 'little')
        if pe_offset + 24 > len(data) or data[pe_offset:pe_offset + 4] != b'PE\0\0':
            return None
        section_count = int.from_bytes(data[pe_offset + 6:pe_offset + 8], 'little')
        optional_size = int.from_bytes(data[pe_offset + 20:pe_offset + 22], 'little')
        optional = pe_offset + 24
        if optional + optional_size > len(data):
            return None
        magic = int.from_bytes(data[optional:optional + 2], 'little')
        if magic == 0x10B:
            image_base = int.from_bytes(data[optional + 0x1C:optional + 0x20], 'little')
        elif magic == 0x20B:
            image_base = int.from_bytes(data[optional + 0x18:optional + 0x20], 'little')
        else:
            return None
        sections = []
        table = optional + optional_size
        for index in range(section_count):
            entry = table + 40 * index
            if entry + 40 > len(data):
                return None
            virtual_size = int.from_bytes(data[entry + 8:entry + 12], 'little')
            virtual_address = int.from_bytes(data[entry + 12:entry + 16], 'little')
            raw_size = int.from_bytes(data[entry + 16:entry + 20], 'little')
            raw_pointer = int.from_bytes(data[entry + 20:entry + 24], 'little')
            sections.append((virtual_address, max(virtual_size, raw_size), raw_pointer, raw_size))
        return image_base, sections
    except (IndexError, ValueError):
        return None


def file_offset_to_va(data, offset):
    """Return the virtual address of ``offset`` or ``None`` when it is not mapped."""
    layout = _pe_layout(data)
    if layout is None:
        return None
    image_base, sections = layout
    for virtual_address, virtual_size, raw_pointer, raw_size in sections:
        if raw_pointer <= offset < raw_pointer + raw_size:
            return image_base + virtual_address + (offset - raw_pointer)
    return None


# ---------------------------------------------------------------------------
# Analysis, preview, patching, rollback
# ---------------------------------------------------------------------------
def _read_file(path):
    with open(path, 'rb') as handle:
        return handle.read()


def analyze_file(path):
    """Scan one DLL and describe its seed state (never writes anything)."""
    data = _read_file(path)
    seeds = scan_seeds(data)
    for seed in seeds:
        seed['va'] = file_offset_to_va(data, seed['offset'])
    states = {seed['state'] for seed in seeds}
    if STATE_FACTORY in states:
        state = STATE_FACTORY
    elif seeds:
        state = STATE_TARGET
    else:
        state = STATE_UNKNOWN
    return {
        'path': path,
        'size': len(data),
        'sha256': hashlib.sha256(data).hexdigest(),
        'seeds': seeds,
        'state': state,
        'pending': [seed for seed in seeds if seed['state'] == STATE_FACTORY],
    }


def analyze_install_dir(directory):
    """Analyze whichever of ida.dll / ida32.dll exist in ``directory``."""
    analyses = []
    missing = []
    base = os.path.abspath(directory)
    for name in PATCH_FILE_NAMES:
        path = os.path.join(base, name)
        if os.path.isfile(path):
            analyses.append(analyze_file(path))
        else:
            missing.append(name)
    return analyses, missing


def preview_patch(analyses):
    """Dry run: list the blocks that would be rewritten, without touching disk."""
    plan = {'files': [], 'errors': [], 'total_blocks': 0, 'total_bytes': 0,
            'no_change': True, 'skipped': []}
    for analysis in analyses:
        name = os.path.basename(analysis['path'])
        if analysis['state'] == STATE_UNKNOWN:
            plan['errors'].append('%s:未识别到任何种子,已拒绝写入。' % name)
            continue
        blocks = [{'offset': seed['offset'], 'va': seed.get('va'),
                   'length': SEED_SIZE} for seed in analysis['pending']]
        if not blocks:
            plan['skipped'].append('%s:已是目标种子,无需改动。' % name)
            continue
        plan['no_change'] = False
        plan['files'].append({'path': analysis['path'], 'sha256': analysis['sha256'],
                              'state': analysis['state'], 'blocks': blocks})
        plan['total_blocks'] += len(blocks)
        plan['total_bytes'] += len(blocks) * SEED_SIZE
    return plan


def _probe_writable(path):
    try:
        with open(path, 'r+b'):
            return True
    except OSError:
        return False


def _probe_exclusive(path):
    """True when the file can be opened for write with no sharing allowed."""
    if os.name != 'nt':
        return _probe_writable(path)
    import ctypes
    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
    kernel32.CreateFileW.restype = ctypes.c_void_p
    kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
    handle = kernel32.CreateFileW(ctypes.c_wchar_p(os.path.abspath(path)),
                                  0x80000000 | 0x40000000, 0, None, 3, 0x80, None)
    if handle is None or handle == ctypes.c_void_p(-1).value:
        return False
    kernel32.CloseHandle(ctypes.c_void_p(handle))
    return True


def _unique_run_dir(root, stamp):
    candidate = os.path.join(root, stamp)
    index = 1
    while os.path.exists(candidate):
        candidate = os.path.join(root, '%s-%d' % (stamp, index))
        index += 1
    return candidate


def _write_bytes_atomic(path, data):
    temp_path = path + '.patchtmp'
    with open(temp_path, 'wb') as handle:
        handle.write(data)
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(temp_path, path)


def _run_preflight(analysis):
    """Return the reasons this file must not be patched, empty when it may."""
    reasons = []
    if not os.path.isfile(analysis['path']):
        reasons.append('%s:文件不存在。' % os.path.basename(analysis['path']))
    elif not _probe_writable(analysis['path']):
        reasons.append('%s:目标文件不可写(只读或被拒绝访问)。' % os.path.basename(analysis['path']))
    elif not _probe_exclusive(analysis['path']):
        reasons.append('%s:文件正被占用(无法以写方式独占打开)。' % os.path.basename(analysis['path']))
    return reasons


def apply_patch(analyses, backup_root=None, timestamp=None):
    """Replace every factory seed with PATCH_REPLACE, then verify and roll back on error.

    ``backup_root`` defaults to ``<install dir>\\backup``; backups live in a
    timestamped sub-directory together with the manifest.  Files already holding
    the target seed are skipped, so repeated runs never write or re-back-up.
    """
    plan = preview_patch(analyses)
    if plan['errors']:
        return {'ok': False, 'errors': plan['errors'], 'no_change': False,
                'manifest': None, 'files': [], 'run_dir': None}
    if plan['no_change']:
        return {'ok': True, 'errors': [], 'no_change': True, 'manifest': None,
                'files': [], 'run_dir': None, 'skipped': plan['skipped']}

    targets = plan['files']
    errors = []
    for analysis in analyses:
        if analysis['pending']:
            errors.extend(_run_preflight(analysis))
    if errors:
        return {'ok': False, 'errors': errors, 'no_change': False,
                'manifest': None, 'files': [], 'run_dir': None}

    if backup_root is None:
        backup_root = os.path.join(os.path.dirname(os.path.abspath(targets[0]['path'])),
                                   BACKUP_DIR_NAME)
    stamp = timestamp or _dt.datetime.now().strftime('%Y%m%d-%H%M%S')
    run_dir = _unique_run_dir(os.path.abspath(backup_root), stamp)
    os.makedirs(run_dir, exist_ok=True)

    manifest = {'version': 1, 'created': _dt.datetime.now().strftime(DATE_FMT), 'files': []}
    done = []
    try:
        for index, target in enumerate(targets):
            path = target['path']
            name = os.path.basename(path)
            backup_path = os.path.join(run_dir, '%02d_%s' % (index, name))
            original = _read_file(path)
            shutil.copy2(path, backup_path)
            patched = bytearray(original)
            for block in target['blocks']:
                patched[block['offset']:block['offset'] + SEED_SIZE] = PATCH_REPLACE
            _write_bytes_atomic(path, bytes(patched))
            done.append((target, path, backup_path, original, hashlib.sha256(bytes(patched)).hexdigest()))
            manifest['files'].append({
                'path': os.path.abspath(path),
                'backup': os.path.abspath(backup_path),
                'sha256_before': target['sha256'],
                'sha256_after': hashlib.sha256(bytes(patched)).hexdigest(),
                'size': len(original),
                'blocks': target['blocks'],
                'patched_at': _dt.datetime.now().strftime(DATE_FMT),
            })

        verify_errors = []
        for target, path, backup_path, original, _new_hash in done:
            check = analyze_file(path)
            expected = len(scan_seeds(original))
            if check['state'] != STATE_TARGET or len(check['seeds']) != expected:
                verify_errors.append('%s:写后校验失败(状态 %s,副本 %d/%d)。'
                                     % (os.path.basename(path),
                                        STATE_LABELS[check['state']],
                                        len(check['seeds']), expected))
        if verify_errors:
            for target, path, backup_path, original, _new_hash in done:
                shutil.copy2(backup_path, path)
            return {'ok': False, 'errors': verify_errors, 'no_change': False,
                    'manifest': None, 'files': [], 'run_dir': run_dir}

        manifest_path = os.path.join(run_dir, 'patch_manifest_%s%s' % (stamp, MANIFEST_SUFFIX))
        with open(manifest_path, 'w', encoding='utf-8') as handle:
            json.dump(manifest, handle, ensure_ascii=False, indent=2)
        return {'ok': True, 'errors': [], 'no_change': False, 'manifest': manifest_path,
                'files': manifest['files'], 'run_dir': run_dir}
    except Exception as exc:
        for target, path, backup_path, original, _new_hash in done:
            try:
                shutil.copy2(backup_path, path)
            except OSError:
                pass
        return {'ok': False, 'errors': [str(exc)], 'no_change': False,
                'manifest': None, 'files': [], 'run_dir': run_dir}


def load_manifest(manifest_path):
    """Read and minimally validate a patch manifest."""
    with open(manifest_path, 'r', encoding='utf-8') as handle:
        manifest = json.load(handle)
    if not isinstance(manifest, dict) or not isinstance(manifest.get('files'), list):
        raise ValueError('补丁清单格式无效。')
    for entry in manifest['files']:
        for key in ('path', 'backup', 'sha256_before'):
            if key not in entry:
                raise ValueError('补丁清单缺少字段: %s' % key)
    return manifest


def rollback_manifest(manifest_path):
    """Restore every file listed in the manifest and verify the original hash."""
    try:
        manifest = load_manifest(manifest_path)
    except Exception as exc:
        return {'ok': False, 'errors': [str(exc)], 'files': []}
    results = []
    errors = []
    for entry in manifest['files']:
        path = entry['path']
        backup = entry['backup']
        try:
            if not os.path.isfile(backup):
                raise ValueError('备份文件不存在: %s' % backup)
            if not _probe_writable(path):
                raise ValueError('目标文件不可写: %s' % path)
            _write_bytes_atomic(path, _read_file(backup))
            digest = hashlib.sha256(_read_file(path)).hexdigest()
            if digest != entry['sha256_before']:
                raise ValueError('还原后 SHA-256 不符: %s' % path)
            results.append({'path': path, 'sha256': digest, 'ok': True})
        except Exception as exc:
            errors.append('%s:%s' % (os.path.basename(path), exc))
            results.append({'path': path, 'sha256': None, 'ok': False})
    return {'ok': not errors, 'errors': errors, 'files': results}



# ---------------------------------------------------------------------------
# GUI: date editor
# ---------------------------------------------------------------------------
class DateEditor:
    """Segmented year/month/day editor with a month-linked day list and presets."""

    def __init__(self, tk, ttk, master, default, fixed_time, on_change=None):
        self.tk = tk
        self.ttk = ttk
        self.on_change = on_change
        self.year_var = tk.StringVar(value='%d' % default[0])
        self.month_var = tk.StringVar(value='%d' % default[1])
        self.day_var = tk.StringVar(value='%d' % default[2])

        self.frame = ttk.Frame(master, style='Card.TFrame')
        self.frame.columnconfigure(6, weight=1)

        combo_kw = dict(state='readonly', style='Combo.TCombobox')
        self.year_box = ttk.Combobox(self.frame, textvariable=self.year_var, width=6,
                                     values=[str(year) for year in range(YEAR_MIN, YEAR_MAX + 1)], **combo_kw)
        self.month_box = ttk.Combobox(self.frame, textvariable=self.month_var, width=3,
                                      values=[str(month) for month in range(1, 13)], **combo_kw)
        self.day_box = ttk.Combobox(self.frame, textvariable=self.day_var, width=3, **combo_kw)
        self._boxes = (self.year_box, self.month_box, self.day_box)

        label_kw = dict(style='Card.TLabel')
        self.year_box.grid(row=0, column=0)
        ttk.Label(self.frame, text='年', **label_kw).grid(row=0, column=1, padx=(4, 10))
        self.month_box.grid(row=0, column=2)
        ttk.Label(self.frame, text='月', **label_kw).grid(row=0, column=3, padx=(4, 10))
        self.day_box.grid(row=0, column=4)
        ttk.Label(self.frame, text='日', **label_kw).grid(row=0, column=5, padx=(4, 10))
        ttk.Label(self.frame, text=fixed_time, style='Hint.TLabel').grid(row=0, column=6, sticky='w')

        self.year_var.trace_add('write', self._on_period_change)
        self.month_var.trace_add('write', self._on_period_change)
        self.refresh_days()

        presets = ttk.Frame(self.frame, style='Card.TFrame')
        presets.grid(row=1, column=0, columnspan=7, sticky='w', pady=(4, 0))
        for years in PRESET_YEARS:
            ttk.Button(presets, text='%d 年后' % years, style='Ghost.TButton',
                       command=self._safe(lambda count=years: self.set_date(
                           *add_years(_dt.date.today(), count)))).pack(side='left', padx=(0, 6))
        ttk.Button(presets, text='%d-%02d-%02d' % PRESET_FIXED_DATE, style='Ghost.TButton',
                   command=self._safe(lambda: self.set_date(*PRESET_FIXED_DATE))).pack(side='left')

    # -- helpers -----------------------------------------------------------
    def _safe(self, func):
        def wrapper():
            try:
                func()
            except Exception:
                return None                     # never raise into the Tk event loop
        return wrapper

    def refresh_days(self):
        try:
            year = int(self.year_var.get())
            month = int(self.month_var.get())
        except (TypeError, ValueError):
            return
        self.day_box.configure(values=build_day_values(year, month))
        clamped = clamp_day(year, month, self.day_var.get())
        if clamped != self.day_var.get():
            self.day_var.set(clamped)

    def _on_period_change(self, *_args):
        try:
            self.refresh_days()
        except Exception:
            return

    def set_date(self, year, month, day):
        self.year_var.set(str(year))
        self.month_var.set(str(month))
        self.refresh_days()
        self.day_var.set(clamp_day(year, month, day))
        if self.on_change is not None:
            self.on_change()

    def parts(self):
        return self.year_var.get(), self.month_var.get(), self.day_var.get()

    def variables(self):
        return (self.year_var, self.month_var, self.day_var)

    def set_error(self, flag):
        style = 'Error.TCombobox' if flag else 'Combo.TCombobox'
        for box in self._boxes:
            box.configure(style=style)


# ---------------------------------------------------------------------------
# GUI: application
# ---------------------------------------------------------------------------
class KeygenApp:
    """Tkinter front-end with live validation and a status bar."""

    def __init__(self, root):
        import tkinter as tk
        from tkinter import ttk
        self.tk = tk
        self.ttk = ttk
        self.root = root
        self.vars = {}
        self.controls = {}
        self.error_labels = {}
        self.editors = {}
        self.readonly_fields = {}
        self.addon_rows = [{
            'id': ADDON_ID_FMT % (index + 1),
            'code': code,
            'owner': LICENSE_ID,
            'start_date': '2024-08-10 00:00:00',
            'end_date': '2099-12-31 23:59:59',
        } for index, code in enumerate(DEFAULT_ADDONS)]
        self.patch_analyses = []
        self.patch_manifest = None
        self.patch_ready = False
        self._ready = False

        # Startup location: saved choice first, then auto-detection.  A stale or
        # corrupt entry silently falls back to detection.
        self.config = load_config()
        self.detected = detect_install_dirs()
        self.install_dir = ''
        self.path_manual = False
        self._setting_output = False
        self._log_warned = False
        saved_dir = self.config.get('install_dir')
        if isinstance(saved_dir, str) and saved_dir.strip():
            try:
                self.install_dir = inspect_install_dir(saved_dir, '已保存配置')['dir']
            except ValidationError:
                self.install_dir = ''
        if not self.install_dir and self.detected:
            self.install_dir = self.detected[0]['dir']

        self._configure_styles()
        self._build_ui()
        self._render_addons()
        self._refresh_candidates()
        self._update_backup_hint()
        self._place_window()
        self._install_traces()
        self._ready = True
        self.refresh_state()

    # -- theme -------------------------------------------------------------
    def _pick_font_family(self):
        import tkinter.font as tkfont
        try:
            available = set(tkfont.families(self.root))
        except Exception:
            return 'Segoe UI'
        for name in ('Microsoft YaHei UI', 'Microsoft YaHei', 'Segoe UI'):
            if name in available:
                return name
        return 'Segoe UI'

    def _configure_styles(self):
        tk, ttk = self.tk, self.ttk
        colours = PALETTE
        style = ttk.Style(self.root)
        try:
            style.theme_use('clam')                 # only clam honours custom colours on Windows
        except tk.TclError:
            pass

        family = self._pick_font_family()
        self.font_ui = (family, 10)
        self.font_small = (family, 9)
        self.font_bold = (family, 10, 'bold')
        self.font_title = (family, 16, 'bold')

        style.configure('App.TFrame', background=colours['window'])
        style.configure('Card.TFrame', background=colours['panel'])
        style.configure('Card.TLabelframe', background=colours['panel'],
                        bordercolor=colours['border'], relief='solid', borderwidth=1)
        style.configure('Card.TLabelframe.Label', background=colours['panel'],
                        foreground=colours['accent'], font=self.font_bold)
        style.configure('Title.TLabel', background=colours['window'], foreground=colours['text'],
                        font=self.font_title)
        style.configure('Subtitle.TLabel', background=colours['window'], foreground=colours['muted'],
                        font=self.font_small)
        style.configure('Card.TLabel', background=colours['panel'], foreground=colours['text'],
                        font=self.font_ui)
        style.configure('Hint.TLabel', background=colours['panel'], foreground=colours['muted'],
                        font=self.font_small)
        style.configure('Error.TLabel', background=colours['panel'], foreground=colours['error'],
                        font=self.font_small)
        style.configure('SummaryError.TLabel', background=colours['panel'], foreground=colours['error'],
                        font=self.font_ui)
        style.configure('SummaryOk.TLabel', background=colours['panel'], foreground=colours['ok'],
                        font=self.font_ui)
        style.configure('Field.TEntry', fieldbackground='#ffffff', foreground=colours['text'],
                        bordercolor=colours['border'], lightcolor='#ffffff', darkcolor='#ffffff',
                        insertcolor=colours['text'], padding=5, relief='flat')
        style.map('Field.TEntry',
                  bordercolor=[('focus', colours['accent'])],
                  lightcolor=[('focus', colours['accent'])],
                  darkcolor=[('focus', colours['accent'])])
        style.configure('Error.TEntry', fieldbackground=colours['error_bg'], foreground=colours['text'],
                        bordercolor=colours['error'], lightcolor=colours['error_bg'],
                        darkcolor=colours['error_bg'], insertcolor=colours['text'],
                        padding=5, relief='flat')
        style.configure('Spin.TSpinbox', fieldbackground='#ffffff', foreground=colours['text'],
                        bordercolor=colours['border'], background='#ffffff',
                        arrowcolor=colours['accent'], padding=4, relief='flat')
        style.configure('Error.TSpinbox', fieldbackground=colours['error_bg'], foreground=colours['text'],
                        bordercolor=colours['error'], background=colours['error_bg'],
                        arrowcolor=colours['error'], padding=4, relief='flat')
        style.configure('Combo.TCombobox', fieldbackground='#ffffff', background='#ffffff',
                        foreground=colours['text'], bordercolor=colours['border'],
                        arrowcolor=colours['accent'], padding=4, relief='flat')
        style.map('Combo.TCombobox',
                  fieldbackground=[('readonly', '#ffffff'), ('disabled', '#eef1f6')],
                  foreground=[('readonly', colours['text'])],
                  bordercolor=[('focus', colours['accent'])])
        style.configure('Error.TCombobox', fieldbackground=colours['error_bg'], background=colours['error_bg'],
                        foreground=colours['text'], bordercolor=colours['error'],
                        arrowcolor=colours['error'], padding=4, relief='flat')
        style.map('Error.TCombobox', fieldbackground=[('readonly', colours['error_bg'])])
        style.configure('Card.TCheckbutton', background=colours['panel'], foreground=colours['text'],
                        font=self.font_ui, padding=(2, 4))
        style.map('Card.TCheckbutton', background=[('active', colours['panel'])])
        style.configure('Primary.TButton', background=colours['accent'], foreground='#ffffff',
                        font=self.font_bold, padding=(20, 8), borderwidth=0, relief='flat')
        style.map('Primary.TButton',
                  background=[('active', colours['accent_hover']), ('disabled', '#d8dfe9')],
                  foreground=[('disabled', '#3b4453')])
        style.configure('Ghost.TButton', background=colours['chip'], foreground=colours['accent'],
                        font=self.font_small, padding=(8, 3), borderwidth=0, relief='flat')
        style.map('Ghost.TButton',
                  background=[('active', '#d7e3f3'), ('pressed', '#c9d9ee')],
                  foreground=[('disabled', '#7b8698')])

        # Patch result table: same panel/ink colours as the cards.
        style.configure('Patch.Treeview', background='#ffffff', fieldbackground='#ffffff',
                        foreground=colours['text'], bordercolor=colours['border'],
                        font=self.font_small, rowheight=22, borderwidth=1, relief='solid')
        style.configure('Patch.Treeview.Heading', background=colours['chip'],
                        foreground=colours['accent'], font=self.font_bold, relief='flat')
        style.map('Patch.Treeview',
                  background=[('selected', colours['accent'])],
                  foreground=[('selected', '#ffffff')])

        # Readable drop-down lists (the popdown is a classic Tk listbox, not themed).
        self.root.option_add('*TCombobox*Listbox.background', '#ffffff')
        self.root.option_add('*TCombobox*Listbox.foreground', colours['text'])
        self.root.option_add('*TCombobox*Listbox.selectBackground', colours['accent'])
        self.root.option_add('*TCombobox*Listbox.selectForeground', '#ffffff')

    def _place_window(self):
        """Size the window to its natural content and centre it on screen."""
        self.root.configure(bg=PALETTE['window'])
        self.root.title('IDA Pro 9.5 许可证生成器')
        self.root.rowconfigure(0, weight=1)
        self.root.columnconfigure(0, weight=1)
        self.root.update_idletasks()
        content_width = self.main_frame.winfo_reqwidth() + 24
        content_height = self.main_frame.winfo_reqheight() + self.status_bar.winfo_reqheight() + 4
        natural_width = max(920, content_width)
        natural_height = content_height
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        height = min(natural_height + 6, screen_height - 90)
        self.root.minsize(min(880, natural_width), min(660, height))
        x = max(0, (screen_width - natural_width) // 2)
        y = max(0, (screen_height - height) // 4)
        self.root.geometry('%dx%d+%d+%d' % (natural_width, height, x, y))

    def _sync_scroll_region(self, _event=None):
        try:
            self.canvas.configure(scrollregion=self.canvas.bbox('all'))
            needed = self.main_frame.winfo_reqheight() > self.canvas.winfo_height()
            if needed and not self.vbar.winfo_ismapped():
                self.vbar.grid()
            elif not needed and self.vbar.winfo_ismapped():
                self.vbar.grid_remove()
                self.canvas.yview_moveto(0)
        except Exception:
            return

    def _on_canvas_configure(self, event):
        try:
            height = max(event.height, self.main_frame.winfo_reqheight())
            self.canvas.itemconfigure(self.canvas_window, width=event.width, height=height)
            self._sync_scroll_region()
        except Exception:
            return

    def _on_mouse_wheel(self, event):
        try:
            if str(event.widget.winfo_class()) in ('Text', 'Listbox', 'TCombobox'):
                return                      # let those widgets scroll themselves
            if self.vbar.winfo_ismapped():
                self.canvas.yview_scroll(-1 if event.delta > 0 else 1, 'units')
        except Exception:
            return

    # -- layout ------------------------------------------------------------
    def _card(self, parent, title, row, weight=0):
        card = self.ttk.LabelFrame(parent, text=title, style='Card.TLabelframe',
                                   padding=(12, 8, 12, 10))
        card.grid(row=row, column=0, sticky='nsew', pady=(0, 8))
        card.columnconfigure(0, weight=1)
        card.rowconfigure(0, weight=1)
        parent.rowconfigure(row, weight=weight)
        body = self.ttk.Frame(card, style='Card.TFrame')
        body.grid(row=0, column=0, sticky='nsew')
        body.columnconfigure(1, weight=1)
        body.columnconfigure(2, minsize=262)
        return body

    def _row_label(self, body, row, text, sticky='w'):
        label = self.ttk.Label(body, text=text, style='Card.TLabel')
        label.grid(row=row, column=0, sticky=sticky, padx=(0, 10), pady=4)
        return label

    def _error_label(self, body, row, key, sticky='w'):
        label = self.tk.Label(body, text='', fg=PALETTE['error'], bg=PALETTE['panel'],
                              font=self.font_small, anchor='w', justify='left', wraplength=250)
        label.grid(row=row, column=2, sticky=sticky, padx=(10, 0), pady=4)
        self.error_labels[key] = label
        return label

    def _readonly_value(self, body, row, label, value, hint, key=None):
        """Render a single-valued field as a non-editable chip."""
        self._row_label(body, row, label)
        holder = self.ttk.Frame(body, style='Card.TFrame')
        holder.grid(row=row, column=1, sticky='we', pady=4)
        self.tk.Label(holder, text=value, bg=PALETTE['chip'], fg=PALETTE['accent'],
                      font=self.font_bold, padx=10, pady=3).pack(side='left')
        self.ttk.Label(holder, text=hint, style='Hint.TLabel').pack(side='left', padx=(10, 0))
        if key:
            self.readonly_fields[key] = value
        return holder

    def _register_control(self, key, widget, normal_style, error_style):
        self.controls[key] = (widget, normal_style, error_style)

    def _build_ui(self):
        ttk, tk = self.ttk, self.tk

        # Scrollable body so the form never clips on small or scaled displays.
        scroll_host = ttk.Frame(self.root, style='App.TFrame')
        scroll_host.grid(row=0, column=0, sticky='nsew')
        scroll_host.rowconfigure(0, weight=1)
        scroll_host.columnconfigure(0, weight=1)
        self.canvas = tk.Canvas(scroll_host, bg=PALETTE['window'], highlightthickness=0, borderwidth=0,
                                width=900, height=600)
        self.canvas.grid(row=0, column=0, sticky='nsew')
        self.vbar = ttk.Scrollbar(scroll_host, orient='vertical', command=self.canvas.yview)
        self.vbar.grid(row=0, column=1, sticky='ns')
        self.canvas.configure(yscrollcommand=self.vbar.set)

        main = ttk.Frame(self.canvas, style='App.TFrame', padding=(14, 12, 14, 6))
        self.main_frame = main
        main.columnconfigure(0, weight=1)
        self.canvas_window = self.canvas.create_window((0, 0), window=main, anchor='nw')
        main.bind('<Configure>', self._sync_scroll_region)
        self.canvas.bind('<Configure>', self._on_canvas_configure)
        self.root.bind_all('<MouseWheel>', self._on_mouse_wheel)

        header = ttk.Frame(main, style='App.TFrame')
        header.grid(row=0, column=0, sticky='we', pady=(0, 10))
        ttk.Label(header, text='IDA Pro 许可证生成器', style='Title.TLabel').pack(anchor='w')
        ttk.Label(header, text='为 IDA Professional %s 生成 idapro.hexlic,并可定位/替换 DLL 种子'
                  '(离线签名,仅使用 Python 标准库)'
                  % PRODUCT_VERSION, style='Subtitle.TLabel').pack(anchor='w', pady=(2, 0))

        # License information -------------------------------------------------
        body = self._card(main, '许可证信息', 1)

        self._row_label(body, 0, '名称 (payload.name)  必填')
        name_var = tk.StringVar(value=SHELL_DEFAULTS['name'])
        name_entry = ttk.Entry(body, textvariable=name_var, style='Field.TEntry')
        name_entry.grid(row=0, column=1, sticky='we', pady=4)
        self.vars['name'] = name_var
        self._register_control('name', name_entry, 'Field.TEntry', 'Error.TEntry')
        self._error_label(body, 0, 'name')

        self._row_label(body, 1, '所有者 (owner)  引擎不显示')
        owner_holder = ttk.Frame(body, style='Card.TFrame')
        owner_holder.grid(row=1, column=1, sticky='we', pady=4)
        owner_holder.columnconfigure(0, weight=1)
        owner_var = tk.StringVar(value=SHELL_DEFAULTS['name'])
        self.owner_entry = ttk.Entry(owner_holder, textvariable=owner_var, style='Field.TEntry')
        self.owner_entry.grid(row=0, column=0, sticky='we')
        self.owner_follow_var = tk.BooleanVar(value=True)
        ttk.Checkbutton(owner_holder, text='跟随名称', variable=self.owner_follow_var,
                        style='Card.TCheckbutton',
                        command=self._guarded(self._sync_owner_follow)).grid(
            row=0, column=1, padx=(10, 0))
        self.owner_hint = ttk.Label(
            owner_holder,
            text='引擎不显示该字段,任意字符串均安全\n'
                 'add-on 的 owner 必须为 XX-XXXX-XXXX-XX',
            style='Hint.TLabel')
        self.owner_hint.grid(row=1, column=0, columnspan=3, sticky='w', pady=(2, 0))
        self.vars['owner'] = owner_var
        self._register_control('owner', self.owner_entry, 'Field.TEntry', 'Error.TEntry')
        self._error_label(body, 1, 'owner')

        self._row_label(body, 2, '邮箱 (Email)  必填')
        email_var = tk.StringVar(value=SHELL_DEFAULTS['email'])
        email_entry = ttk.Entry(body, textvariable=email_var, style='Field.TEntry')
        email_entry.grid(row=2, column=1, sticky='we', pady=4)
        self.vars['email'] = email_var
        self._register_control('email', email_entry, 'Field.TEntry', 'Error.TEntry')
        self._error_label(body, 2, 'email')

        self._readonly_value(body, 3, '产品版本 (product_version)  [只读]', PRODUCT_VERSION,
                             '固定版本,写入 product_version', key='product_version')
        self._readonly_value(body, 4, '容器版本 (header.version)  [只读]',
                             str(CONTAINER_VERSION),
                             '引擎要求整数 1,不可修改', key='header_version')

        # Shell fields ---------------------------------------------------------
        body = self._card(main, '许可字段', 2)

        self._row_label(body, 0, '许可证 ID (licenses[0].id,显示为 License info)')
        license_id_var = tk.StringVar(value=SHELL_DEFAULTS['license_id'])
        license_id_entry = ttk.Entry(body, textvariable=license_id_var, style='Field.TEntry')
        license_id_entry.grid(row=0, column=1, sticky='we', pady=4)
        self.vars['license_id'] = license_id_var
        self._register_control('license_id', license_id_entry, 'Field.TEntry', 'Error.TEntry')
        self._error_label(body, 0, 'license_id')

        # product has exactly one value and no engine read point: read-only.
        self.vars['product'] = tk.StringVar(value=FIXED_PRODUCT)
        self._readonly_value(body, 1, '产品 (product)  [只读]', FIXED_PRODUCT,
                             '引擎不读取该字段,固定为模板值', key='product')

        combo_specs = (
            ('product_id', '产品 ID (product_id)', PRODUCT_ID_CHOICES, SHELL_DEFAULTS['product_id'], 2),
            ('edition_id', '版本 ID (edition_id)', EDITION_CHOICES, SHELL_DEFAULTS['edition_id'], 3),
            ('license_type', '许可证类型 (license_type)', LICENSE_TYPE_CHOICES,
             SHELL_DEFAULTS['license_type'], 4),
        )
        for key, label, choices, default, row in combo_specs:
            self._row_label(body, row, '%s(可选:%s)' % (label, '、'.join(choices)))
            var = tk.StringVar(value=default)
            box = ttk.Combobox(body, textvariable=var, values=list(choices),
                               style='Combo.TCombobox')
            box.grid(row=row, column=1, sticky='we', pady=4)
            self.vars[key] = var
            self._register_control(key, box, 'Combo.TCombobox', 'Error.TCombobox')
            self._error_label(body, row, key)

        self._row_label(body, 5, '描述 (description)')
        description_var = tk.StringVar(value=SHELL_DEFAULTS['description'])
        description_entry = ttk.Entry(body, textvariable=description_var, style='Field.TEntry')
        description_entry.grid(row=5, column=1, sticky='we', pady=4)
        self.vars['description'] = description_var
        self._register_control('description', description_entry, 'Field.TEntry', 'Error.TEntry')
        self._error_label(body, 5, 'description')

        self._row_label(body, 6, '签发时间 (issued_on)  YYYY-MM-DD HH:MM:SS  必填')
        issued_var = tk.StringVar(value=_dt.datetime.now().strftime(DATE_FMT))
        issued_entry = ttk.Entry(body, textvariable=issued_var, style='Field.TEntry')
        issued_entry.grid(row=6, column=1, sticky='we', pady=4)
        self.vars['issued_on'] = issued_var
        self._register_control('issued_on', issued_entry, 'Field.TEntry', 'Error.TEntry')
        self._error_label(body, 6, 'issued_on')

        self._row_label(body, 7, '特性 (features)  逗号分隔,可为空')
        features_var = tk.StringVar(value='')
        features_entry = ttk.Entry(body, textvariable=features_var, style='Field.TEntry')
        features_entry.grid(row=7, column=1, sticky='we', pady=4)
        self.vars['features'] = features_var
        self._register_control('features', features_entry, 'Field.TEntry', 'Error.TEntry')
        self._error_label(body, 7, 'features')

        import_bar = ttk.Frame(body, style='Card.TFrame')
        import_bar.grid(row=8, column=1, columnspan=2, sticky='we', pady=(4, 2))
        ttk.Button(import_bar, text='从现有许可证导入…', style='Ghost.TButton',
                   command=self._guarded(self.on_import_license)).pack(side='left')
        ttk.Label(import_bar, text='读取 .hexlic 并回填全部字段(只读,不修改源文件)',
                  style='Hint.TLabel').pack(side='left', padx=(10, 0))

        # Validity ------------------------------------------------------------
        body = self._card(main, '有效期', 3)
        self._row_label(body, 0, '生效日期 (Start)')
        self.editors['start'] = DateEditor(tk, ttk, body, (2024, 8, 10), START_TIME, self.refresh_state)
        self.editors['start'].frame.grid(row=0, column=1, sticky='we', pady=4)
        self._error_label(body, 0, 'start', sticky='nw')

        self._row_label(body, 1, '到期日期 (End)')
        self.editors['end'] = DateEditor(tk, ttk, body, (2099, 12, 31), END_TIME, self.refresh_state)
        self.editors['end'].frame.grid(row=1, column=1, sticky='we', pady=4)
        self._error_label(body, 1, 'end', sticky='nw')

        ttk.Label(body, text='结束日期不能早于或等于开始日期;每日 00:00:00 生效、23:59:59 结束。',
                  style='Hint.TLabel').grid(row=2, column=1, sticky='w')

        # Seats and add-ons -----------------------------------------------------
        body = self._card(main, '席位与附加组件', 4)
        self._row_label(body, 0, '席位数 (Seats)')
        seat_holder = ttk.Frame(body, style='Card.TFrame')
        seat_holder.grid(row=0, column=1, sticky='w', pady=4)
        seat_var = tk.StringVar(value='1')
        seat_spin = ttk.Spinbox(seat_holder, textvariable=seat_var, from_=SEAT_MIN, to=SEAT_MAX,
                                width=8, style='Spin.TSpinbox', command=self.refresh_state)
        seat_spin.pack(side='left')
        seat_spin.bind('<FocusOut>', self._guarded(self._normalize_seats))
        ttk.Label(seat_holder, text='范围 %d – %d,失去焦点时自动纠正' % (SEAT_MIN, SEAT_MAX),
                  style='Hint.TLabel').pack(side='left', padx=(10, 0))
        self.vars['seats'] = seat_var
        self._register_control('seats', seat_spin, 'Spin.TSpinbox', 'Error.TSpinbox')
        self._error_label(body, 0, 'seats')

        self._row_label(body, 1, '附加组件 (add_ons)', sticky='nw')
        addon_holder = ttk.Frame(body, style='Card.TFrame')
        addon_holder.grid(row=1, column=1, sticky='we', pady=4)
        addon_holder.columnconfigure(0, weight=1)
        addon_columns = ('code', 'id', 'owner', 'start', 'end')
        self.addon_tree = ttk.Treeview(addon_holder, columns=addon_columns, show='headings',
                                       height=6, style='Patch.Treeview', selectmode='browse')
        addon_headings = {'code': '组件代码', 'id': '组件 ID', 'owner': '所有者',
                          'start': '生效时间', 'end': '到期时间'}
        addon_widths = {'code': 190, 'id': 140, 'owner': 140, 'start': 150, 'end': 150}
        for column in addon_columns:
            self.addon_tree.heading(column, text=addon_headings[column])
            self.addon_tree.column(column, width=addon_widths[column], anchor='w', stretch=False)
        self.addon_tree.grid(row=0, column=0, sticky='nsew')
        addon_scroll = ttk.Scrollbar(addon_holder, orient='vertical', command=self.addon_tree.yview)
        addon_scroll.grid(row=0, column=1, sticky='ns')
        self.addon_tree.configure(yscrollcommand=addon_scroll.set)
        self.addon_tree.bind('<Double-1>', self._guarded(self._edit_addon))
        self._error_label(body, 1, 'addons', sticky='nw')

        addon_bar = ttk.Frame(body, style='Card.TFrame')
        addon_bar.grid(row=2, column=1, sticky='we', pady=(2, 0))
        ttk.Button(addon_bar, text='添加', style='Ghost.TButton',
                   command=self._guarded(self._add_addon)).pack(side='left')
        ttk.Button(addon_bar, text='编辑', style='Ghost.TButton',
                   command=self._guarded(self._edit_addon)).pack(side='left', padx=(8, 0))
        ttk.Button(addon_bar, text='删除', style='Ghost.TButton',
                   command=self._guarded(self._remove_addon)).pack(side='left', padx=(8, 0))
        ttk.Button(addon_bar, text='同步日期', style='Ghost.TButton',
                   command=self._guarded(self._sync_addon_dates)).pack(side='left', padx=(8, 0))
        ttk.Label(addon_bar, text='双击可编辑;有效期须在主许可周期内',
                  style='Hint.TLabel').pack(side='left', padx=(12, 0))

        self.addon_count_var = tk.StringVar(value='')
        ttk.Label(body, textvariable=self.addon_count_var, style='Hint.TLabel').grid(
            row=3, column=1, sticky='w')

        # Patch ------------------------------------------------------------
        body = self._card(main, '补丁(DLL 种子替换)', 5, weight=1)
        body.rowconfigure(5, weight=1)

        self._row_label(body, 0, 'IDA 安装目录  自动检测 / 手动选择')
        install_holder = ttk.Frame(body, style='Card.TFrame')
        install_holder.grid(row=0, column=1, columnspan=2, sticky='we', pady=4)
        install_holder.columnconfigure(0, weight=1)
        self.vars['install_dir'] = tk.StringVar(value=self.install_dir)
        install_entry = ttk.Entry(install_holder, textvariable=self.vars['install_dir'],
                                  style='Field.TEntry')
        install_entry.grid(row=0, column=0, sticky='we')
        ttk.Button(install_holder, text='浏览…', style='Ghost.TButton',
                   command=self._guarded(self.on_browse_install_dir)).grid(
            row=0, column=1, padx=(8, 0))
        ttk.Button(install_holder, text='重新检测', style='Ghost.TButton',
                   command=self._guarded(self.on_redetect)).grid(
            row=0, column=2, padx=(8, 0))
        self._register_control('install_dir', install_entry, 'Field.TEntry', 'Error.TEntry')
        self._error_label(body, 0, 'install_dir', sticky='nw')

        self._row_label(body, 1, '检测到的候选')
        candidate_holder = ttk.Frame(body, style='Card.TFrame')
        candidate_holder.grid(row=1, column=1, columnspan=2, sticky='we', pady=4)
        candidate_holder.columnconfigure(0, weight=1)
        self.candidate_var = tk.StringVar(value='')
        self.candidate_box = ttk.Combobox(candidate_holder, textvariable=self.candidate_var,
                                          state='readonly', style='Combo.TCombobox', values=())
        self.candidate_box.grid(row=0, column=0, sticky='we')
        self.candidate_box.bind('<<ComboboxSelected>>',
                                self._guarded(self.on_pick_candidate))
        self.install_status_var = tk.StringVar(value='')
        ttk.Label(candidate_holder, textvariable=self.install_status_var,
                  style='Hint.TLabel', wraplength=340, justify='left').grid(
            row=0, column=1, sticky='w', padx=(10, 0))

        self.backup_hint_var = tk.StringVar(value='')
        ttk.Label(body, textvariable=self.backup_hint_var, style='Hint.TLabel',
                  wraplength=820, justify='left').grid(
            row=2, column=0, columnspan=3, sticky='w', pady=(0, 4))

        action_bar = ttk.Frame(body, style='Card.TFrame')
        action_bar.grid(row=3, column=1, columnspan=2, sticky='we', pady=(2, 6))
        self.analyze_btn = ttk.Button(action_bar, text='分析', style='Primary.TButton',
                                      command=self._guarded(self.on_analyze))
        self.analyze_btn.pack(side='left')
        self.apply_btn = ttk.Button(action_bar, text='应用补丁', style='Primary.TButton',
                                    command=self._guarded(self.on_apply_patch))
        self.apply_btn.pack(side='left', padx=(8, 0))
        self.rollback_btn = ttk.Button(action_bar, text='回滚', style='Ghost.TButton',
                                       command=self._guarded(self.on_rollback))
        self.rollback_btn.pack(side='left', padx=(8, 0))
        ttk.Label(action_bar, text='分析为只读预览,确认后才会写入并备份。',
                  style='Hint.TLabel').pack(side='left', padx=(12, 0))

        self.patch_info_var = tk.StringVar(value='尚未分析。')
        self.patch_info_label = ttk.Label(body, textvariable=self.patch_info_var,
                                          style='SummaryOk.TLabel', anchor='w', justify='left',
                                          wraplength=860)
        self.patch_info_label.grid(row=4, column=0, columnspan=3, sticky='we', pady=(0, 6))

        tree_holder = ttk.Frame(body, style='Card.TFrame')
        tree_holder.grid(row=5, column=0, columnspan=3, sticky='nsew')
        tree_holder.columnconfigure(0, weight=1)
        tree_holder.rowconfigure(0, weight=1)
        columns = ('file', 'offset', 'va', 'sha', 'copies', 'state')
        self.patch_tree = ttk.Treeview(tree_holder, columns=columns, show='headings', height=5,
                                       style='Patch.Treeview', selectmode='browse')
        headings = {'file': '文件', 'offset': '文件偏移', 'va': 'VA', 'sha': '原始 SHA-256',
                    'copies': '副本数', 'state': '当前状态'}
        widths = {'file': 110, 'offset': 160, 'va': 150, 'sha': 330, 'copies': 60, 'state': 140}
        for column in columns:
            self.patch_tree.heading(column, text=headings[column])
            self.patch_tree.column(column, width=widths[column], anchor='w', stretch=False)
        self.patch_tree.tag_configure('state_target', foreground=PALETTE['ok'])
        self.patch_tree.tag_configure('state_factory', foreground=PALETTE['warn'])
        self.patch_tree.tag_configure('state_unknown', foreground=PALETTE['error'])
        self.patch_tree.grid(row=0, column=0, sticky='nsew')
        tree_scroll_y = ttk.Scrollbar(tree_holder, orient='vertical', command=self.patch_tree.yview)
        tree_scroll_y.grid(row=0, column=1, sticky='ns')
        tree_scroll_x = ttk.Scrollbar(tree_holder, orient='horizontal', command=self.patch_tree.xview)
        tree_scroll_x.grid(row=1, column=0, sticky='we')
        self.patch_tree.configure(yscrollcommand=tree_scroll_y.set, xscrollcommand=tree_scroll_x.set)

        # Output -----------------------------------------------------------
        body = self._card(main, '输出', 6, weight=1)
        body.rowconfigure(3, weight=1)

        self._row_label(body, 0, '输出文件  (默认写入所选 IDA 目录)')
        output_holder = ttk.Frame(body, style='Card.TFrame')
        output_holder.grid(row=0, column=1, columnspan=2, sticky='we', pady=4)
        output_holder.columnconfigure(0, weight=1)
        self.vars['path'] = tk.StringVar(value=self._default_output_path())
        output_entry = ttk.Entry(output_holder, textvariable=self.vars['path'],
                                 style='Field.TEntry')
        output_entry.grid(row=0, column=0, sticky='we')
        ttk.Button(output_holder, text='浏览…', style='Ghost.TButton',
                   command=self._guarded(self.on_browse_output)).grid(
            row=0, column=1, padx=(8, 0))
        ttk.Button(output_holder, text='恢复默认', style='Ghost.TButton',
                   command=self._guarded(self.on_reset_output)).grid(
            row=0, column=2, padx=(8, 0))
        self._register_control('path', output_entry, 'Field.TEntry', 'Error.TEntry')
        self._error_label(body, 0, 'path', sticky='nw')

        action_bar = ttk.Frame(body, style='Card.TFrame')
        action_bar.grid(row=1, column=1, columnspan=2, sticky='we', pady=(2, 6))
        self.generate_btn = ttk.Button(action_bar, text='生成许可证', style='Primary.TButton',
                                       command=self._guarded(self.on_generate))
        self.generate_btn.pack(side='right')

        self.summary_var = tk.StringVar(value='')
        self.summary_label = ttk.Label(body, textvariable=self.summary_var, style='SummaryOk.TLabel',
                                       anchor='w', justify='left', wraplength=860)
        self.summary_label.grid(row=2, column=0, columnspan=3, sticky='we', pady=(0, 6))

        log_holder = ttk.Frame(body, style='Card.TFrame')
        log_holder.grid(row=3, column=0, columnspan=3, sticky='nsew')
        log_holder.columnconfigure(0, weight=1)
        log_holder.rowconfigure(0, weight=1)
        self.log = tk.Text(log_holder, height=4, wrap='word', font=(self.font_ui[0], 9),
                           bg=PALETTE['log_bg'], fg=PALETTE['text'], relief='flat', borderwidth=1,
                           highlightthickness=1, highlightbackground=PALETTE['border'],
                           highlightcolor=PALETTE['accent'], insertbackground=PALETTE['text'],
                           padx=8, pady=4, state='disabled')
        self.log.grid(row=0, column=0, sticky='nsew')
        scroll = ttk.Scrollbar(log_holder, orient='vertical', command=self.log.yview)
        scroll.grid(row=0, column=1, sticky='ns')
        self.log.configure(yscrollcommand=scroll.set)

        # Status bar ---------------------------------------------------------
        bar = tk.Frame(self.root, bg=PALETTE['status_bg'])
        bar.grid(row=1, column=0, sticky='we')
        bar.columnconfigure(1, weight=1)
        self.status_bar = bar
        self.status_dot = tk.Label(bar, text='●', bg=PALETTE['status_bg'],
                                   fg=PALETTE['muted'], font=(self.font_ui[0], 9))
        self.status_dot.grid(row=0, column=0, sticky='w', padx=(16, 6), pady=5)
        self.status_var = tk.StringVar(value='就绪')
        tk.Label(bar, textvariable=self.status_var, bg=PALETTE['status_bg'], fg=PALETTE['text'],
                 font=self.font_small, anchor='w').grid(row=0, column=1, sticky='we', pady=5)
        self.path_var = tk.StringVar(value='')
        tk.Label(bar, textvariable=self.path_var, bg=PALETTE['status_bg'], fg=PALETTE['muted'],
                 font=self.font_small, anchor='e').grid(row=0, column=2, sticky='e',
                                                        padx=(8, 16), pady=5)

    # -- plumbing ----------------------------------------------------------
    def _install_traces(self):
        watched = ('name', 'owner', 'email', 'license_id', 'product', 'product_id',
                   'edition_id', 'license_type', 'description', 'issued_on',
                   'features', 'seats', 'path')
        for key in watched:
            self.vars[key].trace_add('write', self.refresh_state)
        # The name also drives the owner mirror and the owner hint text.
        self.vars['name'].trace_add('write', self._sync_owner_follow)
        self.owner_follow_var.trace_add('write', self._sync_owner_follow)
        # The install directory drives the default output path and the hints.
        self.vars['install_dir'].trace_add('write', self._on_install_dir_changed)
        self.vars['path'].trace_add('write', self._on_output_path_edit)
        for editor in self.editors.values():
            for var in editor.variables():
                var.trace_add('write', self.refresh_state)

    # -- install directory -------------------------------------------------
    def _default_output_path(self):
        directory = (getattr(self, 'install_dir', '') or '').strip()
        return os.path.join(directory, LICENSE_OUTPUT_NAME) if directory else ''

    def _describe_install_status(self, profile, prefix=''):
        if profile['version_ok'] is True:
            text = 'IDA %s%s' % (profile['version_text'],
                                 ',含 ida32.dll' if profile['has_ida32'] else '')
        elif profile['version_ok'] is None:
            text = '未确认版本(读不到 ida.dll 版本,请自行确认是 9.5)'
        else:
            text = '版本 %s,不是 9.5,禁止生成/打补丁' % profile['version_text']
        self.install_status_var.set((prefix + ':' if prefix else '') + text)

    def _describe_current_install(self):
        directory = self.vars['install_dir'].get().strip()
        if not directory:
            self.install_status_var.set('尚未选择 IDA 安装目录')
            return
        try:
            self._describe_install_status(inspect_install_dir(directory))
        except ValidationError as exc:
            self.install_status_var.set(str(exc).splitlines()[0])

    def _refresh_candidates(self):
        values = [profile['dir'] for profile in self.detected]
        self.candidate_box.configure(values=values)
        current = self.vars['install_dir'].get().strip()
        if values:
            self.candidate_var.set(current if current in values else '')
            self.install_status_var.set('检测到 %d 个候选,可下拉切换' % len(values))
        else:
            self.candidate_var.set('')
            self.install_status_var.set('未检测到候选:请浏览并手动选择')
        self._describe_current_install()

    def _update_backup_hint(self):
        directory = self.vars['install_dir'].get().strip()
        base = os.path.join(SCRIPT_DIR, BACKUP_DIR_NAME)
        if not os.path.isdir(base) and not _is_writable_dir(SCRIPT_DIR):
            fallback = (os.path.join(os.path.abspath(directory), BACKUP_DIR_NAME)
                        if directory and os.path.isdir(directory)
                        and _is_writable_dir(directory) else None)
            if not fallback:
                self.backup_hint_var.set('补丁备份不可用:脚本目录与 IDA 安装目录均不可写。')
                return
            base = fallback
        self.backup_hint_var.set('补丁备份:%s(每次应用创建时间戳子目录)'
                                 % _shorten_path(os.path.join(base, '<时间戳>'), 96))

    def _persist_install_dir(self):
        directory = self.vars['install_dir'].get().strip()
        if not directory:
            return False
        config = dict(self.config or {})
        config['install_dir'] = os.path.abspath(directory)
        try:
            save_config(config, install_dir=directory)
        except ValidationError as exc:
            self._set_status(str(exc), 'warn')
            return False
        self.config = config
        return True

    def _set_output_path(self, value):
        """Set the output path without marking it as a manual choice."""
        self._setting_output = True
        try:
            self.vars['path'].set(value)
        finally:
            self._setting_output = False

    def _on_output_path_edit(self, *_args):
        if not self._setting_output:
            self.path_manual = True

    def _on_install_dir_changed(self, *_args):
        if not self.path_manual:
            self._set_output_path(self._default_output_path())
        self._describe_current_install()
        self._update_backup_hint()
        self.refresh_state()

    def on_browse_install_dir(self):
        """Pick the IDA directory with an explicit folder dialog."""
        from tkinter import filedialog, messagebox
        current = self.vars['install_dir'].get().strip()
        initial = current if os.path.isdir(current) else SCRIPT_DIR
        directory = filedialog.askdirectory(parent=self.root, title='选择 IDA Pro 安装目录',
                                            initialdir=initial, mustexist=True)
        if not directory:
            return
        self.path_manual = False
        self.vars['install_dir'].set(os.path.abspath(directory))
        try:
            profile = inspect_install_dir(directory)
        except ValidationError as exc:
            self._set_status(str(exc), 'error')
            messagebox.showerror('目录不可用', str(exc), parent=self.root)
            return
        self._persist_install_dir()
        self._describe_install_status(profile, '已选择')
        self._set_status('已选择 IDA 安装目录:%s' % directory, 'ok')

    def on_pick_candidate(self, _event=None):
        directory = self.candidate_var.get().strip()
        if not directory:
            return
        self.path_manual = False
        self.vars['install_dir'].set(directory)
        self._persist_install_dir()

    def on_redetect(self):
        """Re-run detection; keep a still-valid manual choice."""
        from tkinter import messagebox
        self.detected = detect_install_dirs()
        self._refresh_candidates()
        current = self.vars['install_dir'].get().strip()
        current_ok = False
        if current:
            try:
                inspect_install_dir(current)
                current_ok = True
            except ValidationError:
                current_ok = False
        if not current_ok:
            if self.detected:
                self.path_manual = False
                self.vars['install_dir'].set(self.detected[0]['dir'])
                self._persist_install_dir()
            else:
                self.vars['install_dir'].set('')
                messagebox.showwarning('未检测到 IDA',
                                       '未检测到包含 ida.dll 的目录,请点击“浏览…”手动选择。',
                                       parent=self.root)
        if self.detected:
            self._set_status('检测完成:%d 个候选。' % len(self.detected), 'ok')
        else:
            self._set_status('检测完成:未找到候选,请手动选择。', 'warn')
        self.refresh_state()

    def on_browse_output(self):
        """Allow an explicit 'save as' target; it must be chosen by the user."""
        from tkinter import filedialog
        current = self.vars['path'].get().strip()
        initial = os.path.dirname(current) if current else self.vars['install_dir'].get().strip()
        if not os.path.isdir(initial):
            initial = SCRIPT_DIR
        path = filedialog.asksaveasfilename(parent=self.root, title='另存许可证',
                                            defaultextension='.hexlic',
                                            initialfile=LICENSE_OUTPUT_NAME,
                                            initialdir=initial,
                                            filetypes=[('IDA License', '*.hexlic'),
                                                       ('所有文件', '*.*')])
        if path:
            self.path_manual = True
            self.vars['path'].set(os.path.abspath(path))

    def on_reset_output(self):
        """Return the output path to ``<install dir>/idapro.hexlic``."""
        self.path_manual = False
        self._set_output_path(self._default_output_path())

    def _sync_owner_follow(self, *_args):
        """Keep owner bound to the payload name while 'follow name' is checked."""
        follow = self.owner_follow_var.get()
        try:
            self.owner_entry.configure(state='disabled' if follow else 'normal')
        except Exception:
            pass
        if follow:
            self.vars['owner'].set(self.vars['name'].get())
        if follow and not self.vars['name'].get().strip():
            self.owner_hint.configure(text='名称为空:请取消“跟随名称”并手填所有者\n'
                                           '引擎不显示该字段,任意字符串均安全')
        else:
            self.owner_hint.configure(text='引擎不显示该字段,任意字符串均安全\n'
                                           'add-on 的 owner 必须为 XX-XXXX-XXXX-XX')
        self.refresh_state()

    def _render_addons(self):
        self.addon_tree.delete(*self.addon_tree.get_children())
        for row in self.addon_rows:
            self.addon_tree.insert('', 'end', values=(row['code'], row['id'], row['owner'],
                                                      row['start_date'], row['end_date']))
        self.addon_count_var.set('共 %d 项(至少 1 项,组件有效期须在主许可周期内)'
                                 % len(self.addon_rows))

    def _selected_addon_index(self):
        selection = self.addon_tree.selection()
        if not selection:
            return None
        return self.addon_tree.index(selection[0])

    def _main_window_text(self):
        """Return the main start/end as strict strings, or ``None`` when invalid."""
        try:
            start = validate_date_parts(*self.editors['start'].parts(),
                                        '生效日期', START_TIME)
            end = validate_date_parts(*self.editors['end'].parts(),
                                      '到期日期', END_TIME)
        except ValidationError:
            return None, None
        return start, end

    def _addon_dialog(self, row=None):
        """Modal editor for one add-on entry; returns the row or ``None``."""
        dialog = self.tk.Toplevel(self.root)
        dialog.title('组件条目')
        dialog.transient(self.root)
        dialog.resizable(False, False)
        dialog.configure(bg=PALETTE['panel'])
        frame = self.ttk.Frame(dialog, style='Card.TFrame', padding=(14, 12, 14, 10))
        frame.grid(row=0, column=0, sticky='nsew')
        frame.columnconfigure(1, weight=1)

        current = dict(row or {})
        default_start, default_end = self._main_window_text()
        code_var = self.tk.StringVar(value=current.get('code', DEFAULT_ADDONS[0]))
        id_var = self.tk.StringVar(value=current.get('id', ADDON_ID_FMT % (len(self.addon_rows) + 1)))
        owner_var = self.tk.StringVar(value=current.get('owner', self.vars['license_id'].get()))
        start_var = self.tk.StringVar(value=current.get('start_date', default_start or ''))
        end_var = self.tk.StringVar(value=current.get('end_date', default_end or ''))
        message_var = self.tk.StringVar(value='')

        specs = (
            ('组件代码 (code)', self.ttk.Combobox(frame, textvariable=code_var,
                                                 values=list(DEFAULT_ADDONS), state='readonly',
                                                 style='Combo.TCombobox'), 0),
            ('组件 ID (id)', self.ttk.Entry(frame, textvariable=id_var, style='Field.TEntry'), 1),
            ('所有者 (owner)', self.ttk.Entry(frame, textvariable=owner_var, style='Field.TEntry'), 2),
            ('生效时间', self.ttk.Entry(frame, textvariable=start_var, style='Field.TEntry'), 3),
            ('到期时间', self.ttk.Entry(frame, textvariable=end_var, style='Field.TEntry'), 4),
        )
        for label, widget, row_index in specs:
            self.ttk.Label(frame, text=label, style='Card.TLabel').grid(
                row=row_index, column=0, sticky='w', padx=(0, 10), pady=4)
            widget.grid(row=row_index, column=1, sticky='we', pady=4)
        self.ttk.Label(frame, text='ID 形如 XX-XXXX-XXXX-XX;时间格式 YYYY-MM-DD HH:MM:SS',
                       style='Hint.TLabel').grid(row=5, column=0, columnspan=2, sticky='w')
        self.tk.Label(frame, textvariable=message_var, fg=PALETTE['error'], bg=PALETTE['panel'],
                      font=self.font_small, anchor='w', justify='left', wraplength=420).grid(
            row=6, column=0, columnspan=2, sticky='we', pady=(4, 2))

        result = {}

        def on_ok():
            candidate = {'code': code_var.get(), 'id': id_var.get(),
                         'owner': owner_var.get(), 'start_date': start_var.get(),
                         'end_date': end_var.get()}
            try:
                validate_addon_row(candidate, default_start, default_end)
            except ValidationError as exc:
                message_var.set(str(exc))
                return
            result.update(candidate)
            dialog.destroy()

        bar = self.ttk.Frame(frame, style='Card.TFrame')
        bar.grid(row=7, column=0, columnspan=2, sticky='e', pady=(6, 0))
        self.ttk.Button(bar, text='取消', style='Ghost.TButton',
                        command=dialog.destroy).pack(side='right')
        self.ttk.Button(bar, text='确定', style='Primary.TButton',
                        command=on_ok).pack(side='right', padx=(0, 8))
        dialog.grab_set()
        self.root.wait_window(dialog)
        return result or None

    def _add_addon(self):
        from tkinter import messagebox
        if len(self.addon_rows) >= ADDON_MAX:
            messagebox.showinfo('组件数量', '组件最多 %d 项。' % ADDON_MAX, parent=self.root)
            return
        entry = self._addon_dialog()
        if entry:
            self.addon_rows.append(entry)
            self._render_addons()
            self.refresh_state()

    def _edit_addon(self, event=None):
        index = self._selected_addon_index()
        if index is None:
            return
        entry = self._addon_dialog(self.addon_rows[index])
        if entry:
            self.addon_rows[index] = entry
            self._render_addons()
            self.refresh_state()

    def _remove_addon(self):
        from tkinter import messagebox
        index = self._selected_addon_index()
        if index is None:
            messagebox.showinfo('删除组件', '请先在表格中选择一行。', parent=self.root)
            return
        if len(self.addon_rows) <= 1:
            messagebox.showinfo('删除组件', '至少需要保留一个组件。', parent=self.root)
            return
        del self.addon_rows[index]
        self._render_addons()
        self.refresh_state()

    def _sync_addon_dates(self):
        from tkinter import messagebox
        start, end = self._main_window_text()
        if not start or not end:
            messagebox.showerror('同步日期', '主许可日期无效,无法同步。', parent=self.root)
            return
        for row in self.addon_rows:
            row['start_date'] = start
            row['end_date'] = end
        self._render_addons()
        self.refresh_state()

    def _guarded(self, func):
        """Wrap a Tk command so an unexpected exception never escapes the loop."""
        def wrapper(*_args, **_kwargs):
            try:
                return func()
            except Exception as exc:
                try:
                    self._set_status('内部错误: %s' % exc, 'error')
                except Exception:
                    pass
                return None
        return wrapper

    def _set_status(self, text, level='info'):
        colour = {'info': PALETTE['muted'], 'ok': PALETTE['ok'],
                  'warn': PALETTE['warn'], 'error': PALETTE['error']}.get(level, PALETTE['muted'])
        self.status_dot.configure(fg=colour)
        self.status_var.set(text)

    # -- state -------------------------------------------------------------
    def _collect_inputs(self):
        return dict(
            name=self.vars['name'].get(),
            owner=self.vars['owner'].get(),
            email=self.vars['email'].get(),
            license_id=self.vars['license_id'].get(),
            product=self.vars['product'].get(),
            product_id=self.vars['product_id'].get(),
            edition_id=self.vars['edition_id'].get(),
            license_type=self.vars['license_type'].get(),
            description=self.vars['description'].get(),
            issued_on=self.vars['issued_on'].get(),
            features=self.vars['features'].get(),
            seats=self.vars['seats'].get(),
            start_parts=self.editors['start'].parts(),
            end_parts=self.editors['end'].parts(),
            addons=self.collect_addons(),
            addon_rows=[dict(row) for row in self.addon_rows],
            out_path=self.vars['path'].get(),
            install_dir=self.vars['install_dir'].get(),
        )

    def collect_addons(self):
        return [row['code'] for row in self.addon_rows]

    def _normalize_seats(self):
        """Clamp the spinbox text on focus-out so it can never stay out of range."""
        try:
            value = int(self.vars['seats'].get().strip())
        except ValueError:
            value = SEAT_MIN
        self.vars['seats'].set(str(max(SEAT_MIN, min(SEAT_MAX, value))))
        self.refresh_state()

    def refresh_state(self, *_args):
        try:
            self._refresh_state()
        except Exception as exc:
            self._set_status('界面刷新失败: %s' % exc, 'error')

    def _refresh_state(self):
        if not self._ready:
            return
        _values, errors = validate_fields(**self._collect_inputs())
        invalid = [key for key in FIELD_ORDER if errors.get(key)]
        self._apply_errors(errors)

        if invalid:
            self.summary_var.set('存在 %d 项无效输入:%s'
                                 % (len(invalid), '、'.join(FIELD_LABELS[key] for key in invalid)))
            self.summary_label.configure(style='SummaryError.TLabel')
            self.generate_btn.configure(state='disabled')
            self._set_status('输入校验未通过,生成按钮已禁用。', 'warn')
        else:
            self.summary_var.set('输入校验通过,可以生成许可证。')
            self.summary_label.configure(style='SummaryOk.TLabel')
            self.generate_btn.configure(state='normal')
            self._set_status('输入校验通过,等待生成。', 'info')

        raw_path = self.vars['path'].get().strip()
        self.path_var.set(_shorten_path(os.path.abspath(raw_path)) if raw_path else '(未指定输出路径)')

    def _apply_errors(self, errors):
        for key in FIELD_ORDER:
            message = errors.get(key, '')
            label = self.error_labels.get(key)
            if label is not None:
                label.configure(text=message)
            control = self.controls.get(key)
            if control is not None:
                widget, normal_style, error_style = control
                widget.configure(style=error_style if message else normal_style)
            editor = self.editors.get(key)
            if editor is not None:
                editor.set_error(bool(message))

    def append_log(self, text):
        self.log.configure(state='normal')
        self.log.insert('end', text + '\n')
        self.log.see('end')
        self.log.configure(state='disabled')
        if not write_log_line(text, self.vars['install_dir'].get().strip() or None):
            if not self._log_warned:
                self._log_warned = True
                self._set_status('脚本目录与 IDA 安装目录均不可写,日志无法落盘。', 'warn')

    def on_import_license(self):
        """Load an existing .hexlic and backfill the whole form (source stays untouched)."""
        from tkinter import filedialog, messagebox
        path = filedialog.askopenfilename(parent=self.root, title='选择现有许可证',
                                          filetypes=[('IDA License', '*.hexlic'),
                                                     ('所有文件', '*.*')])
        if not path:
            return
        try:
            imported = load_license_file(path)
        except Exception as exc:
            self._set_status('导入失败:%s' % exc, 'error')
            messagebox.showerror('导入失败', '无法解析该许可证:\n%s' % exc, parent=self.root)
            return
        self._apply_import(imported)
        self.append_log('已从 %s 导入许可证字段(源文件未改动)。' % path)
        self._set_status('已导入许可证字段,可在此基础上修改后重新生成。', 'ok')

    def _apply_import(self, imported):
        """Copy parsed license values into the form widgets."""
        self.owner_follow_var.set(False)        # keep the imported owner verbatim
        # ``product`` is a read-only constant and is deliberately not imported.
        for key in ('name', 'owner', 'email', 'license_id', 'product_id',
                    'edition_id', 'license_type', 'description', 'issued_on', 'seats'):
            self.vars[key].set(imported.get(key) or '')
        self.vars['features'].set(', '.join(imported.get('features') or []))
        for key in ('start', 'end'):
            parts = self._parse_date_text(imported.get('%s_date' % key))
            if parts:
                self.editors[key].set_date(*parts)
        self.addon_rows = [dict(row) for row in (imported.get('addon_rows') or [])]
        self._render_addons()
        self.refresh_state()

    @staticmethod
    def _parse_date_text(text):
        try:
            moment = _dt.datetime.strptime((text or '').strip(), DATE_FMT)
        except (TypeError, ValueError):
            return None
        return moment.year, moment.month, moment.day

    # -- patch actions -----------------------------------------------------
    def _patch_directory(self):
        directory = self.vars['install_dir'].get()
        absolute = validate_install_dir(directory)
        self._persist_install_dir()
        return absolute

    def _fill_patch_tree(self, analyses, missing):
        self.patch_tree.delete(*self.patch_tree.get_children())
        for analysis in analyses:
            seeds = analysis['seeds']
            offsets = ', '.join('0x%X' % seed['offset'] for seed in seeds) or '-'
            vas = ', '.join(('0x%X' % seed['va']) if seed.get('va') is not None else '-'
                            for seed in seeds) or '-'
            self.patch_tree.insert('', 'end', values=(
                os.path.basename(analysis['path']), offsets, vas, analysis['sha256'],
                len(seeds), STATE_LABELS[analysis['state']]),
                tags=(STATE_TAGS[analysis['state']],))
        for name in missing:
            self.patch_tree.insert('', 'end',
                                   values=(name, '-', '-', '-', 0, '未找到文件'),
                                   tags=('state_unknown',))

    def _describe_patch_summary(self, analyses, missing):
        parts = []
        for analysis in analyses:
            parts.append('%s:%s(%d 个副本)' % (os.path.basename(analysis['path']),
                                                STATE_LABELS[analysis['state']],
                                                len(analysis['seeds'])))
        if missing:
            parts.append('未找到:%s' % '、'.join(missing))
        return ';'.join(parts)

    def on_analyze(self):
        from tkinter import messagebox
        try:
            directory = self._patch_directory()
        except ValidationError as exc:
            self._set_status(str(exc), 'error')
            messagebox.showerror('无法分析', str(exc), parent=self.root)
            return
        self._set_status('正在扫描 DLL 种子…', 'info')
        self.root.update_idletasks()
        try:
            analyses, missing = analyze_install_dir(directory)
        except Exception as exc:
            self._set_status('分析失败:%s' % exc, 'error')
            messagebox.showerror('分析失败', '无法读取 DLL:\n%s' % exc, parent=self.root)
            return
        if not analyses:
            text = '目录下未找到 ida.dll / ida32.dll:\n%s' % directory
            self._set_status('未找到可处理的 DLL。', 'error')
            messagebox.showerror('未找到 DLL', text, parent=self.root)
            return

        self.patch_analyses = analyses
        self._fill_patch_tree(analyses, missing)
        summary = self._describe_patch_summary(analyses, missing)
        self.patch_info_var.set(summary)
        for analysis in analyses:
            offsets = ', '.join('0x%X' % seed['offset'] for seed in analysis['seeds']) or '-'
            self.append_log('%s:%s,副本 %d 个,偏移 %s,SHA-256 %s'
                            % (analysis['path'], STATE_LABELS[analysis['state']],
                               len(analysis['seeds']), offsets, analysis['sha256']))
        self.patch_ready = any(analysis['state'] == STATE_TARGET for analysis in analyses)
        has_factory = any(analysis['state'] == STATE_FACTORY for analysis in analyses)
        if has_factory:
            self._set_status('分析完成:发现原厂种子,可应用补丁。' + summary, 'warn')
        elif self.patch_ready:
            self._set_status('分析完成:已是目标种子,无需改动。' + summary, 'ok')
        else:
            self._set_status('分析完成:未识别到种子,拒绝打补丁。', 'error')
        self.patch_info_label.configure(
            style='SummaryError.TLabel' if not (has_factory or self.patch_ready) else 'SummaryOk.TLabel')

    def on_apply_patch(self):
        from tkinter import messagebox
        try:
            directory = self._patch_directory()
        except ValidationError as exc:
            self._set_status(str(exc), 'error')
            messagebox.showerror('无法应用补丁', str(exc), parent=self.root)
            return
        self._set_status('正在预检(dry-run,不写盘)…', 'info')
        self.root.update_idletasks()
        try:
            analyses, missing = analyze_install_dir(directory)
        except Exception as exc:
            self._set_status('预检失败:%s' % exc, 'error')
            messagebox.showerror('预检失败', '无法读取 DLL:\n%s' % exc, parent=self.root)
            return
        if not analyses:
            text = '目录下未找到 ida.dll / ida32.dll:\n%s' % directory
            self._set_status('未找到可处理的 DLL。', 'error')
            messagebox.showerror('未找到 DLL', text, parent=self.root)
            return

        self.patch_analyses = analyses
        self._fill_patch_tree(analyses, missing)
        plan = preview_patch(analyses)
        if plan['errors']:
            text = '\n'.join(plan['errors'])
            self.append_log('预检失败,未写入任何文件:\n' + text)
            self._set_status('预检失败,未写入任何文件。', 'error')
            messagebox.showerror('预检失败', text, parent=self.root)
            return
        if plan['no_change']:
            text = '\n'.join(plan['skipped']) or '所有文件已是目标种子,无需改动。'
            self.append_log(text)
            self.patch_info_var.set('无需改动:所有种子副本已派生为 C_MODULUS。')
            self.patch_ready = True
            self._set_status('无需改动:已是目标种子,未写入、未备份。', 'ok')
            messagebox.showinfo('无需改动', text, parent=self.root)
            return

        try:
            backup_root = resolve_backup_root(directory)
        except ValidationError as exc:
            self._set_status(str(exc), 'error')
            messagebox.showerror('无法创建备份', str(exc), parent=self.root)
            return
        lines = ['将改动 %d 个种子副本,共 %d 字节(dry-run 结果,尚未写盘):'
                 % (plan['total_blocks'], plan['total_bytes'])]
        for item in plan['files']:
            offsets = ', '.join('0x%X' % block['offset'] for block in item['blocks'])
            lines.append('%s:%d 块,偏移 %s' % (os.path.basename(item['path']),
                                              len(item['blocks']), offsets))
        lines.append('')
        lines.append('备份目录:%s' % backup_root)
        detail = '\n'.join(lines)
        self.append_log(detail)
        self.patch_info_var.set(lines[0])
        if not messagebox.askyesno('确认应用补丁', detail + '\n\n确认执行写入与备份?',
                                   parent=self.root):
            self._set_status('已取消,未写入任何文件。', 'warn')
            self.append_log('已取消:用户拒绝执行补丁。')
            return

        self._set_status('正在应用补丁并校验…', 'info')
        self.root.update_idletasks()
        result = apply_patch(analyses, backup_root=backup_root)
        if not result['ok']:
            text = '\n'.join(result['errors'])
            self.append_log('补丁失败:\n' + text)
            self._set_status('补丁失败,已尝试用备份回滚。', 'error')
            messagebox.showerror('补丁失败', text, parent=self.root)
            return

        try:
            refreshed, missing_after = analyze_install_dir(directory)
            self.patch_analyses = refreshed
            self._fill_patch_tree(refreshed, missing_after)
        except Exception:
            refreshed = []
        self.patch_manifest = result['manifest']
        self.patch_ready = True
        summary = '补丁完成:%d 个文件,%d 个块;写后校验通过。' % (
            len(result['files']), plan['total_blocks'])
        self.append_log(summary)
        self.append_log('补丁清单:%s' % result['manifest'])
        for analysis in refreshed:
            self.append_log('%s:%s,新 SHA-256 %s'
                            % (analysis['path'], STATE_LABELS[analysis['state']],
                               analysis['sha256']))
        self.patch_info_var.set(summary + ' 清单:' + _shorten_path(result['manifest'], 70))
        self._set_status(summary, 'ok')
        messagebox.showinfo('补丁完成',
                            '%s\n\n备份与清单:%s\n\n下次重复执行会识别为「已是目标种子」,不会重复写入。'
                            % (summary, result['manifest']), parent=self.root)

    def on_rollback(self):
        from tkinter import filedialog, messagebox
        initial = self.patch_manifest or ''
        kwargs = {'parent': self.root, 'title': '选择补丁清单',
                  'filetypes': [('补丁清单', '*.json'), ('所有文件', '*.*')]}
        initial_dir = os.path.dirname(initial) if initial else ''
        if not initial_dir:
            try:
                initial_dir = resolve_backup_root(self.vars['install_dir'].get().strip() or None)
            except ValidationError:
                initial_dir = SCRIPT_DIR
        if initial_dir:
            kwargs['initialdir'] = initial_dir
        if initial:
            kwargs['initialfile'] = os.path.basename(initial)
        manifest_path = filedialog.askopenfilename(**kwargs)
        if not manifest_path:
            return
        try:
            manifest = load_manifest(manifest_path)
        except Exception as exc:
            self._set_status('补丁清单无效:%s' % exc, 'error')
            messagebox.showerror('补丁清单无效', str(exc), parent=self.root)
            return
        detail = '\n'.join('%s ← %s' % (entry['path'], entry['backup'])
                           for entry in manifest['files'])
        if not messagebox.askyesno('确认回滚', '将从备份还原以下文件:\n\n' + detail,
                                   parent=self.root):
            self._set_status('已取消回滚。', 'warn')
            return
        self._set_status('正在回滚并校验 SHA-256…', 'info')
        self.root.update_idletasks()
        result = rollback_manifest(manifest_path)
        if not result['ok']:
            text = '\n'.join(result['errors'])
            self.append_log('回滚失败:\n' + text)
            self._set_status('回滚失败:%s' % text, 'error')
            messagebox.showerror('回滚失败', text, parent=self.root)
            return
        for entry in result['files']:
            self.append_log('已还原 %s,SHA-256 %s(与原值一致)' % (entry['path'], entry['sha256']))
        self._set_status('回滚完成:SHA-256 已恢复为原值。', 'ok')
        self.patch_ready = False
        try:
            directory = validate_install_dir(self.vars['install_dir'].get())
        except ValidationError:
            directory = ''
        if directory and os.path.isdir(directory):
            try:
                analyses, missing = analyze_install_dir(directory)
                self.patch_analyses = analyses
                self._fill_patch_tree(analyses, missing)
                self.patch_info_var.set('回滚后:' + self._describe_patch_summary(analyses, missing))
                self.patch_ready = any(a['state'] == STATE_TARGET for a in analyses)
            except Exception:
                pass
        messagebox.showinfo('回滚完成', '已从备份还原并校验 SHA-256。', parent=self.root)

    # -- actions -----------------------------------------------------------
    def on_generate(self):
        from tkinter import messagebox
        values, errors = validate_fields(**self._collect_inputs())
        invalid = [key for key in FIELD_ORDER if errors.get(key)]
        self._apply_errors(errors)
        if invalid:
            report = format_error_summary(errors)
            self.append_log('校验未通过:\n' + report)
            self._set_status('校验未通过,请修正 %d 项无效输入。' % len(invalid), 'error')
            messagebox.showerror('输入无效', report, parent=self.root)
            return

        path = values['path']
        self._persist_install_dir()
        if os.path.exists(path):
            if not messagebox.askyesno('确认覆盖', '目标文件已存在,是否覆盖?\n%s' % path,
                                       parent=self.root):
                self.append_log('已取消:目标文件已存在,用户拒绝覆盖 %s' % path)
                self._set_status('已取消,目标文件未改动。', 'warn')
                return

        try:
            license_obj = build_license(values)
            ok, detail = back_verify_public(license_obj['payload'], license_obj['signature'])
            if not ok:
                raise RuntimeError('签名回代校验失败: %s' % detail)
            text = write_license(license_obj, path)
        except Exception as exc:
            self.append_log('生成失败:%s' % exc)
            self._set_status('生成失败:%s' % exc, 'error')
            messagebox.showerror('生成失败', '无法写入许可证:\n%s' % exc, parent=self.root)
            return

        size = len(text.encode('utf-8'))
        self.append_log('已生成 %s(%d 字节,签名回代校验:%s)' % (path, size, detail))
        if self.patch_ready:
            self._set_status('生成成功:%d 字节,e=%d 回代校验通过。%s' % (size, E_PUBLIC, detail), 'ok')
            messagebox.showinfo('生成成功', '许可证已写入:\n%s\n\n文件大小:%d 字节' % (path, size),
                                parent=self.root)
        else:
            note = '许可证需配合已打补丁的 DLL 才能被接受。'
            self.append_log('提示:%s' % note)
            self._set_status('生成成功:%d 字节;%s' % (size, note), 'warn')
            messagebox.showinfo('生成成功',
                                '许可证已写入:\n%s\n\n文件大小:%d 字节\n\n提示:%s'
                                % (path, size, note), parent=self.root)


def launch_gui():
    import tkinter as tk
    root = tk.Tk()
    app = KeygenApp(root)
    return root


def main():
    root = launch_gui()
    try:
        root.mainloop()
    except KeyboardInterrupt:
        pass
    return 0


if __name__ == '__main__':
    sys.exit(main())

ps

alt text

posted @ 2026-11-05 10:50  DirWangK  阅读(635)  评论(1)    收藏  举报