kami-armor 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 yuge666
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: kami-armor
3
+ Version: 0.1.0
4
+ Summary: 卡密 license-system client SDK + server-bound Python source protection (encrypt / obfuscate / Cython / one-command packaging)
5
+ Author: yuge666
6
+ License: MIT
7
+ Project-URL: Homepage, https://pypi.org/project/kami-armor/
8
+ Keywords: license,卡密,drm,obfuscation,source-protection,pyarmor-alternative,cython,activation
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Security
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: cryptography>=41.0
18
+ Requires-Dist: py-machineid>=0.6
19
+ Provides-Extra: harden
20
+ Requires-Dist: cython>=3.0; extra == "harden"
21
+ Requires-Dist: pyinstaller>=6.0; extra == "harden"
22
+ Requires-Dist: tomli; python_version < "3.11" and extra == "harden"
23
+ Dynamic: license-file
24
+
25
+ # kami-armor
26
+
27
+ **卡密(license)系统的 Python 客户端 SDK + 服务端绑定密钥的源码保护工具链。**
28
+
29
+ - 🔑 **客户端 SDK**(`kami_client`):在线激活 / 校验 / 心跳 / 解绑、价值闸门调用、按授权解锁加密资源、完整性自测量——只内嵌**公钥**,离线验签,永远拿不到可伪造卡密的私钥。
30
+ - 🛡 **源码保护**(`kami_armor`):把 Python 模块加密成密文随程序分发,**发布物里没有密钥**,运行时经服务器按授权下发密钥、内存解密导入。比 PyArmor 强在一个结构性维度——**密钥托管**(PyArmor 的密钥静态内嵌、可离线脱壳;这里密钥根本不在文件里,可吊销/溯源)。
31
+ - 🧩 **混淆 + 原生编译 + 一键打包**:自建免费的改名/字符串加密(symtable 保证不改坏代码)、Cython 原生编译皇冠模块、`kami-armor harden` 一条命令 混淆→Cython→加密→PyInstaller/Nuitka 出 exe。
32
+
33
+ > ⚠️ 这是**客户端库**,需要配合一个 **kami 授权服务器**(你自建/自部署的单文件 Go 服务)才能工作。SDK 只负责和你的服务器对话。
34
+
35
+ ## 安装
36
+
37
+ ```bash
38
+ pip install kami-armor
39
+ # 需要"一键打包/Cython"功能时(构建期工具):
40
+ pip install "kami-armor[harden]"
41
+ ```
42
+
43
+ ## 客户端 SDK 快速上手
44
+
45
+ ```python
46
+ from kami_client import KamiClient, LicenseError
47
+
48
+ client = KamiClient("https://license.example.com", "你的产品代号", "<服务器公钥HEX>")
49
+ try:
50
+ lic = client.validate() # 先用缓存/在线校验
51
+ except LicenseError:
52
+ lic = client.activate(user_code) # 首次激活(卡密)
53
+
54
+ if lic.has_feature("premium"):
55
+ out, quota = client.gated("premium", {"k": "v"}, cost=1) # 价值在服务端执行
56
+ key = client.unlock("model") # 按授权拿密钥
57
+ data = client.decrypt_resource(sealed_bytes, key) # 仅内存解密
58
+ client.attest("build-1") # 可选:完整性证明
59
+
60
+ # 可选:后台心跳(实时在线 + 即时感知吊销/踢下线)
61
+ stop = client.start_heartbeat # 见文档
62
+ ```
63
+
64
+ ## 源码保护(kami_armor)
65
+
66
+ ```python
67
+ import kami_armor
68
+ # 构建期:加密模块 + 注册密钥(密钥不进发布物)
69
+ kami_armor.build([{"src": "core/algo.py", "module": "core.algo",
70
+ "resource": "algo_v1", "feature": "premium", "keep": ["compute"]}],
71
+ admin_url="https://license.example.com", token="<后台JWT>")
72
+ ```
73
+ ```python
74
+ # 运行期:装上加密导入
75
+ from kami_client import KamiClient
76
+ import kami_armor
77
+ client = KamiClient(url, product, pubkey); client.validate()
78
+ kami_armor.install(client, "dist_protected/manifest.json")
79
+ import core.algo # ← 经服务器按授权解密后才能导入
80
+ ```
81
+
82
+ 命令行:
83
+
84
+ ```bash
85
+ # 只做混淆(改名+字符串加密,供 Cython/Nuitka 用)
86
+ python -m kami_armor obfuscate core/algo.py -o core/algo_obf.py --keep run
87
+ # 一键:混淆→Cython→加密→打包出 exe
88
+ python -m kami_armor harden --config kami-harden.toml
89
+ ```
90
+
91
+ ## 诚实定位
92
+
93
+ 客户端的混淆/加密只能**抬高破解成本**,不是绝对保密——解密后的代码运行时仍可能被持有效授权的攻击者内存 dump(CPython 的硬限制,所有方案都一样)。真正耐久的保护是:**把价值与密钥留在服务端**(价值闸门 + 按授权发密钥),并用**比 crack 传播更快的吊销与更新**让破解迅速过期。本库正是围绕这一原则设计。
94
+
95
+ ## License
96
+
97
+ MIT © yuge666
@@ -0,0 +1,73 @@
1
+ # kami-armor
2
+
3
+ **卡密(license)系统的 Python 客户端 SDK + 服务端绑定密钥的源码保护工具链。**
4
+
5
+ - 🔑 **客户端 SDK**(`kami_client`):在线激活 / 校验 / 心跳 / 解绑、价值闸门调用、按授权解锁加密资源、完整性自测量——只内嵌**公钥**,离线验签,永远拿不到可伪造卡密的私钥。
6
+ - 🛡 **源码保护**(`kami_armor`):把 Python 模块加密成密文随程序分发,**发布物里没有密钥**,运行时经服务器按授权下发密钥、内存解密导入。比 PyArmor 强在一个结构性维度——**密钥托管**(PyArmor 的密钥静态内嵌、可离线脱壳;这里密钥根本不在文件里,可吊销/溯源)。
7
+ - 🧩 **混淆 + 原生编译 + 一键打包**:自建免费的改名/字符串加密(symtable 保证不改坏代码)、Cython 原生编译皇冠模块、`kami-armor harden` 一条命令 混淆→Cython→加密→PyInstaller/Nuitka 出 exe。
8
+
9
+ > ⚠️ 这是**客户端库**,需要配合一个 **kami 授权服务器**(你自建/自部署的单文件 Go 服务)才能工作。SDK 只负责和你的服务器对话。
10
+
11
+ ## 安装
12
+
13
+ ```bash
14
+ pip install kami-armor
15
+ # 需要"一键打包/Cython"功能时(构建期工具):
16
+ pip install "kami-armor[harden]"
17
+ ```
18
+
19
+ ## 客户端 SDK 快速上手
20
+
21
+ ```python
22
+ from kami_client import KamiClient, LicenseError
23
+
24
+ client = KamiClient("https://license.example.com", "你的产品代号", "<服务器公钥HEX>")
25
+ try:
26
+ lic = client.validate() # 先用缓存/在线校验
27
+ except LicenseError:
28
+ lic = client.activate(user_code) # 首次激活(卡密)
29
+
30
+ if lic.has_feature("premium"):
31
+ out, quota = client.gated("premium", {"k": "v"}, cost=1) # 价值在服务端执行
32
+ key = client.unlock("model") # 按授权拿密钥
33
+ data = client.decrypt_resource(sealed_bytes, key) # 仅内存解密
34
+ client.attest("build-1") # 可选:完整性证明
35
+
36
+ # 可选:后台心跳(实时在线 + 即时感知吊销/踢下线)
37
+ stop = client.start_heartbeat # 见文档
38
+ ```
39
+
40
+ ## 源码保护(kami_armor)
41
+
42
+ ```python
43
+ import kami_armor
44
+ # 构建期:加密模块 + 注册密钥(密钥不进发布物)
45
+ kami_armor.build([{"src": "core/algo.py", "module": "core.algo",
46
+ "resource": "algo_v1", "feature": "premium", "keep": ["compute"]}],
47
+ admin_url="https://license.example.com", token="<后台JWT>")
48
+ ```
49
+ ```python
50
+ # 运行期:装上加密导入
51
+ from kami_client import KamiClient
52
+ import kami_armor
53
+ client = KamiClient(url, product, pubkey); client.validate()
54
+ kami_armor.install(client, "dist_protected/manifest.json")
55
+ import core.algo # ← 经服务器按授权解密后才能导入
56
+ ```
57
+
58
+ 命令行:
59
+
60
+ ```bash
61
+ # 只做混淆(改名+字符串加密,供 Cython/Nuitka 用)
62
+ python -m kami_armor obfuscate core/algo.py -o core/algo_obf.py --keep run
63
+ # 一键:混淆→Cython→加密→打包出 exe
64
+ python -m kami_armor harden --config kami-harden.toml
65
+ ```
66
+
67
+ ## 诚实定位
68
+
69
+ 客户端的混淆/加密只能**抬高破解成本**,不是绝对保密——解密后的代码运行时仍可能被持有效授权的攻击者内存 dump(CPython 的硬限制,所有方案都一样)。真正耐久的保护是:**把价值与密钥留在服务端**(价值闸门 + 按授权发密钥),并用**比 crack 传播更快的吊销与更新**让破解迅速过期。本库正是围绕这一原则设计。
70
+
71
+ ## License
72
+
73
+ MIT © yuge666
@@ -0,0 +1,77 @@
1
+ # kami-armor — 服务端绑定密钥的 Python 源码保护(自建 / 免费)
2
+
3
+ 比 PyArmor 强在**一个结构性维度:密钥托管**。PyArmor 的 AES 密钥是静态内嵌、可
4
+ 离线算出(2025 年被公开脚本 G DATA / Lil-House 1shot 静态脱壳 8.0–9.2.x)。
5
+ kami-armor 把模块加密成密文(.kam)随程序分发,**发布物里没有密钥**;运行时由 kami
6
+ 服务器(`/v1/unlock`,需有效授权 + 设备绑定)按会话下发密钥,内存解密执行。
7
+ 于是:离线无法解密、密钥可吊销/轮换/限流、可按客户溯源。并且修正了 PyArmor 的
8
+ GCM 不校验 tag 的缺陷(这里用标准 AES-256-GCM 且校验)。
9
+
10
+ ## 用法
11
+
12
+ **1) 构建期:加密模块 + 注册密钥**
13
+ ```python
14
+ import kami_armor
15
+ kami_armor.build([
16
+ {"src": "core/algo.py", "module": "core.algo", "resource": "algo_v1", "feature": "premium"},
17
+ {"src": "core/pricing.py", "module": "core.pricing", "resource": "pricing_v1"},
18
+ ], admin_url="https://license.example.com", token="<后台JWT>") # 或 apikey="..."
19
+ # 产出 dist_protected/{algo_v1.kam, pricing_v1.kam, manifest.json}
20
+ ```
21
+ 或命令行:`python -m kami_armor pack core/algo.py --module core.algo --resource algo_v1 --url ... --token ...`
22
+
23
+ 发布时**只带 .kam 密文 + manifest.json**,删掉源 .py。
24
+
25
+ **2) 运行期:装上加密导入**
26
+ ```python
27
+ from kami_client import KamiClient
28
+ import kami_armor
29
+
30
+ client = KamiClient("https://license.example.com", "你的产品代号", "<公钥HEX>")
31
+ client.validate() # 先校验授权(否则下面 unlock 会失败)
32
+ kami_armor.install(client, "dist_protected/manifest.json")
33
+
34
+ import core.algo # ← 经服务器按授权取密钥,内存解密后才可导入
35
+ core.algo.run(...)
36
+ ```
37
+ 授权无效/过期/吊销/被踢 → `unlock` 失败 → 导入失败。
38
+
39
+ ## AST 预处理:改名 + 字符串加密(自建免费 RFT / mix-str)
40
+
41
+ `kami_armor.obfuscate` 在**编译/加密之前**对源码做一遍语法树改写,抹掉"白送给逆向者的地图"——可读的名字与字符串。补 Nuitka 泄露符号名、Cython 泄露属性串的洞。
42
+
43
+ ```python
44
+ from kami_armor import obfuscate_source
45
+ new_src = obfuscate_source(open("core/algo.py").read(), keep=["run", "PriceEngine"])
46
+ # 或命令行:python -m kami_armor obfuscate core/algo.py -o core/algo_obf.py --keep run,PriceEngine
47
+ # 打包时一步到位:kami_armor.build([...], obfuscate=True) / pack --obfuscate --keep run
48
+ ```
49
+
50
+ - **改名**:只改模块级、全局唯一、无遮蔽、非公开 API(不在 `keep`/`__all__`)、非导入的私有名(用 CPython 的 `symtable` 做作用域分析,构造即正确);参数名/属性名/builtins/dunder 一律不动。
51
+ - **字符串加密**:字符串常量换成 `_kdec("…")`(XOR+base64,运行时同值);严格跳过 docstring(直接删)、类型注解、f-string、`match` 模式、bytes。
52
+ - **安全保证**:经行为等价测试(原版 vs 混淆版输出逐一比对,覆盖闭包/推导式/类/global/f-string/match)。`keep` 里务必列上对外公开、会被别的模块按名引用的 API。
53
+
54
+ ## 和 Cython 一起用(推荐)
55
+ - **最值钱的 5–20 个函数** → 用 `scripts/cythonize-crown.py` 编译成原生 .pyd/.so(无字节码、连内存 dump 出来的也是机器码,不是代码对象)。
56
+ - **其余受保护模块** → kami-armor 加密(拿到"无静态密钥 + 吊销 + 溯源")。
57
+ - **最值钱的逻辑** → 直接用价值闸门 `/v1/gated` 留服务端(唯一真·保密)。
58
+
59
+ ## 一键打包:`kami harden`(回到"配置→一条命令→出 exe")
60
+
61
+ 像 PyArmor 那样一条龙,但底层是在线授权(密钥不在 exe 里)。配置见仓库根 `kami-harden.toml`:
62
+
63
+ ```bash
64
+ set KAMI_ADMIN_TOKEN=<后台JWT>
65
+ python -m kami_armor harden --config kami-harden.toml
66
+ ```
67
+ 它依次做:(Cython 皇冠模块)→ 混淆(改名+字符串加密)→ kami-armor 加密+注册密钥 →
68
+ 生成运行时引导(PyInstaller runtime-hook / Nuitka boot)→ 调打包器出 exe → 登记构建哈希给 attest。
69
+
70
+ - **PyInstaller vs Nuitka**:纯论保护 Nuitka 更强(整 app 变原生,无 .pyc 可反编译);论省事/兼容 PyInstaller 更好。在本系统里值钱模块已被 kami-armor/Cython 保护,PyInstaller 足够;要连胶水也变原生再上 Nuitka。`[project] packager=` 切换。Nuitka 需 C 编译器。
71
+ - **终端用户授权**:生成的 exe 启动时先在线校验;未激活则读环境变量 `KAMI_CODE` 或同目录 `license.key` 激活。
72
+ - 已实测:PyInstaller 路径产出真 exe,运行即在线激活 + 服务端绑定密钥加载受保护模块。
73
+
74
+ ## 诚实边界(务必读)
75
+ - 模块解密后,代码对象仍在 CPython 内存里——**持有效授权的动态攻击者**仍能 dump(gc 遍历 / Frida 钩 marshal / 自建 CPython)。这是 CPython 的硬天花板,PyArmor 也一样,谁都过不去。
76
+ - 所以 kami-armor 的真实价值是 **发行控制 / 反传播 / 吊销 / 溯源**,不是"反逆向"。要真正藏住逻辑,只有:① Cython 把它变机器码(抬到原生逆向);② 干脆不下发,放服务端价值闸门。
77
+ - 在线依赖:纯离线客户用不了(缓存密钥会把密钥放回设备,重蹈 PyArmor)。
@@ -0,0 +1,14 @@
1
+ """kami-armor:服务端绑定密钥的 Python 源码保护(自建、免费)。
2
+
3
+ - 构建期:pack/build 把模块加密成 .kam 密文 + 注册密钥到 kami(密钥不进发布物)。
4
+ - 运行期:install(client, manifest) 安装加密导入;导入时经服务器按授权取密钥内存解密。
5
+
6
+ 详见本目录 README.md(含诚实边界与 Cython 联合使用建议)。
7
+ """
8
+ from .loader import install, KamiArmorFinder
9
+ from .pack import pack_module, build
10
+ from .obfuscate import obfuscate_source, obfuscate_file
11
+ from .harden import harden, load_config
12
+
13
+ __all__ = ["install", "KamiArmorFinder", "pack_module", "build",
14
+ "obfuscate_source", "obfuscate_file", "harden", "load_config"]
@@ -0,0 +1,72 @@
1
+ """kami-armor CLI:
2
+ python -m kami_armor pack <src.py> --module mypkg.secret --resource res1 \
3
+ --url http://host:8787 --token <JWT> [--apikey K] [--feature F] [--out dist_protected]
4
+ 多次 pack 会累积写入同一 out/manifest.json。
5
+ """
6
+ import argparse
7
+ import json
8
+ import os
9
+
10
+ from .pack import pack_module
11
+ from .obfuscate import obfuscate_file
12
+ from .harden import harden, load_config
13
+
14
+
15
+ def _keeplist(s):
16
+ return tuple(x.strip() for x in s.split(",") if x.strip())
17
+
18
+
19
+ def main():
20
+ ap = argparse.ArgumentParser(prog="kami_armor")
21
+ sub = ap.add_subparsers(dest="cmd")
22
+
23
+ p = sub.add_parser("pack", help="加密一个模块并注册密钥")
24
+ p.add_argument("src")
25
+ p.add_argument("--module", required=True, help="导入名,如 mypkg.secret")
26
+ p.add_argument("--resource", required=True, help="kami 资源名(唯一)")
27
+ p.add_argument("--url", required=True, help="后台地址,如 http://host:8787")
28
+ p.add_argument("--token", default="", help="后台登录 JWT")
29
+ p.add_argument("--apikey", default="", help="或用后台 API Key")
30
+ p.add_argument("--feature", default="", help="解锁需要的功能/授权")
31
+ p.add_argument("--out", default="dist_protected")
32
+ p.add_argument("--obfuscate", action="store_true", help="打包前先跑 AST 改名+字符串加密")
33
+ p.add_argument("--keep", default="", help="逗号分隔的公开 API 名(不可改名)")
34
+
35
+ o = sub.add_parser("obfuscate", help="只做 AST 预处理(改名+字符串加密),产出源码")
36
+ o.add_argument("src")
37
+ o.add_argument("-o", "--out", required=True, help="输出 .py 路径")
38
+ o.add_argument("--keep", default="", help="逗号分隔的公开 API 名(不可改名)")
39
+ o.add_argument("--no-rename", action="store_true")
40
+ o.add_argument("--no-encrypt-strings", action="store_true")
41
+
42
+ h = sub.add_parser("harden", help="一键编排:混淆→Cython→加密→打包出 exe")
43
+ h.add_argument("--config", required=True, help="kami-harden.toml 或 .json")
44
+ h.add_argument("--no-build", action="store_true", help="只产出 .kam/manifest/命令,不真打包")
45
+
46
+ args = ap.parse_args()
47
+
48
+ if args.cmd == "pack":
49
+ e = pack_module(args.src, args.module, args.resource, args.url,
50
+ args.token, args.apikey, args.feature, 0, args.out,
51
+ obfuscate=args.obfuscate, keep=_keeplist(args.keep))
52
+ mpath = os.path.join(args.out, "manifest.json")
53
+ manifest = {"modules": {}}
54
+ if os.path.exists(mpath):
55
+ with open(mpath, encoding="utf-8") as f:
56
+ manifest = json.load(f)
57
+ manifest.setdefault("modules", {})[e["module"]] = {"resource": e["resource"], "blob": e["blob"]}
58
+ with open(mpath, "w", encoding="utf-8") as f:
59
+ json.dump(manifest, f, ensure_ascii=False, indent=2)
60
+ print("packed:", e)
61
+ elif args.cmd == "obfuscate":
62
+ obfuscate_file(args.src, args.out, keep=_keeplist(args.keep),
63
+ rename=not args.no_rename, encrypt_strings=not args.no_encrypt_strings)
64
+ print("obfuscated:", args.src, "->", args.out)
65
+ elif args.cmd == "harden":
66
+ harden(load_config(args.config), run=not args.no_build)
67
+ else:
68
+ ap.print_help()
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
@@ -0,0 +1,235 @@
1
+ """kami harden 一键编排:读配置 → (Cython) → 混淆 → kami-armor 加密+注册密钥 →
2
+ 生成运行时引导 → 调 PyInstaller/Nuitka 打包 → (可选)登记构建哈希给 attest。
3
+
4
+ 把"配置一下 → 一条命令 → 出 exe"的体验做回来,但底层是在线授权(密钥不在 exe 里)。
5
+
6
+ 配置(kami-harden.toml 或 .json):
7
+ [project] entry="app/main.py" name="myapp" product="myapp" packager="pyinstaller"|"nuitka" onefile=true
8
+ [server] url="http://host:8787" (token/apikey 可用环境变量 KAMI_ADMIN_TOKEN/KAMI_ADMIN_APIKEY)
9
+ [obfuscate] enabled=true keep=["main"]
10
+ [[modules]] src="app/core/algo.py" module="app.core.algo" resource="algo_v1" feature="premium" keep=["compute"]
11
+ [[cython]] src="app/core/secret.py"
12
+ [attest] register=true build_id="myapp-1.0"
13
+ """
14
+ import glob
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ import urllib.request
23
+
24
+ from .pack import pack_module
25
+ from .obfuscate import obfuscate_source
26
+
27
+
28
+ def load_config(path):
29
+ if path.endswith(".json"):
30
+ with open(path, "r", encoding="utf-8") as f:
31
+ return json.load(f)
32
+ try:
33
+ import tomllib as toml
34
+ except ImportError:
35
+ import tomli as toml
36
+ with open(path, "rb") as f:
37
+ return toml.load(f)
38
+
39
+
40
+ def _auth(srv):
41
+ return (srv.get("token") or os.environ.get("KAMI_ADMIN_TOKEN", ""),
42
+ srv.get("apikey") or os.environ.get("KAMI_ADMIN_APIKEY", ""))
43
+
44
+
45
+ def _get_pubkey(url, token, apikey):
46
+ req = urllib.request.Request(url.rstrip("/") + "/admin/api/pubkey")
47
+ if token:
48
+ req.add_header("Authorization", "Bearer " + token)
49
+ if apikey:
50
+ req.add_header("X-API-Key", apikey)
51
+ with urllib.request.urlopen(req, timeout=15) as r:
52
+ return json.loads(r.read().decode())["hex"]
53
+
54
+
55
+ def _register_measure(url, token, apikey, build_id, exe):
56
+ h = hashlib.sha256(open(exe, "rb").read()).hexdigest()
57
+ body = json.dumps({"build_id": build_id, "expected_hash": h, "note": os.path.basename(exe)}).encode()
58
+ req = urllib.request.Request(url.rstrip("/") + "/admin/api/measurements", data=body, method="POST")
59
+ req.add_header("Content-Type", "application/json")
60
+ if token:
61
+ req.add_header("Authorization", "Bearer " + token)
62
+ if apikey:
63
+ req.add_header("X-API-Key", apikey)
64
+ try:
65
+ urllib.request.urlopen(req, timeout=15)
66
+ print("已登记构建哈希 build_id=%s sha256=%s" % (build_id, h[:16] + "..."))
67
+ except Exception as e:
68
+ print("登记构建哈希失败:", e)
69
+
70
+
71
+ def _cythonize(specs, obfuscate=False, default_keep=()):
72
+ """把皇冠模块(可选先混淆)编译成原生 .pyd/.so,放到源文件旁边;源 .py 不改动。
73
+ Cython 会泄露 Python 名字/字符串,故强烈建议 obfuscate=True。"""
74
+ try:
75
+ import Cython # noqa
76
+ except ImportError:
77
+ print("[warn] 未装 Cython 或缺 C 编译器,跳过 Cython:", [s["src"] for s in specs])
78
+ return
79
+ for spec in specs:
80
+ src = os.path.abspath(spec["src"])
81
+ name = os.path.splitext(os.path.basename(src))[0]
82
+ with open(src, "r", encoding="utf-8") as f:
83
+ code = f.read()
84
+ if obfuscate:
85
+ code = obfuscate_source(code, keep=tuple(spec.get("keep", default_keep)))
86
+ tmp = tempfile.mkdtemp(prefix="kamicy_")
87
+ try:
88
+ with open(os.path.join(tmp, name + ".py"), "w", encoding="utf-8") as f:
89
+ f.write(code)
90
+ with open(os.path.join(tmp, "setup.py"), "w", encoding="utf-8") as f:
91
+ f.write("from setuptools import setup\nfrom Cython.Build import cythonize\n"
92
+ "setup(ext_modules=cythonize(['%s.py'], compiler_directives={'language_level':'3'}))\n" % name)
93
+ rc = subprocess.call([sys.executable, "setup.py", "build_ext", "--inplace"], cwd=tmp)
94
+ built = glob.glob(os.path.join(tmp, name + "*.pyd")) + glob.glob(os.path.join(tmp, name + "*.so"))
95
+ if rc == 0 and built:
96
+ shutil.copy(built[0], os.path.join(os.path.dirname(src), os.path.basename(built[0])))
97
+ print("Cython 原生编译:", spec["src"], "->", os.path.basename(built[0]))
98
+ else:
99
+ print("[warn] Cython 编译失败:", spec["src"])
100
+ finally:
101
+ shutil.rmtree(tmp, ignore_errors=True)
102
+
103
+
104
+ _RTHOOK = '''# 由 kami harden 生成的运行时引导(在主程序之前运行)
105
+ import os, sys
106
+ def _kami_boot():
107
+ base = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
108
+ from kami_client import KamiClient, LicenseError
109
+ import kami_armor
110
+ client = KamiClient({url!r}, {product!r}, {pubkey!r})
111
+ try:
112
+ client.validate()
113
+ except LicenseError:
114
+ code = os.environ.get("KAMI_CODE", "")
115
+ if not code:
116
+ p = os.path.join(os.path.dirname(sys.executable), "license.key")
117
+ if os.path.exists(p):
118
+ code = open(p).read().strip()
119
+ if not code:
120
+ sys.stderr.write("需要授权:设置环境变量 KAMI_CODE 或同目录放 license.key\\n")
121
+ sys.exit(1)
122
+ try:
123
+ client.activate(code)
124
+ except LicenseError as e:
125
+ sys.stderr.write("激活失败: " + str(e) + "\\n")
126
+ sys.exit(1)
127
+ kami_armor.install(client, os.path.join(base, {manifest!r}))
128
+ _kami_boot()
129
+ '''
130
+
131
+
132
+ def _gen_rthook(build_dir, url, product, pubkey, manifest_name):
133
+ path = os.path.join(build_dir, "kami_rthook.py")
134
+ with open(path, "w", encoding="utf-8") as f:
135
+ f.write(_RTHOOK.format(url=url, product=product, pubkey=pubkey, manifest=manifest_name))
136
+ return path
137
+
138
+
139
+ def harden(cfg, run=True, sdk_path=None):
140
+ proj, srv = cfg["project"], cfg["server"]
141
+ url = srv["url"]
142
+ token, apikey = _auth(srv)
143
+ product = proj["product"]
144
+ build_dir = cfg.get("build_dir", "build_kami")
145
+ os.makedirs(build_dir, exist_ok=True)
146
+ sdk_path = sdk_path or os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # .../sdk/python
147
+
148
+ obf = cfg.get("obfuscate", {})
149
+ obf_on, obf_keep = obf.get("enabled", False), tuple(obf.get("keep", []))
150
+
151
+ if cfg.get("cython"):
152
+ _cythonize(cfg["cython"], obfuscate=obf_on, default_keep=obf_keep)
153
+
154
+ modules, excludes = {}, []
155
+ for m in cfg.get("modules", []):
156
+ e = pack_module(m["src"], m["module"], m["resource"], url, token, apikey,
157
+ m.get("feature", ""), 0, build_dir,
158
+ obfuscate=obf_on, keep=tuple(m.get("keep", obf_keep)))
159
+ modules[e["module"]] = {"resource": e["resource"], "blob": e["blob"]}
160
+ excludes.append(m["module"])
161
+ mpath = os.path.join(build_dir, "manifest.json")
162
+ with open(mpath, "w", encoding="utf-8") as f:
163
+ json.dump({"modules": modules}, f, ensure_ascii=False, indent=2)
164
+ print("已加密 %d 个模块 + 注册密钥 -> %s" % (len(modules), mpath))
165
+
166
+ pubkey = _get_pubkey(url, token, apikey)
167
+ hook = _gen_rthook(build_dir, url, product, pubkey, "manifest.json")
168
+
169
+ packager = proj.get("packager", "nuitka")
170
+ if packager == "pyinstaller":
171
+ cmd, exe = _pyinstaller_cmd(proj, build_dir, modules, excludes, hook, sdk_path)
172
+ else:
173
+ cmd, exe = _nuitka_cmd(proj, build_dir, modules, excludes, hook, sdk_path)
174
+
175
+ print("打包器: %s\n命令:\n %s" % (packager, " ".join(cmd)))
176
+ result = {"manifest": mpath, "hook": hook, "command": cmd, "exe": exe, "build_dir": build_dir}
177
+ if run:
178
+ rc = subprocess.call(cmd)
179
+ if rc == 0 and os.path.exists(exe):
180
+ print("产物:", exe)
181
+ if cfg.get("attest", {}).get("register"):
182
+ _register_measure(url, token, apikey, cfg["attest"].get("build_id", product + "-1"), exe)
183
+ else:
184
+ print("打包失败 rc=%d(或缺打包器/编译器)" % rc)
185
+ result["failed"] = True
186
+ return result
187
+
188
+
189
+ def _datas(build_dir, modules):
190
+ out = [(os.path.join(build_dir, "manifest.json"), ".")]
191
+ for info in modules.values():
192
+ out.append((os.path.join(build_dir, info["blob"]), "."))
193
+ return out
194
+
195
+
196
+ def _pyinstaller_cmd(proj, build_dir, modules, excludes, hook, sdk_path):
197
+ name = proj["name"]
198
+ cmd = ["pyinstaller", "--noconfirm", "--clean", "--noupx", "--name", name,
199
+ "--distpath", os.path.join(build_dir, "dist"),
200
+ "--workpath", os.path.join(build_dir, "work"),
201
+ "--specpath", build_dir,
202
+ "--runtime-hook", hook,
203
+ "--paths", sdk_path,
204
+ "--hidden-import", "kami_client",
205
+ "--collect-submodules", "kami_armor"]
206
+ if proj.get("onefile", True):
207
+ cmd.append("--onefile")
208
+ if not proj.get("console", True):
209
+ cmd.append("--windowed")
210
+ for src, dst in _datas(build_dir, modules):
211
+ cmd += ["--add-data", "%s%s%s" % (os.path.abspath(src), os.pathsep, dst)]
212
+ for ex in excludes:
213
+ cmd += ["--exclude-module", ex]
214
+ cmd.append(os.path.abspath(proj["entry"]))
215
+ exe = os.path.join(build_dir, "dist", name + (".exe" if os.name == "nt" else ""))
216
+ return cmd, exe
217
+
218
+
219
+ def _nuitka_cmd(proj, build_dir, modules, excludes, hook, sdk_path):
220
+ name = proj["name"]
221
+ cmd = [sys.executable, "-m", "nuitka", "--assume-yes-for-downloads",
222
+ "--output-dir=" + build_dir, "--output-filename=" + name,
223
+ "--include-module=kami_client", "--include-package=kami_armor"]
224
+ if proj.get("onefile", True):
225
+ cmd.append("--onefile")
226
+ if not proj.get("console", True):
227
+ cmd.append("--windows-console-mode=disable")
228
+ for ex in excludes:
229
+ cmd.append("--nofollow-import-to=" + ex)
230
+ for src, _ in _datas(build_dir, modules):
231
+ cmd.append("--include-data-files=%s=%s" % (os.path.abspath(src), os.path.basename(src)))
232
+ cmd.append("--include-data-dir=%s=." % sdk_path)
233
+ cmd.append(os.path.abspath(proj["entry"]))
234
+ exe = os.path.join(build_dir, name + (".exe" if os.name == "nt" else ".bin"))
235
+ return cmd, exe
@@ -0,0 +1,70 @@
1
+ """kami-armor 运行时:服务端绑定密钥的加密导入加载器。
2
+
3
+ 受保护模块以密文(.kam)随程序分发,**二进制里没有密钥**。导入时由自定义
4
+ importlib Loader 经 kami 服务器(/v1/unlock,需有效授权+设备绑定)取得密钥,
5
+ 在内存解密 → exec。授权无效/吊销/被踢 → unlock 失败 → 导入失败。
6
+
7
+ 这正是相对 PyArmor 的结构性优势:PyArmor 的 AES 密钥是静态内嵌、可离线算出
8
+ (已被公开脚本静态脱壳);这里密钥根本不在文件里,离线无法解密、可吊销、可溯源。
9
+ 诚实边界:模块解密后代码对象仍在 CPython 内存中,持有效授权的动态攻击者仍可
10
+ dump——这条 CPython 天花板谁都过不去;最值钱的逻辑请用价值闸门留服务端。
11
+ """
12
+ import importlib.abc
13
+ import importlib.util
14
+ import json
15
+ import marshal
16
+ import os
17
+ import sys
18
+
19
+
20
+ class _ProtectedLoader(importlib.abc.Loader):
21
+ def __init__(self, fullname, blob_path, resource, client):
22
+ self.fullname = fullname
23
+ self.blob_path = blob_path
24
+ self.resource = resource
25
+ self.client = client
26
+
27
+ def create_module(self, spec):
28
+ return None # 默认模块对象
29
+
30
+ def exec_module(self, module):
31
+ with open(self.blob_path, "rb") as f:
32
+ blob = f.read()
33
+ key = self.client.unlock(self.resource) # 服务端按授权下发密钥
34
+ data = None
35
+ try:
36
+ data = self.client.decrypt_resource(blob, key) # AES-256-GCM,仅内存
37
+ code = marshal.loads(data)
38
+ module.__dict__["__file__"] = self.blob_path
39
+ exec(code, module.__dict__)
40
+ finally:
41
+ # 尽力丢弃引用(Python 无法真正抹零,但缩短驻留)
42
+ del key, data
43
+
44
+
45
+ class KamiArmorFinder(importlib.abc.MetaPathFinder):
46
+ """拦截受保护模块的导入,交给 _ProtectedLoader。"""
47
+
48
+ def __init__(self, client, modules, base_dir):
49
+ self.client = client
50
+ self.modules = modules # {fullname: {"resource":..., "blob":...}}
51
+ self.base_dir = base_dir
52
+
53
+ def find_spec(self, fullname, path=None, target=None):
54
+ info = self.modules.get(fullname)
55
+ if not info:
56
+ return None
57
+ blob_path = os.path.join(self.base_dir, info["blob"])
58
+ loader = _ProtectedLoader(fullname, blob_path, info["resource"], self.client)
59
+ return importlib.util.spec_from_loader(fullname, loader)
60
+
61
+
62
+ def install(client, manifest_path):
63
+ """安装加密导入。client 需实现 unlock(resource)->key 和
64
+ decrypt_resource(blob,key)->bytes(kami 的 KamiClient 已满足)。"""
65
+ with open(manifest_path, "r", encoding="utf-8") as f:
66
+ manifest = json.load(f)
67
+ base = os.path.dirname(os.path.abspath(manifest_path))
68
+ finder = KamiArmorFinder(client, manifest.get("modules", {}), base)
69
+ sys.meta_path.insert(0, finder)
70
+ return finder