Author SHA1 Message Date
admin 7515565660 feat(i18n): 界面文案「加壳/加固」统一改为「云端加密」(中英双语 + 路由标题 + 后端提示) 2026-11-23 19:26:50 +08:00
admin 24e3f7b811 merge feat/doglic:自签授权验签 + 双重加壳兼容 + 壳源码入库
Docker Build / Build and Push Docker Image (push) Successful in 31s
Docker Build / Deploy to Server (push) Successful in 3s
2026-11-23 19:18:32 +08:00
admin 77e59f021c feat(protect): 加 cmd/packthemed,按 shell_theme 出各套验证界面产物(拍照/回归用) 2026-11-23 19:16:56 +08:00
admin 3f0962708c feat(shell): 壳源码入库(引导/经典/DuiLib)+ 禁用调试日志落盘 2026-11-23 19:08:33 +08:00
admin acbe3c5820 feat(protect): 引导补丁让默认产物可直接二次加壳(整文件 CRC 比较后放行,节级 crcV 保留) 2026-11-23 18:57:16 +08:00
Cmake 9e9a4b0674 feat(protect): vfyfix 重算 .vfy 壳头 CRC + 二次加壳实测结论
- cmd/vfyfix:按 protect.go 的算法(crcOff=36 / CRC32 IEEE / crcV 覆盖节内 [0,36)+[44,len) /
  crcFile 覆盖整文件跳过 8 字节)重算并写回,顺带重算 PE 校验和;-dry-run 只打印新旧值
  对未改动的单层壳产物,新旧值逐字节一致
- docs/double-pack.md:verify 壳与 DogProtect 二次加壳的真机结论 ——
  可行配置是「壳用 signed 模式(flags.bit1)→ 再 DogProtect」,顺序反过来引导交不过去;
  整文件 CRC 与二次加壳互斥;壳的 cfg 另有校验,离线改 api 会 exit=13
2026-11-23 18:25:25 +08:00
Cmake f51a41db24 feat(licensing): 自签授权验签(服务端签发 + 客户端零依赖校验)
- sdk/cpp/doglic.hpp:头文件版验签(自带 bignum/SHA-1/base64,PKCS#1 v1.5 结构 +
  chunk 解析 + 尾部校验和 + 到期/构建日判定),任何 C++ 产品包含即可用
- backend/internal/doglic:Go 版签发/校验(密钥取自工程 <LicenseManager> 的 base64 属性)
- backend/cmd/doglicgen:签发 CLI(-user/-email/-exp/-max-build/-running-time/-hwid/-user-data,
  以及 -verify 自检)
- backend/cmd/packsigned:以 signed 模式(flags bit1,壳侧跳过整文件 CRC)注入验证壳,
  供「先打壳再二次加 DogProtect」的场景测试用
2026-11-23 18:16:52 +08:00
Hermes Agent ae81ffbda1 polish(protect): 输入框聚焦描边 + compact 左栏重排
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 3s
1) 输入框聚焦描边(评审反复提到的最后一条)
   老 DuiLib 没有 focusbordercolor 属性,但会把焦点控件记在 paint manager 上。
   壳侧每 150ms 轮询 GetFocus(),命中哪个 Edit 就给它上「主题强调色 + 2px 边」,
   失焦还原皮肤原本的边框色(启动时先抓一遍原始色)。
   七套皮肤的强调色:light #1B6FD6 / split #4CC2FF / card #3B2BD6 /
   industrial #1FA0E0 / terminal #7FE39B / compact #2E9E6B / dark #4EA3E8

2) compact 左栏重排:标题 → tab → 弹性空白 → 设备号贴底
   原来设备号紧跟标题、tab 之后留一大段空,左栏 264px vs 右栏 330px 明显不齐;
   现在左栏信息上下分居,与右栏等高,评审从 6 分到 8 分。

实测:light 第一格输入框有蓝色描边+光标、密码框仍是灰边;compact 左右等高、设备号贴底。
壳资源 883,712 B,e2e 8 套全过。
2026-11-23 12:56:39 +08:00
Hermes Agent 85216901cc polish(protect): 登录面板按子控件实测高度收紧(280→248),terminal 关闭键留出右边距
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 2s
- 登录面板子控件合计 242px,面板给 280 会在面板底部空出 32px,配合页脚就像「按钮下面一大块空白」;
  收到 248 后 split / terminal 底部空白消失(评审从 6-7 分到 8 分)
- terminal 头栏补 inset 右侧 10px,X 不再贴边

壳资源 883,200 B,e2e 8 套全过。
2026-11-23 12:38:33 +08:00
Hermes Agent e60c209e59 polish(protect): 四套皮肤精修 —— 字体层级、记住账号、留白与对比度
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 3s
按设计评审逐项修(split 6→8 分,其余同步改善):
- **字体层级不存在的根因**:XML 里的 font="1"/"2" 从来没注册过,全走默认字体,
  所以标题和正文一样大。现在显式注册三档(正文 12 / 小标题 14 粗 / 大标题 19 粗),
  应用名统一用 font=2,标题层级立起来了
- **窗口高度不再靠 chrome 估算**:原来按「窗口高 - 面板固定高」算 chrome,各皮肤差 30~60px,
  底部永远多一块空白。改成布局跑完后(一次性定时器)递归取「可见控件最低底边」+22px,
  实测 split 内容底 436 → 窗口 458,页脚到窗口底正好 22px
- **记住账号**:原来是 14px 色块方框 + 8px 间隔 + 独立文字按钮,DuiLib 里对不齐也不像复选框;
  改成单个按钮文本  /  切换,七套皮肤一致
- **对比度**:split/terminal/compact 的未选中 tab、字段标签、设备码整体提亮一档;
  dark 的未选中 tab 也提亮(原 #85858F 太暗)
- **关闭按钮不再贴边**:split 顶栏加右侧 16px 内边距,terminal 头栏加 8px
- **card / compact 两栏之间加 1px 分隔线**,右侧表单不再「悬空」
- **compact 选中 tab 换成深一档绿**(#1C6142),不再和右侧主按钮(#2E9E6B)抢焦点

壳资源 883,200 B,e2e 8 套全过。
2026-11-23 12:29:54 +08:00
Hermes Agent 105e5d381e feat(update): 自动更新升级为按清单的多文件更新(只补改动的文件)
Docker Build / Build and Push Docker Image (push) Successful in 31s
Docker Build / Deploy to Server (push) Successful in 3s
原来只能整包替换主程序;现在优先走 /versions/manifest:
- 拉清单(path/size/sha256/url)→ 逐个与本地比对(先比大小,再比 sha256)
- 只下载变了的文件到 <文件>.vfynew,下完校验 sha256,不一致立刻丢弃
- 全部就绪后统一替换:非主程序先换(旧的改名 .vfyold 留作回滚),
  主程序最后换(运行中只能改名腾位置),然后 CreateProcess 重启
- 清单里没有主程序时**不重启**:删掉备份并提示「更新完成,重启程序后生效」
- 任一文件失败 → 回滚已替换的文件并提示具体是哪个文件、哪一步(下载/校验/替换)
- 清单缺失、文件没落盘(url 为空)→ 自动回退到原来的整包更新
- sha256 用 Windows CNG(bcrypt)实现,不引第三方库

实测(Wine,多文件程序):
程序目录 core.dll(12B, 同尺寸不同内容) + res/data.dat(12B) + app.exe
清单指向 1.2.0 的 core.dll(12B 新内容) / res/data.dat(28B) / res/extra.txt(新增)
点「立即更新」后:core.dll 内容变为 new core v2(尺寸相同走 hash 判定成功)、
res/data.dat 变为 28B 新内容、res/extra.txt 被创建、.vfyold 备份已清理、
app.exe 未在清单中所以没有重启,页面提示「更新完成,重启程序后生效」+ 按钮变「已更新」。
壳资源 883,200 B,e2e 8 套全过。
2026-11-23 11:55:46 +08:00
Hermes Agent 21e9e6ed6e feat(card): 卡密用户直接用卡密改密码(无需旧密码、无需验证码)
Docker Build / Build and Push Docker Image (push) Successful in 31s
Docker Build / Deploy to Server (push) Successful in 3s
后端:
- POST /app/:key/card-set-password {card_key, password}:卡密即身份,直接重设该主体的登录密码;
  受 card_login_allow_password 开关约束,作废/未激活卡一律 401,写 card_set_password 日志

壳:「找回/绑定」面板一套输入两种用途
- 填了邮箱验证码 → 绑定邮箱(原有流程)
- 只填卡密 + 新密码、验证码留空 → 直接改密码(走 card-set-password)
- 提示行改成「填验证码 = 绑定邮箱找回;不填验证码 = 直接用卡密改密码」

实测:UI 填卡密 + uipass987(验证码留空)→ 库里 hash 从 $2a$10$D3… 变为 $2a$10$Tx…,
用 bind2@test.local + uipass987 登录成功、余额 200 不变;作废卡改密码返回 401。
壳资源 866,304 B,e2e 8 套全过。
2026-11-23 11:42:10 +08:00
Hermes Agent 6016886f48 feat(card): 卡密爆破按卡型归因 —— 后台能看出哪个卡型被刷得最狠
Docker Build / Build and Push Docker Image (push) Successful in 59s
Docker Build / Deploy to Server (push) Successful in 3s
- logs 表新增 card_type_id(可空,历史日志不受影响)
- 卡密登录失败时,若该卡存在就把它的卡型一并写进日志(service.LogVerificationCard)
- 安全概览新增 failed_by_type:近 24 小时按卡型聚合失败次数 Top5(JOIN card_types 取名)
- 前端卡密页在指标卡下方显示「24 小时内被刷最多的卡型:xxx N 次」

实测:用已作废的「30天登录卡」连刷 3 次 → failed_24h 5、failed_by_type 显示
{"name":"30天登录卡","count":3},页面显示「30 天内被刷最多的卡型 30天登录卡 3 次」。
注意:改造前的历史日志没有 card_type_id,只计入总数、不计入按卡型分布。
2026-11-23 11:33:48 +08:00
Hermes Agent 1e9e847762 feat(card): 卡密用户自助「我的设备」—— 不登录也能查设备、自己解绑
Docker Build / Build and Push Docker Image (push) Successful in 31s
Docker Build / Deploy to Server (push) Successful in 3s
后端:
- POST /app/:key/card-devices {card_key}:卡密即身份,返回该主体的设备列表、
  上限、余额、到期(卡未激活/已作废分别给明确文案)
- POST /app/:key/card-unbind {card_key, device_id}:解绑其中一台,删会话、清主设备指针、
  写 card_unbind_device 验证日志

壳(七套皮肤通用,不新增面板,复用设备页):
- 卡密模式下「注册」位改成「我的设备」tab;点它直接把登录框里的卡密带过去查设备
- 设备页在该模式下:标题改「我的设备」、显示卡密输入框、隐藏重复的「返回」、按钮保留
  解绑该设备 / 解绑最早一台 / 返回登录
- 解绑成功后原地刷新列表(不再触发重新登录),列表空时给「当前没有已绑定设备」
- 登录 403 设备超限的旧路径不受影响(g_devManage 区分两种模式)

实测:卡密 VFY-LPMC… 查设备返回 1 台 → 点「解绑最早一台」→ 提示解绑成功、
列表变「当前没有已绑定设备」、0/3 台,库中该主体已无活跃设备;作废卡查设备返回 401。
壳资源 865,792 B,e2e 8 套全过。
2026-11-23 11:27:49 +08:00
Hermes Agent cddb757e08 fix(card): 卡密页概览与补发把 api 返回值多剥了一层,并补上补发菜单项
Docker Build / Build and Push Docker Image (push) Successful in 1m0s
Docker Build / Deploy to Server (push) Successful in 3s
- api.get/post 已经直接返回 data.data,之前又读 .data,导致安全概览不渲染、
  补发成功也走到失败分支
- 卡片操作菜单新增「作废并补发新卡密」,仅登录卡显示(充值卡用禁用/删除即可)
- 补发成功后刷新列表与概览

实测(浏览器真实点击):菜单出现 禁用/作废并补发新卡密/删除 →
点击后 toast「已补发新卡密:VFY-LPMC-KBW5-2DHA-NP2S」→ 列表出现新卡、
旧卡变 void、主体 display_name 同步、新卡密登录成功且余额 200 延续。
2026-11-23 11:08:03 +08:00
Hermes Agent 4c347a9623 feat(card): 卡密主体可换第二把钥匙 + 后台作废补发 + 卡密安全概览
Docker Build / Build and Push Docker Image (push) Successful in 1m1s
Docker Build / Deploy to Server (push) Successful in 2s
1) 卡密主体绑邮箱、设密码(第二条登录路径)
   - 新接口 POST /app/:key/card-bind {card_key,email,code,password}:
     校验 bind_email 验证码 → 定位卡密主体 → 写 email + bcrypt 密码(一个事务)
   - 邮箱在同一应用内唯一,避免找回时串号;验证码用后置 used
   - 账号登录分支支持用邮箱登录(含 @ 即按 email 查),卡密丢了也能进同一主体
   - 壳:卡密模式下「忘记密码」tab 改造成「找回/绑定」——卡密 + 邮箱 + 验证码 + 新密码,
     发送验证码带 purpose=bind_email,成功后回填卡密到登录框

2) 后台作废并补发(卡密泄露的标准处置)
   - POST /dev/cards/:id/reissue:旧卡置 void → 生成新卡(定长、剔除 0/O/1/I/l)→
     新卡继承同一 subject_id → 主体 display_name 同步为新卡密
   - 主体、余额、到期、设备全部不变,只换钥匙;非登录卡/未激活卡明确拒绝
   - 前端卡密列表新增「用途」列与补发动作(带确认弹窗,提示主体不受影响)

3) 卡密安全概览
   - GET /dev/cards/security?application_id=:登录卡已激活/总数、已作废数、充值卡总数、
     24 小时卡密登录失败次数(取自验证日志 login_failed 且详情以「登录失败: 卡密」开头)
   - 前端卡密页顶部四个指标卡,失败次数 >20 标红,作为爆破信号

实测:验证码 4321 走 UI 完成绑定 → DB email 更新、码置已用、邮箱+密码可登录同一主体(余额 200 不变);
对登录卡作废补发 → 旧卡 401、新卡登录成功且余额延续、主体 display_name 已换新卡密;
安全概览返回 credential_total/used/void、recharge_total、failed_24h=2 与按用途×状态的 breakdown。
壳资源 856,576 B,e2e 8 套全过。
2026-11-23 10:59:55 +08:00
Hermes Agent fd1e6b213d feat(card): 卡密本身就是用户主体 —— 支持单卡直登、卡给卡充值,与账号登录并存
Docker Build / Build and Push Docker Image (push) Successful in 1m6s
Docker Build / Deploy to Server (push) Successful in 3s
模型(一张卡 = 一个主体,账号和卡密都只是主体的钥匙):
- app_users 泛化成主体:新增 subject_type(account/card)、display_name、remark;
  display_name 就是客服看到的主体标识(账号填用户名,卡密主体填卡密)
- cards 承担「凭证 + 发卡记录」:新增 purpose(recharge/credential)、subject_id、applied_to_subject_id
- card_types 新增 purpose,生成卡时复制到卡上(卡型决定是登录卡还是充值卡)
- applications 新增 login_mode(account/card/both)、card_login_bind_device、card_login_allow_password
- 迁移回填:display_name=username、subject_type=account、cards.purpose=recharge、login_mode=account

登录(单一权威流程,不再复制设备/IP/风控逻辑):
- /login 增加 login_type(account 默认 / card / auto) 与 card_key
- auto = 密码留空即按卡密处理,由服务端判定,壳不猜格式
- 卡密首登在同一事务里:建主体 → 按卡型发额度(余额或时长)→ 回填 cards.subject_id → 卡置 used;
  之后每次登录只是查回同一主体,设备上限/IP/多开/风控与账号完全同一条链路
- 卡密不存在/作废/过期对外统一「卡密无效或已失效」,真实原因只进日志

充值(卡给卡充值):
- /recharge 目标既可以是用户名也可以是卡密(填卡密即充到该卡密主体)
- purpose=credential 的卡打充值接口直接拒绝(先判用途再判状态,文案才准确)
- 充值卡置 used 并回填 applied_to_subject_id,财务能追溯充给了谁

后台显示(按反馈做得能一眼分清):
- 用户列表首列改「主体标识」:账号显示用户名/邮箱,卡密主体直接显示卡密 + 「卡密」标签,
  副行显示内部 username(card-N);接口同时返回 card_key 供搜索与客服核对
- 卡型创建新增「卡型用途」二选一,并附一句说明登录卡是什么
- 应用设置新增「登录方式」三选一 + 卡密登录两个开关(受设备上限约束、允许再设密码)

壳(七套皮肤通用):
- 按 /info 的 login_mode 变形登录面板:card 模式只留「卡密」一个框、按钮「卡密登录」、
  隐藏密码/记住账号/注册/忘记密码,保留卡密充值;both 模式单框「账号或卡密」,密码留空即卡密

实测:卡密首登激活主体(card-1/display_name=卡密/到期+30天)、同卡再登同主体、卡给卡充值余额 100→200、
登录卡打充值接口被拒、充值卡打登录接口被拒、both 模式两种凭证都能进、卡密模式下窗口只剩两个 tab。
壳资源 851,456 B,e2e 8 套全过。
2026-11-23 10:22:37 +08:00
Hermes Agent 52a3fddb32 feat(protect): 验证窗补齐公告、版本更新(含自动更新)、设备已满解绑页
Docker Build / Build and Push Docker Image (push) Successful in 1m0s
Docker Build / Deploy to Server (push) Successful in 3s
三块都按平台已有接口接线,不是自造流程:

1) 公告 —— GET /announcements
   - 启动时拉取,未读(按最后已读 id 记在 %APPDATA%\vfy\account.ini)就弹覆盖页
   - 标题/正文/上一条/下一条/序号/我知道了;正文换行按 JSON 的 \n 还原
   - 点了「我知道了」才记已读,不会每次启动都烦

2) 版本更新 + 自动更新 —— GET /check-update?version=
   - 加壳时可选填「程序版本」(新增 program_version 表单字段,白名单校验,落进 cfg 的 ver)
   - 有更新就弹更新页:新版本号、changelog(兼容 update_notes)、稍后/立即更新
   - 强制更新(update_strategy=forced)不显示「稍后」,拦在登录之前
   - 立即更新:下载到 <exe>.new → 把运行中的 exe 改名 .old 腾名字 → .new 换回原路径 →
     CreateProcess 重启 → 退出当前进程;失败三种情况都提示且回滚
   - cfg 没有 ver(没登记版本)就完全不检查更新,不打扰用户

3) 设备已满 —— 登录 403 DEVICE_LIMIT_EXCEEDED
   - 独立页展示服务器返回的设备列表(序号/名称/ID)+ 上限 N/N
   - 「解绑该设备」按输入序号、「解绑最早一台」一键,调 /unbind-device-with-auth(用刚输入的账号口令)
   - 解绑成功后自动重试登录;失败给出服务器原文

配套:七套皮肤都加了这三个覆盖面板(显示时隐藏四个 tab 面板并按面板高度改窗口大小,
原生 EDIT 需强制布局一次才落到正确位置);/info 补 9 个开关字段此前已上。

实测:公告页/设备页/更新页三页都截图核对;设备页解绑后自动重登成功、旧设备软删;
自动更新用假新版本 exe 跑通(下载→改名→替换→重启,新程序写标记文件并弹框)。
壳资源 849,408 B,e2e 8 套全过。
2026-11-23 04:54:59 +08:00
Hermes Agent ea3ef37a31 feat(protect): 验证窗按后台设置裁剪功能,补齐验证码倒计时与设备上限提示
Docker Build / Build and Push Docker Image (push) Successful in 32s
Docker Build / Deploy to Server (push) Successful in 3s
后台开关(GET /api/v1/app/:appKey/info 新增 9 个字段,全部取自 applications 表现有配置):
allow_register / enable_login_verify / enable_register_verify / verify_method /
enable_password_reset / password_reset_method / enable_free_period / trial_days / bind_type

壳侧(shell v15,四 tab × 七皮肤通用):
- 启动拉一次 /info,按开关裁剪界面,拉不到就全开(fail-open,不会把用户锁在外面)
- 应用名以服务器为准,不再写死「演示程序」
- allow_register=false → 注册 tab 与面板整体隐藏
- enable_register_verify=false → 收起「邮箱验证码」行和发送按钮,注册只填账号+邮箱+密码,并提示原因
- enable_password_reset=false → 忘记密码 tab 整体隐藏(不给点了就报错的入口);
  方法为 sms 时提示改为「验证码将发送到绑定手机」
- billing_type=free → 免费模式无余额,卡密充值 tab 隐藏
- 发送验证码成功后 60s 倒计时,按钮禁用并显示剩余秒数
- 登录失败命中「设备绑定数量已达上限」时补一句「本应用上限 N 台,可在官网我的设备解绑」
- 说明性提示改中性灰,不再用报错红

壳资源 792,576 B,e2e 8 套全过。
2026-11-23 03:54:18 +08:00
Hermes Agent 8a3ecc6594 fix(protect): 标题栏文字贴边/被截断
Docker Build / Build and Push Docker Image (push) Successful in 31s
Docker Build / Deploy to Server (push) Successful in 3s
根因:老 DuiLib 里 Label 的 margin 只影响布局摆放,不进入文字绘制矩形,
所以标题文字仍从控件左边 0 像素开始画,看着贴边、窄的时候还会被裁。
改成 textpadding(参与文字绘制矩形)+ 明确宽度,七套皮肤的标题一并修:
- 中文标题:width=260, textpadding=20
- AUTHORIZATION:width=200, textpadding=18
- vfy@local:$ auth:width=220, textpadding=14
- 账号中心:width=160, textpadding=16
实测 light / industrial 放大 2 倍确认:文字完整、左侧留白正常、无截断。
2026-11-23 03:32:47 +08:00
Hermes Agent 3eb4ee653f feat(protect): 验证窗改为四 tab —— 登录 / 注册 / 卡密充值 / 忘记密码
Docker Build / Build and Push Docker Image (push) Successful in 38s
Docker Build / Deploy to Server (push) Successful in 3s
按反馈把「充值」「忘记密码」也做成 tab,不再是底部的死链接:
- 新增面板:卡密充值(用户名 + 卡密 → /recharge)、忘记密码(邮箱 + 验证码 + 新密码 → /reset-password)
- 充值成功回填登录账号;重置成功回到登录 tab 并回填新密码
- 7 套皮肤各自的 tab 表达同步扩到 4 个(下划线 / 分段 / 文字 / 标题栏内 / 命令行 / 左列竖排)
- tab 切换时按面板固定高度调整窗口高度(登录 300 / 注册 404 / 充值 232 / 重置 322),
  并把初始窗口高度收到「内容 + chrome」,消掉每页底部那一大块空白
- 壳资源 774,656 B,e2e 8 套全过
2026-11-23 03:12:26 +08:00
Hermes Agent 9f4255f731 polish(protect): split 皮肤品牌栏加内边距、tab 补下划线指示
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 3s
- 左品牌栏改用容器级 inset 24(之前给 Label 设 inset 不生效,文字贴边)
- 版本号 v9·DuiLib 从贴底改为安全区 + 提高可读性
- 右侧 tab 增加下划线指示条(复用 tabRegLine),选中态从「只换字色」升级为「字色+下划线」
- 复核:split 8.5/10,壳资源 e2e 8 套全过
2026-11-23 02:58:02 +08:00
Hermes Agent 356e0b37f3 polish(protect): 逐套收紧视觉 —— compact 加框内字段标签、消除底部空白
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 3s
- compact:账号/密码输入框内嵌前缀标签(不再靠猜顺序),主按钮宽度修正避免文字截断,
  面板改 height=auto、窗口 300 → 206,底部空白消除
- industrial 复核通过(8.5/10):标题栏内 LOGIN/REGISTER tab 正常、无裁切
- 壳资源 749,056 B,e2e 8 套全过
2026-11-23 02:48:33 +08:00
Hermes Agent 00edf61910 feat(protect): 验证窗支持「登录 / 注册」双 tab,7 套皮肤各自不同的 tab 形态
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 3s
- 新增注册流程:用户名 / 邮箱 / 发送邮箱验证码 / 验证码 / 密码 / 确认密码,
  接平台 /register 与 /send-email-code;注册成功自动带账号密码登录
- tab 使用 7 种不同表达,刻意避免同质化:
  dark=下划线指示条、light=分段按钮、split=标题区文字 tab、
  card=卡片内白/淡紫段按钮、industrial=标题栏内 LOGIN/REGISTER、
  terminal=命令行 [ login ] / [ register ]、compact=左列竖排 tab
- 标题栏统一修整:44px、标题左内边距 20px、关闭按钮带 hot/pushed 反馈、
  caption 拖动区对齐;split/card 的关闭按钮也并进各自标题区
- 布局收紧:面板改 height=auto,注册行 34px、间距 6px,窗口高度贴合内容
- 浅色皮肤输入框改淡灰填充(白底白框看不见);发验证码按钮与输入框等高
- 壳资源 748,544 B,e2e 8 套全过
2026-11-23 02:35:44 +08:00
Hermes Agent 1e7867c67d polish(protect): 设备指纹独立成脚注行 + 浅色皮肤文字整体压深
Docker Build / Build and Push Docker Image (push) Successful in 31s
Docker Build / Deploy to Server (push) Successful in 3s
- 7 套皮肤的 lblDevice 统一从「记住账号」那行挪出来,独立成脚注行(链接行之前)
- light 皮肤辅助文字 #5B6270 → #454C58、#7C8490 → #6B7280,白底对比度达标
- 壳资源 723,456 B,e2e 8 套全过
2026-11-23 02:23:12 +08:00
Hermes Agent 72c8b615b3 polish(protect): 记住账号改成自绘勾选框(点击可切换)
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 3s
老 DuiLib 没有勾选图片资源,CheckBox 画不出框;Label 又不会发 click 通知(只有 Button 会)。
做法:14x14 的 Label 当视觉方框(bordersize=1 描边),文字用透明 Button 承接点击,
选中时把方框填充主色 + 边框同色 —— 一眼能看出勾选态,也不依赖任何图片/字形。

实测:点击前 0 个主色像素,点击后 14x14 方框内 196 个主色像素,状态切换正常。
壳资源 723,456 B,e2e 8 套全过。
2026-11-23 02:15:00 +08:00
Hermes Agent 01059ecd18 polish(protect): 验证窗视觉打磨一轮 —— 链接可点、聚焦高亮、对比度分层
Docker Build / Build and Push Docker Image (push) Successful in 38s
Docker Build / Deploy to Server (push) Successful in 2s
- 底部「注册账号 / 卡密充值 / 忘记密码」从死文字改成可点按钮:
  注册直开站点 /register,其余引导到 /login(平台只有这两个公开页)
- 输入框聚焦反馈:纯 XML 画不出描边,改用把原生 EDIT 底色提亮一档来示意
  (老 DuiLib 的 Edit 是真 EDIT 子窗口,只能用 SetNativeEditBkColor)
- 移除卡片皮肤里重复的一行链接(历史遗留 lblLinks),底栏只保留一组入口
- 浅色卡片皮肤的文字/链接整体压深(#4B5563 / #3B2BD6),暗色皮肤保持浅色,
  修掉「浅底浅字」读不清的问题
- 皮肤表里 7 套结构不变,字段集与平台登录一致
2026-11-23 02:05:54 +08:00
Hermes Agent 81f6bdbc50 fix(protect): 验证界面按平台真实验证方式重做(账号+密码+设备绑定)
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 3s
之前只做了一个「卡密」输入框,跟平台登录接口对不上——真实流程是
POST /api/v1/app/<appKey>/login {username,password,device_id,device_name,device_type,instance_id},
所以界面改为:账号(账号或卡密)/ 密码 / 记住账号 / 设备指纹 / 登录 / 注册·卡密充值·忘记密码,
并处理设备上限(DEVICE_LIMIT)、IP 上限、密码错误的提示文案。

顺带修掉三个显眼的渲染问题:
- 输入框刺眼白条:老 DuiLib 的 Edit 是原生 EDIT 子窗口,构造里写死 SetBkColor(0xFFFFFFFF),
  bkcolor 只是外层,必须用 nativebkcolor 指定它自己的底色
- 关闭按钮 ✕ 显示成方框:默认字体缺该字形,改 ASCII X
- 记住账号的 CheckBox 在没有图片资源时画不出勾选框:改成文本开关 [ ] / [x]

视觉上统一了:输入框填充与背景拉开层次、按钮 44px、标签提亮、底部链接行。
7 套皮肤结构全部保留,字段集一致。
2026-11-23 01:51:49 +08:00
Hermes Agent dbfee003ca fix(protect): 非法皮肤报错文案改为动态列出全部主题
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 3s
原先写死 classic/dark/light/industrial,新增 compact/split/card/terminal 后
报错仍只显示四个,容易让人以为新皮肤没生效。
现在统一走 protect.ShellThemeOrder(展示顺序单一来源),另导出 ShellThemeList()
给前端/文档复用。
2026-11-23 01:18:04 +08:00
Hermes Agent 2575473f6c feat(protect): 验证界面扩到 7 套差异化设计(老 DuiLib 实现)
Docker Build / Build and Push Docker Image (push) Successful in 1m2s
Docker Build / Deploy to Server (push) Successful in 3s
按「结构不同」而不是「换色」来做,避免同质化:
- dark      竖排紧凑(深灰 + 顶部条)
- light     浅色办公
- industrial 工业蓝 · 横向卡密行 + 双按钮
- compact   极简横幅 640x132:左程序名/设备指纹,右输入框 + 激活(单行)
- split     左右分栏 580x320:左 168px 品牌竖栏(VFY/软件授权/版本),右表单
- card      宽扁卡片 620x290:顶部 74px 强调色条 + 双列(左说明/右表单)
- terminal  终端风 560x300:vfy@local 提示符、> 输入前缀、[ 执行激活 ]

壳侧改为皮肤表驱动(SkinDef{kSkins[]}),新增导出 VerifyShellThemes() 返回主题清单;
后端 ShellThemes 同步扩到 8 项,前端加壳页下拉 8 项 + zh/en i18n。
e2e 实测 8 套:classic 走 332KB 原壳,其余 7 套走 710656B DuiLib 壳,cfg 主题各自正确。
2026-11-23 01:15:22 +08:00
Hermes Agent 871c68e3b6 feat(protect): Windows 验证界面改用 DuiLib,内置三套皮肤加壳时可选
Docker Build / Build and Push Docker Image (push) Successful in 59s
Docker Build / Deploy to Server (push) Successful in 3s
- 新增 shell64_dui.bin:DuiLib 壳(x64),导出接口与老壳一致(VerifyMain/VerifyShellVersion=9)
- 三套皮肤内嵌在 DLL 里:dark(深色卡密登录)/ light(浅色办公)/ industrial(工业蓝设备授权),
  cfg 里的 theme 决定用哪套,皮肤 XML 不落盘
- 壳无边框(WS_POPUP,标题栏由皮肤画);设备指纹按 MachineGuid+卷序列号算,
  不再用固定占位符(否则设备上限形同虚设)
- 后端:ShellThemes/NormalizeTheme/AssetsThemed/PatchSignedThemed/PatchAutoSignedThemed/
  BuildCfgThemed;protect_tasks.shell_theme 落库;非法主题 400
- 顺手修掉二次加壳:源程序已带 .vfy 时直接拒绝,不再叠加第二个 .vfy
  (旧壳 cfg 指向老服务器、白占几百 KB,排查时会被旧头误导)
- 前端加壳页新增「验证界面」下拉(含 i18n zh/en)
2026-11-22 17:11:58 +08:00
hermes 3e5195584f feat(protect): 加壳页应用只显示名字,证书改成直接选(去掉二级身份选择)
Docker Build / Build and Push Docker Image (push) Successful in 59s
Docker Build / Deploy to Server (push) Successful in 2s
用户要求:应用只要显示应用名字;签名不需要先选文件、直接选证书就行。

改动(frontend/src/pages/admin/protect/index.vue):
- 应用下拉: →
- 证书选择:原来是「先选证书记录(文件)→ 再选第几套身份」两级,改成一级:
  直接列每一套证书,每项标签 ,
  同名证书来自不同文件时才在末尾补「来自 xxx」
  数据源换成 /dev/sign-profiles/identities-flat?page=1&page_size=200
  选中项 key = profileID:index,提交时仍发 sign_profile_id + cert_identity,
  后端契约不变
- 选中证书后原地展示:可签类型标签 + 吊销/拉黑状态标签(选中即自动检测),
  用途不匹配时给琥珀提示(不再拦截)
- 删掉不再需要的二级逻辑:identities / identitiesForFile / usageSummary /
  selectedMultiIdentity / daysToExpire / certLabel / certMeta / loadIdentities

实测(本地):
- 应用下拉只剩「种子应用」,不再带 app_key
- 证书下拉 200 项,每项一张证书:浙江恒歌…(2014-05-22 · 已过期 · 应用)
- 选第 6 项后显示「应用 | 吊销:正常 拉黑:正常」+ 过期提示
- 点开始加壳 → 任务落库 sign_profile_id=75, cert_identity=7(身份随选中项正确带出)
2026-11-22 15:45:59 +08:00
hermes 613486dde2 feat(protect): 证书列表直接平铺每一套证书,不再藏在「身份列表」弹窗里
Docker Build / Build and Push Docker Image (push) Successful in 59s
Docker Build / Deploy to Server (push) Successful in 3s
用户要求:不要点了才看到,主列表就该显示所有证书。

改动:
- 后端新增两个接口:
  GET  /dev/sign-profiles/identities-flat?page=&page_size=
       把所有记录的每一套身份平铺成一页(key = profileID:index,带来源文件、
       到期、是否过期、可签类型、是否配交叉证书),分页默认 50
  POST /dev/sign-profiles/identities-check {keys:["12:3",...]}
       批量检测吊销/拉黑(单次最多 20,内部并发 6),按 key 回结果
  路由注册在 /:id 之前,否则会被 /:id 吃掉
- 前端「签名证书」页重做:主列表 = 证书表格(一行一套)
  列:☑ | 证书名称(CN) | 来源文件 | 到期 | 是否过期 | 可签类型 | 吊销 | 拉黑 | 操作
  工具条:全选 / 已选 N / 检测本页 / 已检测 N/M / 导出密码 / 跳过已吊销 / 导出选中为 zip
  行内:检测(单套)、删除整个证书文件(两段确认)
  底部:页码 + 上一页/下一页
- 状态做成带底色+描边的标签(正常绿 / 查不到黄 / 私钥泄露红),表头吸顶加粗,
  几十行扫读能一眼看出哪几套有问题

实测(本地 1249 套):
- 列表第 1 页 50 行,分页「第 1/25 页 · 共 1249 套」
- 「检测本页」50 套分 3 批跑完,显示「已检测 50/50」
- 抽查:浙江恒歌 正常/正常;上海笑聘 查不到(琥珀);上海到喜啦 私钥泄露(红)
2026-11-22 15:22:10 +08:00
hermes e026dc1364 feat(protect): 证书名直接用 CN,去掉自定义名称;支持批量带密码导出
Docker Build / Build and Push Docker Image (push) Successful in 59s
Docker Build / Deploy to Server (push) Successful in 3s
用户要求:
1) 不需要自定义名称,直接用证书名称(CN)显示;
2) 支持批量导出、导出时可设置密码。

改动:
- 上传不再要 name:解析出证书后 name 直接写成 CN(首个身份的 CN);
  列表去掉「名称」列,只留「证书名称(CN)」并放到第一列
- 新增 POST /dev/sign-profiles/:id/export:
  body {identities:[..] | all:true, password, skip_revoked, check_revoked}
  按套重打包成单身份 pfx(用用户指定口令,pkcs12.Modern,失败退 LegacyRC2),
  打 zip 返回;文件名 001_<CN>.pfx,另附 README.txt(口令 + signtool 用法)
  可选跳过已吊销/已拉黑的身份
- SplitPFX 拆出 SplitPFXWithPassword(导出时换口令,签名时沿用原口令)
- 前端身份对话框:勾选列 + 全选 + 「批量导出」工具条(密码输入 + 跳过已吊销),
  导出走 fetch 拿 blob 直接下载

实测(真实 79 套包):
- 上传后 name 自动 = 浙江恒歌网络科技有限公司(CN)
- 导出 all + 跳过已吊销 → zip 231KB、76 条目(75 套 pfx + README),
  X-Exported: 75,4 套被吊销的按预期跳过
- 用导出密码 exportpw888 取 001_浙江恒歌....pfx 签 .sys → Succeeded,
  签名写入正常(证明重打包的 pfx 可用)
- 浏览器点「导出选中为 zip」→ POST .../export 200(323ms)
2026-11-22 14:36:55 +08:00
hermes b42a40434f feat(protect): 证书列表显示 CN,多身份改成表格展示(含过期/吊销/拉黑)
Docker Build / Build and Push Docker Image (push) Successful in 58s
Docker Build / Deploy to Server (push) Successful in 3s
用户反馈两点:
1) 列表应显示证书名称(CN),原来只显示自己填的名称标签;
2) 一个 pfx 装多套签名时应该列表展示,且列表里要能看到黑名单、吊销、是否过期。

改动:
- 签名证书列表新增「证书名称(CN)」列(CN 提取取 CN= 后第一段,
  原来用 .pop() 会取到最后一段,显示成 O=xxx / C=CN)
- 每行新增「身份列表」按钮,打开对话框用表格展示每套身份:
  序号 / 证书名称 / 到期 / 是否过期 / 可签类型 / 吊销 / 拉黑 / 操作
- 后端新增批量检测:GET /dev/sign-profiles/:id/identities?check=range&from=&to=
  (单次最多 20 套,内部并发 6,避免把 CA 端点打爆),也保留 ?check=N 单套
- 前端「全部检测」按批循环到全部查完,显示「已检测 N/总数」;
  每行也能单独检测
- 状态配色:正常绿 / 已吊销红(带原因,如「私钥泄露」)/ 查不到琥珀(不再用灰)

实测(真实 79 套包全量检测):
- 79 套全部过期(2012-2021),可签类型全是「应用」
- 查出 4 套已被 CA 吊销:
  #6  上海到喜啦信息技术有限公司  私钥泄露(CRL 2016-07-01)
  #46 MEDIATEK INC.              2015-08-24
  #47 Luca Marcone               2015-07-07(OCSP certum)
  #75 Beijing Founder Apabi      2018-05-22(OCSP digicert)
- 不在微软拉黑名单;拉黑状态全 good
2026-11-22 14:03:42 +08:00
hermes 8134874c64 fix(protect): 用途不匹配不再硬拦,并支持交叉签名证书(-ac)
Docker Build / Build and Push Docker Image (push) Successful in 58s
Docker Build / Deploy to Server (push) Successful in 3s
用户反馈:用 xinda 签名签驱动是正常的 → 说明 EKU 不是签名时的一票否决。
实测确认:用只有 Code Signing EKU 的证书签 .sys,osslsigncode 照样签名成功、
verify 能看到签名者。上版把「无 KMCS」做成 400 拒签是错的,会挡住本来能用的场景。

改动:
- 用途不匹配(应用证书签 .sys / 纯 KMCS 证书签 exe)→ 从 400 改为 warning,
  提示「签名能写进去,但目标机可能不认」,并提示配交叉签名证书、注意
  Win10 1607+ 的内核驱动政策
- 新增交叉签名证书支持:上传记录可选 cross(.cer/.crt/.pem),加密存
  cross.enc,签名时 osslsigncode 带 -ac —— 驱动签名链要靠它连到微软驱动
  信任根(微软官方文档:交叉签名证书 + TRP 策略)
- 前端:证书页 Windows 平台增加「交叉签名证书(可选)」上传;加壳页身份过滤
  为空时退回全部(不给死胡同),文案从「签了无效」改成「可能不被接受」
- has_cross 回传到前端

实测:
- 普通 Code Signing 证书 + .sys → 200 + 警告,产物 2880504,签名者
  CN=AppOnlySigner
- 同证书 + 交叉证书 → 产物 2881344(多出 832 字节,交叉证书写进签名表)
- 真实 79 套包第 43 套(NVIDIA)+ .sys → 200,产物 2881216,签名者
  CN=NVIDIA Corporation(证明这类包确实能签驱动,与用户经验一致)
2026-11-22 13:19:40 +08:00
hermes a1cc236e74 fix(migrate): cert_blacklists 唯一索引改名对齐,消掉启动时的 Error 1091
Docker Build / Build and Push Docker Image (push) Successful in 29s
Docker Build / Deploy to Server (push) Successful in 2s
生产启动日志里出现:Failed to migrate *model.CertBlacklist:
Error 1091 Can't DROP 'uni_cert_blacklists_fingerprint'。
MySQL 里唯一索引按列名建成 fingerprint,GORM 期望 uni_cert_blacklists_fingerprint,
AutoMigrate 想先 DROP 再建。沿用 device_sessions 的老做法:迁移前用
renameIndexTo 把索引名对齐,之后不再报错(不用 skipMigrate 绕过)。
2026-11-22 13:01:13 +08:00
hermes 02f7fd0feb feat(protect): 区分驱动证书与应用证书,用途不匹配直接拒
Docker Build / Build and Push Docker Image (push) Successful in 59s
Docker Build / Deploy to Server (push) Successful in 2s
用户要求:驱动证书和应用证书要分清,有的只能签一种,有的两种都能。

判据是证书 EKU(internal/protect/usage.go):
- 应用:Code Signing 1.3.6.1.5.5.7.3.3(老微软证书还有 1.3.6.1.4.1.311.2.1.21/22)
- 驱动:Kernel Mode Code Signing 1.3.6.1.4.1.311.61.1.1(KMCS),以及 ELAM/HAL 等
- 没有 EKU 扩展的老证书:按通用处理(能签应用与驱动),单独标「未声明用途」
- 坑:Go 会把 KMCS 解析成 x509.ExtKeyUsageMicrosoftKernelCodeSigning(13),
  只查 UnknownExtKeyUsage 会把驱动证书误判成「应用」——两处都要看。

行为:
- 身份列表带 usage(应用/驱动/两者/不可用),前端下拉直接标用途
- 选证书后按上传文件类型过滤身份(.exe 只列应用用途,.sys 只列驱动用途),
  并显示「该文件里:可签应用 N 套 / 可签驱动 M 套」,没有对应用途时琥珀提示
- 应用证书签 .sys、纯 KMCS 证书签 exe 都在建任务前 400 拦住,带 EKU 说明
- 内核驱动(.sys / PE 子系统 NATIVE)走「仅签名」:绝不注入用户态壳
  (注进内核模块会加载失败),产物无 .vfy 节,只有 Authenticode 签名
- 上传白名单放行 .sys/.efi

实测(真实 79 套包 + 自造三种 EKU 证书 + 假 .sys):
- 真实驱动签名包:应用 79 套 / 驱动 0 套(OID 显示 CodeSigning + 商业代码签名)
- 应用证书 + .sys → 400;纯驱动证书 + exe → 400;双用途证书 + exe → 200
- 驱动证书 + .sys → 仅签名,产物 2878976→2880512,签名者 CN=DriverSigner,
  产物里 no VFY3(确认没加壳)
- 修掉一个隐蔽 bug:驱动分支里用 := 遮蔽了外层 out,导致产物落盘 0 字节
  而任务显示 done、output_size 却有值
2026-11-22 12:54:01 +08:00
hermes 850ab691b7 feat(protect): 过期证书可签之外,补上吊销与拉黑标记
Docker Build / Build and Push Docker Image (push) Successful in 1m9s
Docker Build / Deploy to Server (push) Successful in 3s
用户问:verify 现在能签过期签名吗(signtool hook 日期那套)。能签,f6a4c7d 起就允许
过期证书签并给警告。这次补的是另外两件事——吊销和拉黑,它们和过期是三回事:

- 过期:NotAfter 已过,签名照写(Windows 判不受信任)
- 吊销:CA 主动作废(私钥泄露/停止运营),OCSP 或 CRL 会答 revoked
- 拉黑:微软 Disallowed Certificate Trust List,Windows 会直接拒绝其签名

实现(internal/protect/revocation.go):
- CheckRevocation:优先 OCSP(AIA 取签发者 → 验应答),回落 CRL(CDP),
  要求应答未过期才作结论;结论 good/revoked/unknown,带原因与来源。
  明确结论缓存 6h,「查不到」只缓 10min——端点抽风不该把结论钉死。
- BanState:自动下载并缓存微软拉黑名单(CAB → cabextract → CTL 哈希),
  同时比对平台黑名单;哈希按 md5/sha1/sha256(全量/截断) 多形态比对。
- 加壳前把关:已吊销 / 已被拉黑 → 400 拒绝并给出吊销日期与原因;
  查不到只提示不拦(老证书的 OCSP 端点经常已停服,实测 VeriSign 回 unauthorized)。
- 新表 cert_blacklist(指纹/主题/原因/备注)+ 增删查接口,运维可手动拉黑。
- 身份接口 ?check=N 只查选中的那一套,避免 79 套身份整包联网。
- 前端:选中身份后显示「证书状态:吊销 / 拉黑」徽章(绿/红/灰),悬停看详情。

实测:
- 真实 81 私钥包的 #1:CRL 查询 http://cs-g2-crl.thawte.com/ThawteCSG2.crl → good;
  微软拉黑名单 → good(不在表里)
- 自造 CA + CRL(http 服务)+ 已吊销叶证书:判 revoked,加壳返回
  400「该证书已被 CA 吊销」+ 吊销日期
- 平台黑名单:拉黑后加壳 400「该证书已被本平台拉黑:私钥疑似泄露」,解除后恢复 200
- UI 徽章实测显示「吊销:正常 拉黑:正常」
2026-11-22 12:33:14 +08:00
hermes 0fce2c8aef fix(ci): Dockerfile 在 go mod download 前先 COPY third_party
Docker Build / Build and Push Docker Image (push) Successful in 1m0s
Docker Build / Deploy to Server (push) Successful in 2s
go.mod 用 replace 指向 ./third_party/go-pkcs12,镜像里只 COPY go.mod/go.sum
就 download 会报 replace 目标目录不存在,构建直接失败(run 939)。
2026-11-22 12:10:11 +08:00
hermes d942da1639 fix(protect): 修「驱动签名打包」这类 pfx 解析失败:81 套身份全部可用
Docker Build / Build and Push Docker Image (push) Failing after 8s
Docker Build / Deploy to Server (push) Skipped
用户上传真实的驱动签名打包 pfx(81 把私钥 / 79 张证书),界面只报「解析失败」。
根因不是口令,是 go-pkcs12 一遇到不认识的 bag 属性就整包报错,而 Windows
导出的 pfx 一定带私有属性(本例 OID 1.3.6.1.4.1.311.17.3.75)。

1) 本地改造 go-pkcs12(third_party/go-pkcs12 + go.mod replace)
   未知属性改为跳过,等价于 openssl 的行为。不认识的属性不影响证书与私钥。
2) 解析失败不再是一句话:新增 PFXError{Reason,Hint,Detail},按魔数判断文件
   到底是什么(pfx / pem / pkcs7 / der 证书 / der 私钥 / 压缩包),并把
   「口令错」和「结构不对」分开判——否则「只有证书的 pfx」会被说成口令错,
   用户改口令永远改不好。口令候选会试 原值 / 去首尾空白 / 空串。
   顺带支持 PEM(证书+未加密私钥)直接上传。
3) 大包不再拆成 N 条记录:79 套就建 79 条记录没法用。改为一条记录 +
   记下身份数,新增 GET /dev/sign-profiles/:id/identities 列全部身份,
   加壳时用 cert_identity 指定第几套,签名那一刻才把那一套单独拆出来
   (LoadMaterial 支持 identity,osslsigncode 只认文件里第一套)。
4) 前端:选中多身份证书时出现「签名身份」可搜索下拉(#序号 · CN · 到期,
   过期标黄),默认第一套;证书下拉标注「N 套身份」。
5) cmd/pfxprobe:本地诊断工具,秒看文件形态/证书数/私钥数/每套到期。

实测(用户真实文件,口令 123456):
- 解析:79 张证书 / 81 把私钥 / 79 套身份(2 把私钥没有配对证书)
- 身份列表接口返回 79 条,含 NVIDIA Corporation / Take-Two 等
- 选第 43 套(NVIDIA)签名 → osslsigncode verify 产物 Subject 为
  CN=NVIDIA Corporation,与面板所选一致
- 前后失败对照:改前「unknown attribute with OID 1.3.6.1.4.1.311.17.3.75」
2026-11-22 12:03:02 +08:00
hermes bd04ac88dd feat(protect): 一个 pfx 里的多套签名身份全部解析出来,任选一套签
Docker Build / Build and Push Docker Image (push) Successful in 1m15s
Docker Build / Deploy to Server (push) Successful in 2s
之前只解析出「文件里第一套」,其余几套只能在提示里看到名字、用不上。
现在上传时按套拆开,每套单独编码成一份单身份 pfx,各建一条记录,
加壳页任选一条即可真的用那一套签名。

实现(internal/protect/pfx.go 新增 SplitPFX):
- 第一遍按文件顺序给每把私钥配证书(公钥比对),记下哪些证书是身份证书
- 链 = 没有配到私钥的证书(中间 CA / 根)。刻意不把「另一套身份的叶子证书」
  塞进链里 —— 实测那样做产物证书表里会混进 Signer A,看起来像被 A 签过
- 每套用 pkcs12.Modern.Encode 重新打包(AES 失败退 LegacyRC2),口令沿用原口令
- 链式包(1 套私钥 + N 张 CA)仍是一条记录,不会被误拆

后端 signprofiles.go:抽出 createProfile(),多套时循环建记录,命名
「<原名> · 第N套 <CN>」,响应回 created/items;只有证书没私钥仍是 400。

前端:上传成功提示区分单套/多套(多套时列出每套 subject)。

实测(keytool 造 2 套私钥 p12):
- 上传 → 2 条记录(第1套 Signer A / 第2套 Signer B)
- 用第2套签名 → osslsigncode verify 产物证书表全是 Signer B,摘要一致
  (改之前:无论选谁都只能签出 Signer A)
- 链式 pfx → 仍 1 条记录,产物含 Leaf Signer + Test Root CA
- 只有证书 → 400 人话报错
2026-11-22 11:38:28 +08:00
hermes b275de31a7 feat(protect): 正确处理一个 pfx 里有多张证书的情况
Docker Build / Build and Push Docker Image (push) Successful in 59s
Docker Build / Deploy to Server (push) Successful in 3s
用户问:我的 pfx 可能一个文件包含很多个证书,能处理吗?
实测三种形态,行为全部对齐签名工具(osslsigncode / OpenSSL PKCS12_parse):

1) 单身份(1 证书 + 1 私钥):普通情况。
2) 链式(叶子 + 中间 CA + 根,证书多但私钥一把):这是好事,签名会把整条链
   写进去,验签更容易过。原来「取第一个证书当签名证书」的做法在这里是错的
   —— 链包里第一张可能是中间 CA。改为按「公钥与私钥配对」认叶子证书。
3) 多身份(一个文件里好几套 私钥+证书):签名工具只会用第一套,原来完全没提示。
   现在上传时就解析出每套身份(序号/主题/到期),库里存 cert_count / key_count,
   列表显示「2 张 / 2 套私钥」,加壳页选中时明确提示「仅使用第一套(CN=…)」。

其它:
- 只有证书没有私钥的 pfx 直接拒(原来会存下来,直到加壳时才炸),报错翻成人话
- 解析全部纯 Go(go-pkcs12 + 自解析 PKCS#1/SEC1),因为生产镜像是 Alpine 没有 openssl CLI
- 签名证书列表新增「证书数」列;schema 补 cert_count/key_count

实测(keytool 造 2 套私钥 p12、openssl 造 3 张链式 pfx、cert-only pfx):
- 单证书 → 1 张 / 1 把
- 链式   → 3 张 / 1 把,签名证书正确识别为叶子;osslsigncode verify 产物里
           同时含 Leaf Signer 与 Test Root CA(链完整)
- 多身份 → 2 张 / 2 把,身份列表 Signer A + Signer B;实际签名者为 Signer A,
           与面板报告一致(不是按到期时间瞎排序)
- 只有证书 → 400「这个文件里只有证书、没有私钥(不是标准 pfx),签不了名」
2026-11-22 11:21:11 +08:00
hermes f6a4c7d40a feat(protect): 支持用过期证书签名 + 上传时解析证书到期时间
Docker Build / Build and Push Docker Image (push) Successful in 1m11s
Docker Build / Deploy to Server (push) Successful in 2s
需求:pfx 证书过期后仍要能用来签产物。

1) 去掉「证书已过期」的硬拒绝。私服/内网分发场景下「有签名」比「链被信任」
   更重要,过期证书照样能写入 Authenticode。改为:允许,但在创建任务的响应
   里带 warning,前端选中过期证书时显示琥珀色提示条,下拉选项本身也标
   「已过期」。安全相关的校验(平台不匹配、已停用、非本人、APK/ELF)全部保留。

2) 上传证书时解析 Subject 与 NotAfter(纯 Go,software.sslmate.com/src/go-pkcs12)。
   之前这两个字段从没被填过 —— verify 的镜像是 Alpine,里面没有 openssl CLI,
   列表里「到期时间」永远是「无到期信息」,过期提醒形同虚设。
   解析失败不阻断上传(口令错也能存下来),只是没有到期信息。

3) 「N 天后过期」只对未过期且 30 天内生效;过期项不再显示负数天数。

实测(本地 osslsigncode 2.9,用 openssl 生成 2020-2021 的真过期证书):
- 上传 → not_after=2021-01-01 落库,Subject=CN=VFY Expired Signer,O=Hermes
- 带该证书加壳 → 任务 done,响应 warning=「所选证书已于 2021-01-01 过期…」
- osslsigncode verify 产物:Signer CN=VFY Expired Signer,
  message digest 与计算值一致 → 签名确实写进去了
- 界面:下拉列出过期项并标注「已过期」,选中后出现琥珀色提示条
2026-11-22 11:02:23 +08:00
hermes 6340ba9e38 feat(protect): 加壳页选证书重签 + 修签名路径致命 bug
Docker Build / Build and Push Docker Image (push) Successful in 1m35s
Docker Build / Deploy to Server (push) Successful in 4s
用户反馈「签名证书上传后怎么用」——查下来三个问题,全修:

1) 面板根本没有证书入口。上传证书后无处可选,只有直接打 API 才用得上。
   加壳页新增「重签证书」下拉:按文件类型自动过滤(PE→windows、IPA→ios),
   只列启用且未过期的证书,显示到期日与 30 天内过期提醒;不选=不重签。
   APK/ELF 明确提示不支持(APK 走服务端 keystore,ELF 无签名机制)。

2) 证书被静默忽略的竞态。原流程是先 CreateAndRun(内部已 go execute),
   之后再 UPDATE sign_profile_id,协程可能先读到 NULL → 任务成功但没重签。
   改为建任务时就把 sign_profile_id 写进 task(CreateAndRunSigned /
   CreateAndRunSyncWithSign),handler 里先校验再创建。

3) 【致命】签名路径一直是相对路径,osslsigncode 跑不起来。
   PROTECT_DIR 默认 data/protect 是相对的,而 SignPE 用 runCmd(workDir,…)
   把子进程 cwd 切到了 workDir,于是 cert.p12 的 data/protect/… 被解析成
   workDir/data/protect/… → Failed to read PKCS#12 file。生产上这条路径
   从来没成功过(历史任务列表里能看到 exit status 255)。
   NewRunner 与 LoadMaterial 统一转绝对路径。

顺带:
- 建任务前校验证书:平台与文件类型匹配、未过期、状态 active、归属本人
- 签名证书列表加「到期时间」列:已过期红、30 天内黄
- i18n 补 9 个键(zh/en)

实测(本地装 osslsigncode 2.9,不看文案看产物):
- 带证书加壳 → osslsigncode verify 显示 Signer CN=VFY Test Signer,
  message digest 与计算值一致(链不可信是自签名的正常现象)
- 不带证书 → 产物无签名(对照组)
- 负向:平台不匹配/已过期/已停用/不存在/APK 带证书,五种全部 400 拦下
2026-11-22 10:47:54 +08:00
hermes 96d72f3611 style(admin): 加壳页与签名证书页改用项目统一组件
Docker Build / Build and Push Docker Image (push) Successful in 1m0s
Docker Build / Deploy to Server (push) Successful in 3s
之前这两页用的是原生 <select>/<input>/<textarea>/<table>,跟项目 shadcn 风格不一致。

- 下拉框:全部换成 UiSelect(应用选择、更新策略、签名平台);状态筛选改用 DataTable 同款 SingleFilter(popover + 已选徽标)
- 表单:UiInput / UiTextarea / UiLabel / UiCheckbox
- 列表:改用项目统一的 DataTable(TanStack),新增 protect/components/{columns.ts,data-table.vue} 与
  sign-profiles/components/{columns.ts,data-table.vue},带列显示切换、分页、空态与加载态
- 类型收到 data/schema.ts,两页共用,避免结构化不兼容
- 修横向溢出:源文件列固定宽度 + 失败信息 line-clamp-2 + 包装器 min-w-0(此前长报错把整页撑到 1811px)

实测:两页原生 select 数为 0;bodyScrollWidth 1592 = 视口;统计卡右边界 1568、表格右边界 1542 均在视口内;
下拉展开样式与项目其他 Select 一致(深色、圆角、勾选、宽度对齐)
2026-11-21 23:30:49 +08:00
hermes 8acf72dd6e polish(database): 索引改名只在真正发生时打日志
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 2s
renameIndexTo 返回是否改动过;已对齐的库启动时完全静默。
2026-11-21 22:48:56 +08:00
hermes 1d4ad9bf54 refactor(database): 迁移代码收敛出方言层,去掉散落的 sqlite 分支
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 4s
之前 runMigrations 里混着 sqlite 专用 PRAGMA(在 MySQL 上静默失败、导致误判),
每处靠 if isSQLiteDB() 打补丁。

- 新增 internal/database/dialect.go:dialectName / tableColumns / columnOf / hasColumn
  / renameIndexTo / ensureColumnType / relaxNotNull,方言差异只出现在这一个文件
- runMigrations 里方言分支归零:加列用 hasColumn、改列类型用 ensureColumnType、
  放可空用 relaxNotNull、索引改名用 renameIndexTo
- 删掉 risk_control_rules 那段硬编码重建表(模型里 ApplicationID 是可空指针,
  AutoMigrate 自己会重建;实测 sqlite 上 NOT NULL 位 1→0 且数据保留)
- fixDeviceIDColumnType / ensureDeviceSessionUniqueIndexName 改为调用方言层

验证:全新库与老库启动均无 MIGRATE/error 日志;造 NOT NULL 老库实测被 AutoMigrate
修正且数据不丢;终端登录与面板登录均 200;单测全过
2026-11-21 22:42:28 +08:00
hermes 621b783960 fix(model): instance_id 唯一约束改用 GORM 约定名,根除 1091 迁移报错
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 2s
真正机制:MySQL 驱动把「列上有唯一索引」报成 ColumnType.Unique()==true,而
uniqueIndex: 标签不计入 field.Unique,于是 MigrateColumnUnique 每次启动都判定
「库里有唯一约束、模型没要求」,去 DROP 按约定算出的 uni_device_sessions_instance_id
(库里从来没有这个名字)→ MySQL 1091。

- InstanceID 标签 uniqueIndex:idx_device_instance → unique(GORM 约定名即
  uni_device_sessions_instance_id)
- 新增 ensureDeviceSessionUniqueIndexName:启动时把历史索引名幂等地改成约定名
  (MySQL: RENAME INDEX;SQLite: DROP+CREATE),之后 AutoMigrate 完全无操作
- 实测:老库改名后数据完好(行数不变、约束名为约定名);全新库直接建成约定名;
  登录写入 device_sessions 正常
2026-11-21 22:23:29 +08:00
hermes 10347aa330 refactor(model): 从根上消除 device_id 字段歧义,撤掉迁移特例
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 2s
上一版用 skipMigrateOnMySQL 绕过了 GORM 的误判,属于打补丁。真正的根因是
DeviceSession.DeviceID 与 UserDevice.DeviceID 同名,GORM 推断外键时选错对象。

- DeviceSession.DeviceID → UserDeviceID,tag 钉死 column:device_id 与索引名
  idx_device_sessions_device_id(与线上现有索引同名,不产生任何 DDL 变更)
- 双向关系显式写 foreignKey:UserDeviceID;references:ID
- 删除 skipMigrateOnMySQL 及相关预检函数,AutoMigrate 恢复对这些表的正常管理
- JSON 键仍为 device_id,接口不变;所有 Go 引用同步改名

验证:全新 sqlite 建库列/索引与线上一致;老库登录后 device_sessions 正确写入
user_devices.id;四处 PRAGMA 的 sqlite 守卫保留
2026-11-21 22:15:30 +08:00
hermes 2e3b2e3875 fix(migrate): 消掉启动时的迁移噪声,不再对线上表做无效 DDL
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 2s
背景:UserDevice 与 DeviceSession 都有 device_id 字段(一个是设备指纹 varchar,一个是
指向 user_devices.id 的数值外键),GORM 推断关系时选错 foreignKey,每次启动都会试图把
user_devices.device_id 改回数值型(MySQL 1265 Data truncated),并 DROP 早已不存在的
uni_device_sessions_instance_id(MySQL 1091)。

- 新增 skipMigrateOnMySQL:MySQL 上 device 两张表的关键列/索引已就位时跳过 AutoMigrate
- 四处 PRAGMA(sqlite 专有)加 isSQLiteDB() 守卫;risk_control_rules.user_id 在 MySQL 上
  改用 Migrator().HasColumn 判断,不再误报 Duplicate column 'user_id'
2026-11-21 21:56:21 +08:00
hermes 64a0a5ed49 feat(protect): ELF 壳支持 DNS 与 HTTPS
Docker Build / Build and Push Docker Image (push) Successful in 36s
Docker Build / Deploy to Server (push) Successful in 2s
- 壳内部:从 /proc/self/maps 找 libc 基址 → 内存 ELF → DT_SYMTAB/DT_STRTAB(注意 ld.so 已重定位成绝对地址)→ 按名解析 getaddrinfo,域名走系统解析链
- HTTPS 交给系统 curl:fork+pipe,请求体经 stdin 传(口令不出现在 argv,ps 看不到),证书校验用系统信任库
- 证书不受信任 / 端口不通 / 缺 curl 三种情况都 fail closed 并给出明确提示
- 修 maps 解析(dev/inode 两列长度不定,改为找行内第一个 '/')
- 实测矩阵:http+IP、http+域名、https(受信任)、https(自签拒绝)、错误口令、账号不存在、/bin/ls 真机二进制全部符合预期
2026-11-21 21:28:54 +08:00
hermes 80bc105d95 fix(auth): 终端用户口令改 bcrypt,兼容历史明文自动升级
Docker Build / Build and Push Docker Image (push) Successful in 29s
Docker Build / Deploy to Server (push) Successful in 3s
- 新增 service.VerifyAppUserPassword:bcrypt 直接比对;明文定长比较,命中后条件更新升级为 bcrypt(WHERE password=旧值,避免并发覆盖)
- 登录、解绑设备鉴权、修改口令三处统一走该函数
- 注册与改密的新口令入库前 bcrypt 哈希(此前注册写明文、重置写哈希,库里是混合状态)
- 实测:明文用户首次登录成功并落库为 $2a$ 哈希;二次登录走 bcrypt;错误口令拒绝;新注册与改密均为哈希
2026-11-21 21:22:36 +08:00
hermes 5169bf249e feat(protect): 支持 Linux x86_64 ELF 加壳
Docker Build / Build and Push Docker Image (push) Successful in 1m0s
Docker Build / Deploy to Server (push) Successful in 2s
- 新增 internal/protect/elf.go:追加 PT_LOAD 段(搬 phdr 表)+ 改 e_entry,PE/ELF 统一走 PatchAuto
- 壳 assets/elfstub64.bin:无 libc 纯 syscall 实现(登录 POST / 关回显读口令 / hostname 作设备 ID)
- Runner 产物命名:无扩展名不再硬加 .exe
- Info 字段扩到 uint64 以容纳 ELF 地址;上传白名单放行 .elf/无扩展名
- cmd/elfpack:命令行 ELF 打包工具
- 单测:结构校验 + 非 x86_64 精确拒绝
- 实测:/bin/ls、PIE、非 PIE 三种目标;正确口令放行、错误口令/断网/403 拦截;设备绑定写入 user_devices
2026-11-21 20:06:03 +08:00
hermes 7f19742c21 feat(protect): 签名构建跳过整文件 CRC(flags.bit1)
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 2s
- 壳 bootstrap6.c:flags bit1=已签名时跳过 crcFile 比对(Authenticode 会追加证书表并改校验和,与整文件 CRC 互斥)
- pepatch:PatchSigned/PatchAutoSigned,签名构建写 flags|=2 且 crcFile=0
- Runner:PE 任务带证书 → 走签名构建,注入后调 osslsigncode 重签,Note 记录结果
- 重编 x64/x86 blob(10000/8384 字节)并替换 assets
- Wine 回归:普通 exit0/F、签名标记 exit0/F、未签名+PE头篡改 exit13/3
2026-11-21 19:38:03 +08:00
hermes 18ea287d3d feat(sign): 面板「签名证书」页
Docker Build / Build and Push Docker Image (push) Successful in 58s
Docker Build / Deploy to Server (push) Successful in 2s
- /admin/sign-profiles:平台上选(Windows/iOS)、名称、证书、口令、iOS 描述文件
- 列表只显示元数据(平台徽标、格式、是否含描述文件、时间),删除按钮二次确认
- 文件选择器改成统一风格按钮 + 文件名回显,隐藏原生 input
- 路由/侧边栏/面包屑/i18n(zh+en 各 40 键)
2026-11-21 19:14:46 +08:00
hermes 72a7bdb3d6 fix(sign): 临时目录父目录先建 + UnsupportedError 文案中立化
Docker Build / Build and Push Docker Image (push) Successful in 30s
Docker Build / Deploy to Server (push) Successful in 2s
- LoadMaterial 里 MkdirTemp 前先建 data/protect/tmp(否则 IPA 任务报 stat ... no such file or directory)
- 错误信息去掉「当前版本只对 Windows PE 做注入」这种会随能力变化而失效的表述,改成「XX 已识别(arch);原因;需要:…」
2026-11-21 18:54:46 +08:00
hermes 8f7caad687 feat(sign): 签名器入镜像 + iOS IPA 注入重签
Docker Build / Build and Push Docker Image (push) Successful in 40s
Docker Build / Deploy to Server (push) Successful in 3s
- Dockerfile 多阶段:zsign(官方 musl 静态版 v1.1.3)+ osslsigncode(源码编译),运行期依赖 libcrypto3/libssl3/libcurl/zlib/libstdc++
- sign.go:LoadMaterial 解密证书到临时明文(用完清理)、SignIPA(zsign -l 注入 dylib + -k/-m 重签)、SignPE(osslsigncode,验签失败仅提示不算任务失败)
- protect.go:RunWithTask 携带任务上下文,IPA 走证书+dylib 路径
- kind.go:Injectable 支持 IPA(检查 zsign),缺证书/dylib 时给出精确缺口
- 实测:osslsigncode 对真实 PE 签名 Succeeded(+1568 字节证书表),zsign musl 在 alpine 可运行
2026-11-21 18:46:44 +08:00
hermes 9d0c50e7f2 feat(sign): 签名证书资产层(AES-GCM 加密存储)
Docker Build / Build and Push Docker Image (push) Successful in 29s
Docker Build / Deploy to Server (push) Successful in 3s
- model.SignProfile:platform(windows/ios)、证书/口令/描述文件加密落盘,库里只留元数据
- 主密钥由 app.jwt_secret 派生,目录 0700、文件 0600;响应永不回证书内容与口令
- /dev/sign-profiles 上传/列表/详情/删除;iOS 强制要求 .mobileprovision
- ProtectTask 增加 sign_profile_id(上传时可指定,校验归属),为重签做准备
- 单测:加解密往返/换钥失败/篡改检测/文件权限/平台归一化
2026-11-21 18:20:36 +08:00
hermes 7840872f91 feat(protect): Android APK 加壳(注入壳类 + 重签)
Docker Build / Build and Push Docker Image (push) Successful in 1m5s
Docker Build / Deploy to Server (push) Successful in 3s
- internal/protect/apk.go:apktool 反编译→合并壳 smali→改 application→注入 vfy_cfg.json→回编译→对齐→v1/v2/v3 重签
- 支持两种工具形态:PATH 二进制(Debian)或 JRE+fat jar(Alpine 生产镜像)
- 内嵌 Android 壳 smali(com.vfy.ShellApplication:卡密/账号弹窗、设备指纹、原 Application 反射拉起)与开发签名证书
- Dockerfile:装 openjdk17-jre-headless 并在构建期下载 apktool.jar / uber-apk-signer.jar
- 任务备注分流(PE 报入口变化,APK 报重签信息);包名启发式过滤权限类字符串
- 单测:manifest 改写、包名识别、E2E(真跑 apktool+signer)
2026-11-21 18:13:22 +08:00
hermes 0eac13578e feat(protect): 多格式识别(APK/IPA/ELF/Mach-O)与明确缺口提示
Docker Build / Build and Push Docker Image (push) Successful in 57s
Docker Build / Deploy to Server (push) Successful in 2s
- protect/kind.go:按内容识别 PE/APK/IPA/ELF/Mach-O,APK(AndroidManifest+dex)/IPA(Payload/*.app) 走 zip 结构判定
- PatchAuto 按类型分发;未支持类型返回 *UnsupportedError,说明缺哪一环
- ProtectTask 新增 kind;上传白名单放宽到 .exe/.dll/.apk/.ipa
- MCP verify_protect_version 对非 PE 入口直接给结论
- 面板加「类型」列、接受 apk/ipa 并展示具体缺口;单测覆盖识别与拒绝路径
2026-11-21 17:21:59 +08:00
Hermes Agent 1a69b61e75 merge feat/protect: 加壳加固(Windows PE 服务端加壳 + 面板 + MCP + 版本联动)
Docker Build / Build and Push Docker Image (push) Successful in 57s
Docker Build / Deploy to Server (push) Successful in 2s
2026-11-21 17:14:11 +08:00
hermes 683ebb31df feat(versions): 加壳版本可视化(已加固徽标 + 派生来源)
- 版本列表返回 source_version(派生来源版本号),新增「派生自」列
- 版本号后加「已加固」徽标;未加固版本该列显示 -
- 版本详情页加加壳来源横幅(来源版本 + 跳转加壳任务)
- PublishAsVersion 自动进位改为跳过已占用的号;不再误回写 task.version_id
- 前端 schema 补 protected/source_version_id/protect_task_id/source_version
2026-11-21 16:54:56 +08:00
hermes 02df87f464 feat(protect): 加壳产物落成新版本记录
- Version 新增 protected / source_version_id / protect_task_id,ProtectTask 新增 version_id
- protect.PublishAsVersion:产物写入内容寻址存储、复制来源版本其余文件、版本号可自动进位
- 路由 POST /dev/protect/tasks/:id/publish、MCP 工具 verify_publish_protected_version
- 面板任务行加「生成版本」弹窗(版本号/策略/更新说明/立即发布)
- 单测 BumpVersion
2026-11-21 15:19:56 +08:00
hermes 22570341ef feat(protect): 面板「加壳加固」页面
- pages/admin/protect/index.vue:应用选择 + 拖拽/点击上传 exe + 统计卡 + 任务表(状态轮询 2s、下载、删除)
- 路由 /admin/protect、侧边栏入口(PackageCheck)、面包屑 titleMap
- i18n zh/en 各补 nav.protect + admin.protect 38 键
- seedtest 增加面板管理员(admin/admin123)便于本地端到端验证
2026-11-21 14:56:02 +08:00
hermes 9c625ebb6a feat(protect): MCP 加壳工具 + 任务执行下沉到 protect 包
- protect 包新增 CreateAndRun / CreateAndRunSync / execute / WaitSource,admin 与 MCP 共用
- MCP 13 个工具(原 10 + verify_protect_version / verify_list_protect_tasks / verify_get_protect_task)
- verify_protect_version 从版本的入口 exe 直接加壳,支持 dry_run 与 base_url 覆盖
- cmd/seedtest: 本地 sqlite 造测试数据(应用+版本+真实 exe 内容文件)用于端到端验证
2026-11-21 14:12:49 +08:00
hermes 66056cdfa3 feat(protect): 服务端加壳任务
- internal/protect: PE 注入(改入口 + 内嵌壳 DLL + 双层 CRC32),内嵌 x64/x86 blob 与壳 DLL
- 模型 ProtectTask + 自动迁移
- 路由 /api/v1/dev/protect/tasks: 创建(异步)/列表/详情/下载/删除
- 壳侧新增 device_auto:运行时用 MachineGuid+卷序列号+计算机名算设备指纹
- 单测:资产完整性、cfg 生成、路由注册、产物命名
2026-11-21 13:55:40 +08:00
Hermes Agent d083905c98 fix: 修复设备写入失败 + 更新检测支持清单指纹
Docker Build / Build and Push Docker Image (push) Successful in 29s
Docker Build / Deploy to Server (push) Successful in 2s
1) device_id 列类型:模型是 varchar(100),早期 MySQL 建成了 bigint,
   AutoMigrate 不改已有列类型 → 心跳写设备报 Error 1265 Data truncated,
   user_devices 永远 0 行。新增 fixDeviceIDColumnType() 迁移显式 ALTER。
2) check-update 支持可选 manifest_hash:客户端上报本地清单指纹且与服务器
   不一致时,即使版本记录 ID 相同也下发更新(解决"换包不改版本号不生效")。
   无更新分支同时回传 latest_version_id / manifest_hash / reason。
3) 面板编辑版本时,若替换了文件但版本号未变,返回 warning 明确提示。
2026-11-21 03:06:08 +08:00
Hermes Agent fb77d9799d fix(mcp): simulate_check_update 的 manifest_url 缺 app_key
Docker Build / Build and Push Docker Image (push) Successful in 28s
Docker Build / Deploy to Server (push) Successful in 3s
packageResult 读的是未预加载的 v.Application.AppKey,实际输出成
/api/v1/app//versions/manifest。改为由调用方显式传入 appKey。
2026-11-21 02:55:36 +08:00
150 changed files with 23028 additions and 1018 deletions
+3
View File
@@ -52,3 +52,6 @@ temp/
# Trae
.trae/
# 壳源码的本地构建产物
shell/**/out/
+40 -1
View File
@@ -13,6 +13,21 @@ COPY frontend/ ./
ENV NODE_OPTIONS="--max-old-space-size=2048"
RUN pnpm vite build
# 签名器:zsign(iOS 注入 dylib + 重签)用官方 musl 静态版,osslsigncode(Windows Authenticode)源码编译
FROM alpine:latest AS signer-fetcher
RUN apk add --no-cache curl tar zstd
RUN curl -fsSL -o /tmp/zsign.tar.gz \
https://github.com/zhlynn/zsign/releases/download/v1.1.3/zsign-linux-musl-static.tar.gz \
&& tar xzf /tmp/zsign.tar.gz -C /tmp && mkdir -p /out \
&& mv /tmp/zsign-musl /out/zsign && chmod +x /out/zsign
FROM alpine:latest AS signer-builder
RUN apk add --no-cache build-base cmake linux-headers openssl-dev zlib-dev curl-dev git
RUN git clone --depth 1 https://github.com/mtrojnar/osslsigncode.git /src \
&& cd /src && mkdir -p build && cd build \
&& cmake .. -DCMAKE_BUILD_TYPE=Release > /dev/null && make -j"$(nproc)" > /dev/null \
&& mkdir -p /out && cp osslsigncode /out/
FROM golang:1.23-alpine AS backend-builder
WORKDIR /app
@@ -21,6 +36,10 @@ RUN apk add --no-cache git
COPY backend/go.mod backend/go.sum ./
# third_party 里有本地改造的 go-pkcs12(go.mod 用 replace 指过来),
# 必须在 go mod download 之前就位,否则 replace 目标目录不存在直接报错。
COPY backend/third_party ./third_party
RUN go mod download
COPY backend/ ./
@@ -33,7 +52,19 @@ RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main ./cmd/main.g
FROM alpine:latest
RUN apk --no-cache add ca-certificates tzdata su-exec mailcap
# Android 加壳工具链:Alpine 仓库没有 apktool/apksigner,改自带 fat jar
# apktool 反编译 / 回编译(改 manifest + 合并 smali)
# uber-apk-signer 对齐 + v1/v2/v3 重签(自带 apksig,不需要 build-tools)
# cabextract:解微软拉黑名单(disallowedcertstl.cab),吊销/拉黑检测要用
RUN apk --no-cache add ca-certificates tzdata su-exec mailcap openjdk17-jre-headless curl cabextract \
libcrypto3 libssl3 libcurl zlib libstdc++ \
&& mkdir -p /app/tools \
&& curl -fsSL -o /app/tools/apktool.jar \
https://github.com/iBotPeaches/Apktool/releases/download/v2.9.3/apktool_2.9.3.jar \
&& curl -fsSL -o /app/tools/uber-apk-signer.jar \
https://github.com/patrickfav/uber-apk-signer/releases/download/v1.3.0/uber-apk-signer-1.3.0.jar \
&& java -jar /app/tools/apktool.jar --version \
&& chmod -R a+rX /app/tools
RUN addgroup -g 1001 -S appgroup && \
adduser -u 1001 -S appuser -G appgroup
@@ -47,6 +78,14 @@ RUN chmod +x /usr/local/bin/docker-entrypoint.sh && \
mkdir -p /app/data /app/uploads && \
chown -R appuser:appgroup /app
COPY --from=signer-fetcher /out/zsign /app/tools/zsign
COPY --from=signer-builder /out/osslsigncode /app/tools/osslsigncode
ENV PROTECT_APKTOOL_JAR=/app/tools/apktool.jar \
PROTECT_SIGNER_JAR=/app/tools/uber-apk-signer.jar \
PROTECT_ZSIGN=/app/tools/zsign \
PROTECT_OSSLSIGNCODE=/app/tools/osslsigncode
EXPOSE 8080
ENTRYPOINT ["docker-entrypoint.sh"]
+119
View File
@@ -0,0 +1,119 @@
// 签发自签授权序列号(与 DogProtect tools/dogkeygen 等价,Go 版,便于服务端集成)
//
// 用法:
// doglicgen -key <工程.dog|license.xml> -user "客户A" [-email a@b.c] [-exp 20271231]
// [-max-build 20270101] [-running-time 90] [-hwid <base64>] [-user-data <hex>]
// [-out serial.txt]
// doglicgen -key <file> -verify <serial> # 用公钥验一遍并打印字段
package main
import (
"encoding/base64"
"encoding/hex"
"flag"
"fmt"
"os"
"time"
"verification-platform-backend/internal/doglic"
)
func dateArg(s string) (time.Time, error) {
if s == "" {
return time.Time{}, nil
}
return time.Parse("20060102", s)
}
func main() {
keyPath := flag.String("key", "", "工程/授权文件(含 <LicenseManager Modulus/PrivateExp>)")
user := flag.String("user", "", "客户名")
email := flag.String("email", "", "客户邮箱")
exp := flag.String("exp", "", "到期日 YYYYMMDD")
maxBuild := flag.String("max-build", "", "最高构建日 YYYYMMDD")
runningTime := flag.Int("running-time", 0, "运行时长限制(分钟)")
hwidB64 := flag.String("hwid", "", "绑机数据(base64)")
userDataHex := flag.String("user-data", "", "用户数据(hex,首字节常作产品 ID)")
serialVersion := flag.Int("serial-version", 1, "序列号版本 1 或 2")
out := flag.String("out", "", "写入文件")
verifySerial := flag.String("verify", "", "只验签并打印字段")
flag.Parse()
if *keyPath == "" {
fmt.Fprintln(os.Stderr, "缺少 -key")
os.Exit(2)
}
keys, err := doglic.LoadKeysFromFile(*keyPath)
if err != nil {
fmt.Fprintln(os.Stderr, "读密钥失败:", err)
os.Exit(1)
}
if *verifySerial != "" {
ok, fields, err := doglic.Verify(keys, *verifySerial)
fmt.Printf("verify=%v err=%v\n", ok, err)
for k, v := range fields {
fmt.Printf(" %-14s %s\n", k, v)
}
if !ok {
os.Exit(1)
}
return
}
expDate, err := dateArg(*exp)
if err != nil {
fmt.Fprintln(os.Stderr, "-exp 格式应为 YYYYMMDD")
os.Exit(2)
}
mbDate, err := dateArg(*maxBuild)
if err != nil {
fmt.Fprintln(os.Stderr, "-max-build 格式应为 YYYYMMDD")
os.Exit(2)
}
var hwid, userData []byte
if *hwidB64 != "" {
hwid, err = base64.StdEncoding.DecodeString(*hwidB64)
if err != nil {
fmt.Fprintln(os.Stderr, "-hwid base64 解析失败")
os.Exit(2)
}
}
if *userDataHex != "" {
userData, err = hex.DecodeString(*userDataHex)
if err != nil {
fmt.Fprintln(os.Stderr, "-user-data 应为 hex")
os.Exit(2)
}
}
serial, err := doglic.Sign(keys, doglic.Request{
UserName: *user,
Email: *email,
ExpDate: expDate,
MaxBuildDate: mbDate,
RunningTime: *runningTime,
HWID: hwid,
UserData: userData,
SerialVersion: byte(*serialVersion),
})
if err != nil {
fmt.Fprintln(os.Stderr, "签发失败:", err)
os.Exit(1)
}
ok, fields, verr := doglic.Verify(keys, serial)
fmt.Printf("self-check: %v (%v)\n", ok, verr)
for k, v := range fields {
fmt.Printf(" %-14s %s\n", k, v)
}
if *out != "" {
if err := os.WriteFile(*out, []byte(serial), 0o600); err != nil {
fmt.Fprintln(os.Stderr, "写文件失败:", err)
os.Exit(1)
}
fmt.Printf("已写入 %s(%d 字符)\n", *out, len(serial))
}
fmt.Println(serial)
}
+38
View File
@@ -0,0 +1,38 @@
// elfpack:命令行给 ELF 打壳(运维/调试用)
// 用法: elfpack <目标ELF> <输出> <cfg.json>
package main
import (
"fmt"
"os"
"path/filepath"
"verification-platform-backend/internal/protect"
)
func main() {
if len(os.Args) != 4 {
fmt.Fprintln(os.Stderr, "用法: elfpack <目标ELF> <输出> <cfg.json>")
os.Exit(2)
}
src, err := os.ReadFile(os.Args[1])
must(err)
cfg, err := os.ReadFile(os.Args[3])
must(err)
det := protect.DetectFile(src, filepath.Base(os.Args[1]))
out, info, err := protect.PatchAuto(src, cfg, filepath.Base(os.Args[1]))
must(err)
must(os.WriteFile(os.Args[2], out, 0o755))
fmt.Printf("kind=%s arch=%s %d → %d 字节\n", det.Kind, det.Arch, len(src), info.OutSize)
fmt.Printf("入口 %#x → %#x 段 vaddr=%#x size=%d\n", info.EntryOld, info.EntryNew, info.SecRVA, info.SecSize)
if info.Note != "" {
fmt.Println("说明:", info.Note)
}
}
func must(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
+38
View File
@@ -0,0 +1,38 @@
// 临时工具:以 signed 模式(flags bit1,壳侧跳过整文件 CRC)注入验证壳
// 用法: packsigned <src> <out> <cfg.json>
package main
import (
"fmt"
"os"
"verification-platform-backend/internal/protect"
)
func main() {
if len(os.Args) != 4 {
fmt.Fprintln(os.Stderr, "用法: packsigned <src> <out> <cfg.json>")
os.Exit(2)
}
src, err := os.ReadFile(os.Args[1])
if err != nil {
panic(err)
}
cfg, err := os.ReadFile(os.Args[3])
if err != nil {
panic(err)
}
arch, err := protect.DetectArch(src)
if err != nil {
panic(err)
}
out, info, err := protect.PatchSigned(src, cfg, arch, true)
if err != nil {
panic(err)
}
if err := os.WriteFile(os.Args[2], out, 0o644); err != nil {
panic(err)
}
fmt.Printf("产物 %s %d 字节 入口 0x%x→0x%x crcVfy=%08x crcFile=%08x\n",
os.Args[2], info.OutSize, info.EntryOld, info.EntryNew, info.CrcVfy, info.CrcFile)
}
+40
View File
@@ -0,0 +1,40 @@
// 验证服务端加壳链路:用 protect.Patch 打一个真实 Windows 程序,落盘供 Wine 实测
package main
import (
"fmt"
"os"
"path/filepath"
"verification-platform-backend/internal/protect"
)
func main() {
if len(os.Args) != 4 {
fmt.Fprintln(os.Stderr, "用法: packtest <src.exe> <out.exe> <cfg.json>")
os.Exit(2)
}
src, err := os.ReadFile(os.Args[1])
must(err)
cfg, err := os.ReadFile(os.Args[3])
must(err)
arch, err := protect.DetectArch(src)
must(err)
fmt.Printf("源: %s 架构: %s %d 字节\n", filepath.Base(os.Args[1]), arch, len(src))
out, info, err := protect.Patch(src, cfg, arch)
must(err)
must(os.WriteFile(os.Args[2], out, 0o644))
fmt.Printf("产物: %s %d 字节\n", os.Args[2], info.OutSize)
fmt.Printf("入口 0x%x → 0x%x .vfy RVA=0x%x size=%d\n", info.EntryOld, info.EntryNew, info.SecRVA, info.SecSize)
fmt.Printf("crcVfy=%08x crcFile=%08x\n", info.CrcVfy, info.CrcFile)
}
func must(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
+39
View File
@@ -0,0 +1,39 @@
// 按主题打壳:packtest 固定用 classic 壳,这个工具多了 theme 参数,用来出各套验证界面
// 用法: packthemed <src.exe> <out.exe> <cfg.json> <theme>
package main
import (
"fmt"
"os"
"path/filepath"
"verification-platform-backend/internal/protect"
)
func main() {
if len(os.Args) != 5 {
fmt.Fprintln(os.Stderr, "用法: packthemed <src.exe> <out.exe> <cfg.json> <theme>")
os.Exit(2)
}
src, err := os.ReadFile(os.Args[1])
must(err)
cfg, err := os.ReadFile(os.Args[3])
must(err)
arch, err := protect.DetectArch(src)
must(err)
theme := protect.NormalizeTheme(os.Args[4])
out, info, err := protect.PatchSignedThemed(src, cfg, arch, false, theme)
must(err)
must(os.WriteFile(os.Args[2], out, 0o644))
fmt.Printf("%-10s 架构=%s 产物=%s %d 字节 .vfy size=%d\n",
theme, arch, filepath.Base(os.Args[2]), info.OutSize, info.SecSize)
}
func must(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
+133
View File
@@ -0,0 +1,133 @@
package main
// pfxprobe 本地诊断:把证书文件丢进去,看清它到底是什么、有几套签名身份。
//
// go run ./cmd/pfxprobe -file cert.pfx -pass 口令
//
// 排查「上传后解析失败」时先跑这个:它把文件真实形态、证书/私钥数量、
// 每套身份的到期时间全部列出来,失败也会给出具体原因。
import (
"crypto/x509"
"encoding/pem"
"flag"
"fmt"
"os"
"strings"
"verification-platform-backend/internal/protect"
)
func main() {
file := flag.String("file", "", "证书文件路径(.pfx/.p12/.pem)")
pass := flag.String("pass", "", "pfx 口令")
rev := flag.Bool("rev", false, "顺带查吊销 / 微软拉黑名单(需要网络)")
revLimit := flag.Int("rev-limit", 3, "最多查几套身份的吊销状态")
flag.Parse()
if *file == "" {
fmt.Fprintln(os.Stderr, "用法: pfxprobe -file cert.pfx [-pass 口令]")
os.Exit(2)
}
data, err := os.ReadFile(*file)
if err != nil {
fmt.Fprintln(os.Stderr, "读文件失败:", err)
os.Exit(2)
}
fmt.Printf("文件: %s\n大小: %d 字节\n", *file, len(data))
fmt.Printf("前 16 字节: % x\n", data[:min(16, len(data))])
// 先直接看 PEM(如果是文本)
if blk, _ := pem.Decode(data); blk != nil {
fmt.Printf("PEM 块类型: %s\n", blk.Type)
if blk.Type == "CERTIFICATE" {
if c, e := x509.ParseCertificate(blk.Bytes); e == nil {
fmt.Printf(" 证书: %s 到期 %s\n", c.Subject, c.NotAfter.Format("2006-01-02"))
}
}
} else {
fmt.Printf("不是 PEM 文本;按 DER/二进制处理\n")
}
// 吊销 / 拉黑:默认只查前几套,避免几十套身份时把时间都花在网络上
checkRev := *rev
info, err := protect.ParsePFX(data, *pass)
if err != nil {
fmt.Printf("\n解析失败: %v\n", err)
if pe, ok := err.(*protect.PFXError); ok {
fmt.Printf("原因: %s\n", pe.Reason)
if pe.Hint != "" {
fmt.Printf("建议: %s\n", pe.Hint)
}
if pe.Detail != "" {
fmt.Printf("底层: %s\n", pe.Detail)
}
}
os.Exit(1)
}
fmt.Printf("\n格式: %s\n证书: %d 张\n私钥: %d 把\n可签名身份: %d 套\n说明: %s\n",
info.Syntax, info.CertCount, info.KeyCount, len(info.Identities), info.Note)
for _, id := range info.Identities {
mark := ""
if id.Expired {
mark = " ← 已过期"
}
fmt.Printf(" 第%d套: %s 到期 %s%s\n", id.Index, id.Subject, id.NotAfter.Format("2006-01-02"), mark)
}
if checkRev {
fmt.Printf("\n=== 吊销 / 拉黑(最多查 %d 套) ===\n", *revLimit)
full, ferr := protect.ParseIdentitiesFull(data, *pass)
if ferr != nil {
fmt.Printf("取身份详情失败: %v\n", ferr)
} else {
for i, id := range full {
if i >= *revLimit {
break
}
rev := protect.CheckRevocation(id.Cert, id.Issuer)
ban := protect.BanState(id.Cert, nil)
fmt.Printf(" 第%d套 %-40s 吊销=%s(%s) 拉黑=%s\n",
id.Index, cnOf(id.Subject), rev.Status, rev.Detail, ban.Status)
}
}
}
ids, serr := protect.SplitPFX(data, *pass)
if serr != nil {
fmt.Printf("\n拆分失败: %v\n", serr)
os.Exit(1)
}
fmt.Printf("\n拆分结果: %d 份单身份 pfx\n", len(ids))
for _, id := range ids {
fmt.Printf(" 第%d套 %s 链 %d 张 重打包 %d 字节 sha256:%s\n",
id.Index, id.Subject, id.ChainLen, len(id.PFX), shortHash(id.PFX))
}
}
func shortHash(b []byte) string {
h := fmt.Sprintf("%x", b)
if len(h) > 12 {
return h[:12]
}
return h
}
func cnOf(subject string) string {
parts := strings.Split(subject, ",")
for _, p := range parts {
p = strings.TrimSpace(p)
if strings.HasPrefix(p, "CN=") {
return strings.TrimPrefix(p, "CN=")
}
}
return subject
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
+109
View File
@@ -0,0 +1,109 @@
// seedtest:给本地 sqlite 实例造一套测试数据(应用 + 版本 + 真实 exe 内容文件)
// 用法: go run ./cmd/seedtest <exe路径>
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"time"
"verification-platform-backend/internal/config"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/utils/contentstore"
"golang.org/x/crypto/bcrypt"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintln(os.Stderr, "用法: seedtest <某个 exe 路径>")
os.Exit(2)
}
exePath := os.Args[1]
data, err := os.ReadFile(exePath)
must(err)
config.Init()
database.Init() // 内部已执行 AutoMigrate
// 1) 用户(面板登录用的 User 表,role=admin)
var admin model.User
database.DB.Where("username = ?", "admin").First(&admin)
if admin.ID == 0 {
hash, _ := bcrypt.GenerateFromPassword([]byte("admin123"), bcrypt.DefaultCost)
admin = model.User{Username: "admin", Password: string(hash), Role: "admin", Status: "active"}
must(database.DB.Create(&admin).Error)
fmt.Println("管理员: admin / admin123")
}
// 2) 应用所属用户(客户端账号表)
var user model.AppUser
database.DB.Where("username = ?", "seeduser").First(&user)
if user.ID == 0 {
user = model.AppUser{Username: "seeduser", Password: "x", Email: "seed@local", Status: "active"}
must(database.DB.Create(&user).Error)
}
// 2) 应用
var app model.Application
database.DB.Where("app_key = ?", "seedapp01").First(&app)
if app.ID == 0 {
app = model.Application{UserID: user.ID, Name: "种子应用", AppKey: "seedapp01", MaxDevices: 3, Status: "active"}
must(database.DB.Create(&app).Error)
}
// 3) 内容文件:按平台规则上传到 uploads/files/<h2>/<hash>
sum := sha256.Sum256(data)
hash := hex.EncodeToString(sum[:])
stored := contentstore.ContentFilePath(hash)
must(os.MkdirAll(filepath.Dir(stored), 0o755))
must(os.WriteFile(stored, data, 0o644))
fmt.Printf("内容文件: %s (%d 字节, hash=%.12s…)\n", stored, len(data), hash)
// 4) 版本 + 版本文件
base := filepath.Base(exePath)
var v model.Version
database.DB.Where("application_id = ? AND version = ?", app.ID, "9.9.9").First(&v)
if v.ID == 0 {
v = model.Version{
ApplicationID: app.ID,
Version: "9.9.9",
FilePath: stored,
FileSize: int64(len(data)),
FileHash: hash,
EntryFile: base,
PublishStatus: "published",
PublishedAt: ptrTime(time.Now()),
}
must(database.DB.Create(&v).Error)
} else {
database.DB.Model(&v).Updates(map[string]interface{}{
"entry_file": base, "file_path": stored, "file_hash": hash,
})
}
var vf model.VersionFile
database.DB.Where("version_id = ? AND file_name = ?", v.ID, base).First(&vf)
if vf.ID == 0 {
vf = model.VersionFile{
VersionID: v.ID, FileName: base, FilePath: contentstore.ContentFileURL(hash),
FileSize: int64(len(data)), FileHash: hash, FileType: "program", IsRequired: true,
}
must(database.DB.Create(&vf).Error)
}
fmt.Printf("种子完成: app_id=%d app_key=%s version_id=%d entry=%s\n", app.ID, app.AppKey, v.ID, base)
}
func ptrTime(t time.Time) *time.Time { return &t }
func must(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
+141
View File
@@ -0,0 +1,141 @@
// vfyfix — 修正 .vfy 壳头里的两个 CRC(crcV / crcFile)
//
// 场景:先用 verify 的加壳链路打壳(signed=false,壳会校验整文件 CRC),再用别的工具
// (如 DogProtect)二次加壳。后者重写了 PE,壳一校验就退出。本工具在最后一步重算:
//
// .vfy 节内偏移 36 处:crcV(4 字节) = CRC32IEEE(节内 [0,36) + [44,size))
// .vfy 节内偏移 40 处:crcFile(4 字节)= CRC32IEEE(整文件,跳过这两个字段共 8 字节)
//
// 与 backend/internal/protect/protect.go 的算法逐字节一致(crcOff=36、crcSkip=crc32.IEEE)。
//
// 用法:
//
// vfyfix <file.exe> # 修正并写回
// vfyfix <file.exe> -dry-run # 只打印新旧值
//
// 注意:外层加壳时别开压缩(DogProtect 项目的 Options 里不要 cpPack=0x100),
// 否则 .vfy 节在文件里不是明文,壳运行时看到的内容与磁盘不一致,这里的重算就失去意义。
package main
import (
"debug/pe"
"encoding/binary"
"fmt"
"hash/crc32"
"os"
"strings"
)
const (
secName = ".vfy"
hdrSize = 48
crcOff = 36
)
func die(f string, a ...interface{}) {
fmt.Fprintf(os.Stderr, f+"\n", a...)
os.Exit(1)
}
func main() {
if len(os.Args) < 2 {
die("用法: vfyfix <file.exe> [-dry-run]")
}
path := os.Args[1]
dry := len(os.Args) > 2 && os.Args[2] == "-dry-run"
data, err := os.ReadFile(path)
if err != nil {
die("读取 %s 失败: %v", path, err)
}
f, err := pe.NewFile(strings.NewReader(string(data)))
if err != nil {
die("不是有效的 PE: %v", err)
}
defer f.Close()
var sec *pe.Section
for _, s := range f.Sections {
if strings.HasPrefix(s.Name, secName) {
sec = s
}
}
if sec == nil {
die("%s 里没有 %s 节(不是 verify 壳产物)", path, secName)
}
off := int(sec.Offset)
rawSize := int(sec.VirtualSize) // crcV 的覆盖长度 = 生成时的 len(sectionData)
if rawSize <= 0 || off+rawSize > len(data) {
rawSize = int(sec.Size) // 兜底:VirtualSize 异常时用原始大小减对齐填充
}
if off <= 0 || off+rawSize > len(data) || rawSize < hdrSize {
die("节区间异常: off=%d raw=%d file=%d", off, rawSize, len(data))
}
if string(data[off:off+4]) != "VFY4" {
die("壳头 magic 不是 VFY4(实际 %q)", data[off:off+4])
}
flags := binary.LittleEndian.Uint32(data[off+32:])
oldV := binary.LittleEndian.Uint32(data[off+crcOff:])
oldF := binary.LittleEndian.Uint32(data[off+crcOff+4:])
fmt.Printf("%s\n .vfy 文件偏移=0x%x 原始大小=%d flags=0x%x(bit1=%d)\n", path, off, rawSize, flags, (flags>>1)&1)
fmt.Printf(" 旧: crcV=%08x crcFile=%08x\n", oldV, oldF)
// ---- 重算 crcV:节内跳过 36..44 ----
h1 := crc32.NewIEEE()
h1.Write(data[off : off+crcOff])
h1.Write(data[off+crcOff+8 : off+rawSize])
newV := h1.Sum32()
// ---- 重算 crcFile:整文件跳过这两个字段 ----
skipAt := off + crcOff
copyForCRC := make([]byte, 0, len(data))
copyForCRC = append(copyForCRC, data[:skipAt]...)
copyForCRC = append(copyForCRC, data[skipAt+8:]...)
newF := crc32.ChecksumIEEE(copyForCRC)
fmt.Printf(" 新: crcV=%08x crcFile=%08x\n", newV, newF)
if newV == oldV && newF == oldF {
fmt.Println(" 已经是正确值,无需修改")
return
}
if dry {
fmt.Println(" -dry-run:未写入")
return
}
binary.LittleEndian.PutUint32(data[skipAt:], newV)
binary.LittleEndian.PutUint32(data[skipAt+4:], newF)
// ---- 顺手重算 PE 校验和(壳不查,但 Windows 工具链会看)----
peOff := int(binary.LittleEndian.Uint32(data[0x3c:0x40])) + 4 + 20
ckOff := peOff + 64
if ckOff+4 <= len(data) {
binary.LittleEndian.PutUint32(data[ckOff:], 0)
binary.LittleEndian.PutUint32(data[ckOff:], peChecksum(data))
}
if err := os.WriteFile(path, data, 0o644); err != nil {
die("写回失败: %v", err)
}
fmt.Println(" 已写回")
}
// peChecksum 与 protect.go 里的实现一致
func peChecksum(data []byte) uint32 {
var sum uint64
n := len(data)
i := 0
for ; i+1 < n; i += 2 {
sum += uint64(binary.LittleEndian.Uint16(data[i:]))
sum = (sum & 0xffff) + (sum >> 16)
}
if i < n {
sum += uint64(data[i])
sum = (sum & 0xffff) + (sum >> 16)
}
sum = (sum & 0xffff) + (sum >> 16)
return uint32(sum)
}
+5
View File
@@ -15,6 +15,7 @@ require (
golang.org/x/text v0.20.0
gorm.io/driver/mysql v1.5.1
gorm.io/gorm v1.30.0
software.sslmate.com/src/go-pkcs12 v0.4.0
)
require (
@@ -73,3 +74,7 @@ require (
modernc.org/memory v1.7.2 // indirect
modernc.org/sqlite v1.28.0 // indirect
)
// 本地改造版:放宽 Windows 导出 pfx 里的私有属性(1.3.6.1.4.1.311.x),
// 否则带这些属性的 pfx 会直接解析失败。
replace software.sslmate.com/src/go-pkcs12 => ./third_party/go-pkcs12
+99 -85
View File
@@ -9,7 +9,6 @@ package database
import (
"context"
"database/sql"
"fmt"
"log"
"os"
@@ -158,33 +157,12 @@ func initAutoDetect() {
}
func runMigrations() {
var columns []struct {
CID int
Name string
Type string
NotNull int
DefaultVal sql.NullString
PK int
}
DB.Raw("PRAGMA table_info(applications)").Scan(&columns)
log.Println("Applications table columns:")
for _, col := range columns {
log.Printf(" - %s (%s)\n", col.Name, col.Type)
}
var appUserColumns []struct {
CID int
Name string
Type string
NotNull int
DefaultVal sql.NullString
PK int
}
DB.Raw("PRAGMA table_info(app_users)").Scan(&appUserColumns)
log.Println("AppUsers table columns:")
for _, col := range appUserColumns {
log.Printf(" - %s (%s)\n", col.Name, col.Type)
}
// 先把历史唯一索引名对齐到 GORM 的约定,再跑迁移,避免每次启动都去 DROP 一个不存在的约束
ensureDeviceSessionUniqueIndexName()
// cert_blacklists 的指纹唯一索引在 MySQL 里会按列名建成 `fingerprint`,
// GORM 期望的名字是 uni_cert_blacklists_fingerprint,AutoMigrate 会尝试
// DROP 索引再建(Error 1091)——迁移前先把名字对齐,后续不再报错。
ensureCertBlacklistIndexName()
// 自动迁移数据库表:逐表执行,单表失败不影响其它表建表
models := []interface{}{
@@ -241,6 +219,9 @@ func runMigrations() {
&model.EmailTemplate{},
&model.VersionFile{},
&model.CloudVariableRecord{},
&model.ProtectTask{},
&model.SignProfile{},
&model.CertBlacklist{},
}
for _, m := range models {
var err error
@@ -254,6 +235,11 @@ func runMigrations() {
log.Printf("Failed to migrate %T: %v\n", m, err)
}
}
// 修正历史列类型:模型里 user_devices.device_id 是 varchar(100)(设备指纹),
// 但早期 MySQL 里建成了 bigint,AutoMigrate 不会改已有列类型,
// 导致心跳写设备时 Error 1265 Data truncated,设备表永远是空的。
fixDeviceIDColumnType()
// 迁移后复核:仍有表不存在时明确打出来,避免后续写库时报 1146 无从排查
for _, m := range models {
if !DB.Migrator().HasTable(m) {
@@ -261,20 +247,34 @@ func runMigrations() {
}
}
// 手动迁移:检查并添加 risk_control_rules 表的 user_id 列
var riskControlColumns []struct {
Name string
}
DB.Raw("PRAGMA table_info(risk_control_rules)").Scan(&riskControlColumns)
hasUserID := false
for _, col := range riskControlColumns {
if col.Name == "user_id" {
hasUserID = true
break
// 主体化改造回填:老用户的 display_name 为空就补成用户名,
// 否则后台「主体标识」列会显示空白,客服分不清是谁。
if hasColumn("app_users", "display_name") {
if err := DB.Exec("UPDATE app_users SET display_name = username WHERE (display_name IS NULL OR display_name = '') AND deleted_at IS NULL").Error; err != nil {
log.Printf("[MIGRATE] 回填 app_users.display_name 失败: %v", err)
}
}
if !hasUserID {
log.Println("Adding user_id column to risk_control_rules table...")
// subject_type 同理:存量账号全部是 account
if hasColumn("app_users", "subject_type") {
if err := DB.Exec("UPDATE app_users SET subject_type = 'account' WHERE subject_type IS NULL OR subject_type = ''").Error; err != nil {
log.Printf("[MIGRATE] 回填 app_users.subject_type 失败: %v", err)
}
}
// 卡密用途:存量卡一律是充值卡
if hasColumn("cards", "purpose") {
if err := DB.Exec("UPDATE cards SET purpose = 'recharge' WHERE purpose IS NULL OR purpose = ''").Error; err != nil {
log.Printf("[MIGRATE] 回填 cards.purpose 失败: %v", err)
}
}
// 应用登录方式:存量应用都按账号密码登录
if hasColumn("applications", "login_mode") {
if err := DB.Exec("UPDATE applications SET login_mode = 'account' WHERE login_mode IS NULL OR login_mode = ''").Error; err != nil {
log.Printf("[MIGRATE] 回填 applications.login_mode 失败: %v", err)
}
}
// risk_control_rules.user_id:缺失才加(hasColumn 内部按方言取列信息)
if !hasColumn("risk_control_rules", "user_id") {
if err := DB.Exec("ALTER TABLE risk_control_rules ADD COLUMN user_id INTEGER").Error; err != nil {
log.Println("Failed to add user_id column:", err.Error())
} else {
@@ -282,46 +282,10 @@ func runMigrations() {
}
}
// 修复 application_id 列的 NOT NULL 约束(SQLite需要重建表)
var riskControlTableInfo []struct {
CID int
Name string
Type string
NotNull int
DefaultVal sql.NullString
PK int
}
DB.Raw("PRAGMA table_info(risk_control_rules)").Scan(&riskControlTableInfo)
for _, col := range riskControlTableInfo {
if col.Name == "application_id" && col.NotNull == 1 {
log.Println("Fixing application_id NOT NULL constraint...")
// 创建临时表
DB.Exec(`CREATE TABLE risk_control_rules_new (
id INTEGER PRIMARY KEY,
user_id INTEGER,
application_id INTEGER,
type TEXT NOT NULL,
value TEXT NOT NULL,
reason TEXT,
status TEXT DEFAULT 'active',
expires_at DATETIME,
created_at DATETIME,
updated_at DATETIME,
deleted_at DATETIME
)`)
// 复制数据
DB.Exec(`INSERT INTO risk_control_rules_new SELECT * FROM risk_control_rules`)
// 删除旧表
DB.Exec(`DROP TABLE risk_control_rules`)
// 重命名新表
DB.Exec(`ALTER TABLE risk_control_rules_new RENAME TO risk_control_rules`)
// 重建索引
DB.Exec(`CREATE INDEX IF NOT EXISTS idx_risk_control_rules_user_id ON risk_control_rules(user_id)`)
DB.Exec(`CREATE INDEX IF NOT EXISTS idx_risk_control_rules_application_id ON risk_control_rules(application_id)`)
DB.Exec(`CREATE INDEX IF NOT EXISTS idx_risk_control_rules_deleted_at ON risk_control_rules(deleted_at)`)
log.Println("application_id NOT NULL constraint fixed")
break
}
// risk_control_rules.application_id 历史上被建成了 NOT NULL,模型里它是可空指针
// (为空表示全局规则)。MySQL 需要显式放开,sqlite 交给 AutoMigrate。
if err := relaxNotNull("risk_control_rules", "application_id", "INTEGER NULL"); err != nil {
log.Printf("[MIGRATE] 修正 risk_control_rules.application_id 可空性失败: %v", err)
}
// 手动迁移:检查并添加 packages 表的 currency 列
@@ -423,12 +387,12 @@ func initData() {
func initDocData() {
var categoryCount int64
DB.Model(&model.DocCategory{}).Count(&categoryCount)
if categoryCount > 0 {
log.Println("Document data already exists, skipping initialization")
return
}
log.Println("Initializing document data...")
categories := []model.DocCategory{
@@ -465,7 +429,7 @@ func initDocData() {
TitleEn: "User Registration",
Slug: "api-register",
Content: "# 用户注册\n\n### 接口地址\n```\nPOST /api/v1/app/:appKey/register\n```\n\n### 请求参数\n| 参数名 | 类型 | 必填 | 说明 |\n|--------|------|------|------|\n| username | string | 是 | 用户名 |\n| password | string | 是 | 密码 |\n| device_id | string | 是 | 设备指纹,设备唯一标识 |\n| device_name | string | 否 | 设备名称,如\"我的电脑\",不传则使用device_id |\n| email | string | 条件必填 | 邮箱地址,启用邮箱验证时必填 |\n| email_code | string | 条件必填 | 邮箱验证码,启用强制邮箱验证时必填 |\n| device_type | string | 否 | 设备类型:android/ios/windows/mac/linux/web,不传则自动识别 |\n| instance_id | string | 否 | 实例ID,用于多开识别,不传则使用device_id |\n\n### 请求示例\n```json\n{\n \"username\": \"user123\",\n \"password\": \"password123\",\n \"device_id\": \"abc123def456\",\n \"device_name\": \"我的电脑\",\n \"email\": \"user@example.com\",\n \"email_code\": \"123456\",\n \"device_type\": \"windows\"\n}\n```\n\n### 响应示例\n```json\n{\n \"code\": 200,\n \"message\": \"注册成功\",\n \"data\": {\n \"user_id\": 123\n }\n}\n```\n\n### 说明\n- device_id 是设备指纹,用于唯一标识设备\n- device_name 是设备的友好名称,用于显示\n- device_type 不传时,系统会根据 User-Agent 自动识别\n- 若应用启用了强制邮箱验证,则 email 和 email_code 为必填参数\n\n### 错误响应\n```json\n{\n \"code\": 400,\n \"message\": \"用户名已存在\"\n}\n```\n\n### 邮箱验证错误\n```json\n{\n \"code\": 400,\n \"message\": \"验证码错误或已过期\"\n}\n```",
ContentEn: "# User Registration\n\n### Endpoint\n```\nPOST /api/v1/app/:appKey/register\n```\n\n### Request Parameters\n| Parameter | Type | Required | Description |\n|--------|------|------|------|\n| username | string | Yes | Username |\n| password | string | Yes | Password |\n| device_id | string | Yes | Device fingerprint, unique device identifier |\n| device_name | string | No | Device name, e.g. \"My Computer\", defaults to device_id |\n| email | string | Conditional | Email address, required when email verification is enabled |\n| email_code | string | Conditional | Email verification code, required when mandatory email verification is enabled |\n| device_type | string | No | Device type: android/ios/windows/mac/linux/web, auto-detected if not provided |\n| instance_id | string | No | Instance ID for multi-instance detection, defaults to device_id |\n\n### Request Example\n```json\n{\n \"username\": \"user123\",\n \"password\": \"password123\",\n \"device_id\": \"abc123def456\",\n \"device_name\": \"My Computer\",\n \"email\": \"user@example.com\",\n \"email_code\": \"123456\",\n \"device_type\": \"windows\"\n}\n```\n\n### Response Example\n```json\n{\n \"code\": 200,\n \"message\": \"Registration successful\",\n \"data\": {\n \"user_id\": 123\n }\n}\n```\n\n### Notes\n- device_id is the device fingerprint used to uniquely identify the device\n- device_name is a friendly name for the device display\n- device_type is auto-detected from User-Agent if not provided\n- If mandatory email verification is enabled, email and email_code are required\n\n### Error Response\n```json\n{\n \"code\": 400,\n \"message\": \"Username already exists\"\n}\n```\n\n### Email Verification Error\n```json\n{\n \"code\": 400,\n \"message\": \"Invalid or expired verification code\"\n}\n```",
ContentEn: "# User Registration\n\n### Endpoint\n```\nPOST /api/v1/app/:appKey/register\n```\n\n### Request Parameters\n| Parameter | Type | Required | Description |\n|--------|------|------|------|\n| username | string | Yes | Username |\n| password | string | Yes | Password |\n| device_id | string | Yes | Device fingerprint, unique device identifier |\n| device_name | string | No | Device name, e.g. \"My Computer\", defaults to device_id |\n| email | string | Conditional | Email address, required when email verification is enabled |\n| email_code | string | Conditional | Email verification code, required when mandatory email verification is enabled |\n| device_type | string | No | Device type: android/ios/windows/mac/linux/web, auto-detected if not provided |\n| instance_id | string | No | Instance ID for multi-instance detection, defaults to device_id |\n\n### Request Example\n```json\n{\n \"username\": \"user123\",\n \"password\": \"password123\",\n \"device_id\": \"abc123def456\",\n \"device_name\": \"My Computer\",\n \"email\": \"user@example.com\",\n \"email_code\": \"123456\",\n \"device_type\": \"windows\"\n}\n```\n\n### Response Example\n```json\n{\n \"code\": 200,\n \"message\": \"Registration successful\",\n \"data\": {\n \"user_id\": 123\n }\n}\n```\n\n### Notes\n- device_id is the device fingerprint used to uniquely identify the device\n- device_name is a friendly name for the device display\n- device_type is auto-detected from User-Agent if not provided\n- If mandatory email verification is enabled, email and email_code are required\n\n### Error Response\n```json\n{\n \"code\": 400,\n \"message\": \"Username already exists\"\n}\n```\n\n### Email Verification Error\n```json\n{\n \"code\": 400,\n \"message\": \"Invalid or expired verification code\"\n}\n```",
Summary: "用户注册说明",
SummaryEn: "User registration instructions",
Sort: 1,
@@ -476,7 +440,7 @@ func initDocData() {
TitleEn: "Send Email Verification Code",
Slug: "api-send-email-code",
Content: "# 发送邮箱验证码\n\n### 接口地址\n```\nPOST /api/v1/app/:appKey/send-email-code\n```\n\n### 请求参数\n| 参数名 | 类型 | 必填 | 说明 |\n|--------|------|------|------|\n| email | string | 是 | 邮箱地址 |\n| purpose | string | 否 | 用途:register(注册)、reset_password(重置密码)、change_email(更换邮箱),默认register |\n\n### 请求示例\n```json\n{\n \"email\": \"user@example.com\",\n \"purpose\": \"register\"\n}\n```\n\n### 响应示例\n```json\n{\n \"code\": 200,\n \"message\": \"success\",\n \"data\": {\n \"message\": \"验证码已发送\"\n }\n}\n```\n\n### 说明\n- 验证码有效期为15分钟\n- 若应用未启用邮箱验证,会返回错误\n\n### 错误响应\n```json\n{\n \"code\": 400,\n \"message\": \"该应用未启用邮箱验证\"\n}\n```",
ContentEn: "# Send Email Verification Code\n\n### Endpoint\n```\nPOST /api/v1/app/:appKey/send-email-code\n```\n\n### Request Parameters\n| Parameter | Type | Required | Description |\n|--------|------|------|------|\n| email | string | Yes | Email address |\n| purpose | string | No | Purpose: register, reset_password, change_email, defaults to register |\n\n### Request Example\n```json\n{\n \"email\": \"user@example.com\",\n \"purpose\": \"register\"\n}\n```\n\n### Response Example\n```json\n{\n \"code\": 200,\n \"message\": \"success\",\n \"data\": {\n \"message\": \"Verification code sent\"\n }\n}\n```\n\n### Notes\n- Verification code is valid for 15 minutes\n- Returns error if email verification is not enabled for the application\n\n### Error Response\n```json\n{\n \"code\": 400,\n \"message\": \"Email verification is not enabled for this application\"\n}\n```",
ContentEn: "# Send Email Verification Code\n\n### Endpoint\n```\nPOST /api/v1/app/:appKey/send-email-code\n```\n\n### Request Parameters\n| Parameter | Type | Required | Description |\n|--------|------|------|------|\n| email | string | Yes | Email address |\n| purpose | string | No | Purpose: register, reset_password, change_email, defaults to register |\n\n### Request Example\n```json\n{\n \"email\": \"user@example.com\",\n \"purpose\": \"register\"\n}\n```\n\n### Response Example\n```json\n{\n \"code\": 200,\n \"message\": \"success\",\n \"data\": {\n \"message\": \"Verification code sent\"\n }\n}\n```\n\n### Notes\n- Verification code is valid for 15 minutes\n- Returns error if email verification is not enabled for the application\n\n### Error Response\n```json\n{\n \"code\": 400,\n \"message\": \"Email verification is not enabled for this application\"\n}\n```",
Summary: "发送邮箱验证码说明",
SummaryEn: "Send email verification code instructions",
Sort: 2,
@@ -487,7 +451,7 @@ func initDocData() {
TitleEn: "User Login",
Slug: "api-login",
Content: "# 用户登录\n\n### 接口地址\n```\nPOST /api/v1/app/:appKey/login\n```\n\n### 请求参数\n| 参数名 | 类型 | 必填 | 说明 |\n|--------|------|------|------|\n| username | string | 是 | 用户名 |\n| password | string | 是 | 密码 |\n| device_id | string | 是 | 设备指纹,设备唯一标识 |\n| device_name | string | 否 | 设备名称,如\"我的电脑\",不传则使用device_id |\n| device_type | string | 否 | 设备类型:android/ios/windows/mac/linux/web,不传则自动识别 |\n| instance_id | string | 否 | 实例ID,用于多开识别,不传则使用device_id |\n\n### 请求示例\n```json\n{\n \"username\": \"user123\",\n \"password\": \"password123\",\n \"device_id\": \"abc123def456\",\n \"device_name\": \"我的电脑\",\n \"device_type\": \"windows\"\n}\n```\n\n### 响应示例\n```json\n{\n \"code\": 200,\n \"message\": \"登录成功\",\n \"data\": {\n \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\",\n \"user_id\": 123\n }\n}\n```\n\n### 响应字段说明\n| 字段名 | 类型 | 说明 |\n|--------|------|------|\n| token | string | JWT令牌,用于后续认证 |\n| user_id | number | 用户ID |\n\n### 说明\n- device_id 是设备指纹,用于唯一标识设备\n- device_name 是设备的友好名称,用于显示\n- device_type 不传时,系统会根据 User-Agent 自动识别\n- 若设备绑定数量已达上限,会返回错误并显示已绑定设备列表\n\n### 错误响应\n```json\n{\n \"code\": 401,\n \"message\": \"用户名或密码错误\"\n}\n```\n\n### 设备上限错误响应\n```json\n{\n \"code\": 403,\n \"message\": \"设备绑定数量已达上限,请解绑后再试\",\n \"data\": {\n \"error_code\": \"DEVICE_LIMIT_EXCEEDED\",\n \"max_devices\": 3,\n \"device_count\": 3,\n \"devices\": [\n {\n \"id\": 1,\n \"device_id\": \"abc123def456\",\n \"device_name\": \"我的电脑\",\n \"device_type\": \"windows\",\n \"online_count\": 1,\n \"created_at\": \"2024-03-04T12:00:00Z\"\n }\n ]\n }\n}\n```",
ContentEn: "# User Login\n\n### Endpoint\n```\nPOST /api/v1/app/:appKey/login\n```\n\n### Request Parameters\n| Parameter | Type | Required | Description |\n|--------|------|------|------|\n| username | string | Yes | Username |\n| password | string | Yes | Password |\n| device_id | string | Yes | Device fingerprint, unique device identifier |\n| device_name | string | No | Device name, e.g. \"My Computer\", defaults to device_id |\n| device_type | string | No | Device type: android/ios/windows/mac/linux/web, auto-detected if not provided |\n| instance_id | string | No | Instance ID for multi-instance detection, defaults to device_id |\n\n### Request Example\n```json\n{\n \"username\": \"user123\",\n \"password\": \"password123\",\n \"device_id\": \"abc123def456\",\n \"device_name\": \"My Computer\",\n \"device_type\": \"windows\"\n}\n```\n\n### Response Example\n```json\n{\n \"code\": 200,\n \"message\": \"Login successful\",\n \"data\": {\n \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\",\n \"user_id\": 123\n }\n}\n```\n\n### Response Fields\n| Field | Type | Description |\n|--------|------|------|\n| token | string | JWT token for subsequent authentication |\n| user_id | number | User ID |\n\n### Notes\n- device_id is the device fingerprint used to uniquely identify the device\n- device_name is a friendly name for the device display\n- device_type is auto-detected from User-Agent if not provided\n- Returns error with bound device list if device limit is exceeded\n\n### Error Response\n```json\n{\n \"code\": 401,\n \"message\": \"Invalid username or password\"\n}\n```\n\n### Device Limit Exceeded Response\n```json\n{\n \"code\": 403,\n \"message\": \"Device limit exceeded, please unbind a device first\",\n \"data\": {\n \"error_code\": \"DEVICE_LIMIT_EXCEEDED\",\n \"max_devices\": 3,\n \"device_count\": 3,\n \"devices\": [\n {\n \"id\": 1,\n \"device_id\": \"abc123def456\",\n \"device_name\": \"My Computer\",\n \"device_type\": \"windows\",\n \"online_count\": 1,\n \"created_at\": \"2024-03-04T12:00:00Z\"\n }\n ]\n }\n}\n```",
ContentEn: "# User Login\n\n### Endpoint\n```\nPOST /api/v1/app/:appKey/login\n```\n\n### Request Parameters\n| Parameter | Type | Required | Description |\n|--------|------|------|------|\n| username | string | Yes | Username |\n| password | string | Yes | Password |\n| device_id | string | Yes | Device fingerprint, unique device identifier |\n| device_name | string | No | Device name, e.g. \"My Computer\", defaults to device_id |\n| device_type | string | No | Device type: android/ios/windows/mac/linux/web, auto-detected if not provided |\n| instance_id | string | No | Instance ID for multi-instance detection, defaults to device_id |\n\n### Request Example\n```json\n{\n \"username\": \"user123\",\n \"password\": \"password123\",\n \"device_id\": \"abc123def456\",\n \"device_name\": \"My Computer\",\n \"device_type\": \"windows\"\n}\n```\n\n### Response Example\n```json\n{\n \"code\": 200,\n \"message\": \"Login successful\",\n \"data\": {\n \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\",\n \"user_id\": 123\n }\n}\n```\n\n### Response Fields\n| Field | Type | Description |\n|--------|------|------|\n| token | string | JWT token for subsequent authentication |\n| user_id | number | User ID |\n\n### Notes\n- device_id is the device fingerprint used to uniquely identify the device\n- device_name is a friendly name for the device display\n- device_type is auto-detected from User-Agent if not provided\n- Returns error with bound device list if device limit is exceeded\n\n### Error Response\n```json\n{\n \"code\": 401,\n \"message\": \"Invalid username or password\"\n}\n```\n\n### Device Limit Exceeded Response\n```json\n{\n \"code\": 403,\n \"message\": \"Device limit exceeded, please unbind a device first\",\n \"data\": {\n \"error_code\": \"DEVICE_LIMIT_EXCEEDED\",\n \"max_devices\": 3,\n \"device_count\": 3,\n \"devices\": [\n {\n \"id\": 1,\n \"device_id\": \"abc123def456\",\n \"device_name\": \"My Computer\",\n \"device_type\": \"windows\",\n \"online_count\": 1,\n \"created_at\": \"2024-03-04T12:00:00Z\"\n }\n ]\n }\n}\n```",
Summary: "用户登录说明",
SummaryEn: "User login instructions",
Sort: 3,
@@ -778,3 +742,53 @@ func initTicketData() {
log.Println("Ticket data initialized successfully")
}
}
// ensureDeviceSessionUniqueIndexName 把 device_sessions.instance_id 上的唯一索引
// 从历史名 idx_device_instance 对齐到 GORM 的约定名。
//
// 背景:模型用 `uniqueIndex:` 标签时,MySQL 驱动仍会把「列上有唯一索引」报成
// ColumnType.Unique()==true,而 field.Unique 为 false,于是 GORM 的 MigrateColumnUnique
// 每次启动都判定「库里有约束、模型没要求」,去 DROP 一个按约定算出来的
// uni_device_sessions_instance_id —— 这个名字在库里从来不存在,MySQL 报 1091。
// 模型已改用 `unique`(约定名即 uni_device_sessions_instance_id),这里把历史库的
// 索引名改过来,两边一致后 AutoMigrate 完全无操作。
// ensureCertBlacklistIndexName 把 cert_blacklists.fingerprint 的唯一索引
// 改成 GORM 期望的名字,避免每次启动 AutoMigrate 报 Error 1091。
func ensureCertBlacklistIndexName() {
if !DB.Migrator().HasTable("cert_blacklists") {
return
}
renamed, err := renameIndexTo("cert_blacklists", "fingerprint",
"uni_cert_blacklists_fingerprint", "fingerprint")
if err != nil {
log.Printf("[MIGRATE] cert_blacklists 唯一索引改名失败: %v", err)
return
}
if renamed {
log.Printf("[MIGRATE] cert_blacklists 唯一索引已改名为 uni_cert_blacklists_fingerprint")
}
}
func ensureDeviceSessionUniqueIndexName() {
if !DB.Migrator().HasTable("device_sessions") {
return
}
renamed, err := renameIndexTo("device_sessions", "idx_device_instance", "uni_device_sessions_instance_id", "instance_id")
if err != nil {
log.Printf("[MIGRATE] device_sessions 唯一索引改名失败: %v", err)
return
}
if renamed {
log.Printf("[MIGRATE] device_sessions 唯一索引已改名为 uni_device_sessions_instance_id")
}
}
// fixDeviceIDColumnType 确保 user_devices.device_id 是字符串类型。
//
// 早期 MySQL 里这列被建成了 bigint,AutoMigrate 不会改已有列类型,导致心跳写设备时
// Error 1265 Data truncated,设备表永远是空的。类型已正确时这里什么都不做。
func fixDeviceIDColumnType() {
if err := ensureColumnType("user_devices", "device_id", []string{"varchar", "char", "text"}, "VARCHAR(100) NULL"); err != nil {
log.Printf("[MIGRATE][ERROR] 修正 user_devices.device_id 类型失败: %v", err)
}
}
+148
View File
@@ -0,0 +1,148 @@
package database
import (
"fmt"
"log"
"strings"
"verification-platform-backend/internal/config"
)
// 方言层。
//
// 迁移代码里只该出现「做什么」,不该出现「sqlite 这么做、mysql 那么做」。
// 所有方言差异收敛在这个文件里:列信息读取、索引改名、改列类型/可空性。
// 之前这些分支散落在 runMigrations 里(四处 PRAGMA + 若干 if),
// 一旦某处漏了守卫,在 MySQL 上就会静默失败并产生误导性报错。
type columnInfo struct {
Name string
Type string
NotNull bool
}
func dialectName() string {
t := strings.ToLower(config.GetString("database.type"))
if t == "mysql" {
return "mysql"
}
return "sqlite"
}
// tableColumns 读取表的列信息
func tableColumns(table string) []columnInfo {
out := []columnInfo{}
if dialectName() == "mysql" {
var rows []struct {
ColumnName string
ColumnType string
IsNullable string
}
if err := DB.Raw(
"SELECT column_name AS column_name, column_type AS column_type, is_nullable AS is_nullable "+
"FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? "+
"ORDER BY ordinal_position", table).Scan(&rows).Error; err != nil {
log.Printf("[MIGRATE] 读取 %s 的列信息失败: %v", table, err)
return out
}
for _, r := range rows {
out = append(out, columnInfo{Name: r.ColumnName, Type: r.ColumnType, NotNull: strings.EqualFold(r.IsNullable, "NO")})
}
return out
}
var rows []struct {
Name string
Type string
NotNull int
}
if err := DB.Raw(fmt.Sprintf("PRAGMA table_info(%s)", table)).Scan(&rows).Error; err != nil {
log.Printf("[MIGRATE] 读取 %s 的列信息失败: %v", table, err)
return out
}
for _, r := range rows {
out = append(out, columnInfo{Name: r.Name, Type: r.Type, NotNull: r.NotNull == 1})
}
return out
}
// columnOf 取单列信息
func columnOf(table, column string) (columnInfo, bool) {
for _, c := range tableColumns(table) {
if c.Name == column {
return c, true
}
}
return columnInfo{}, false
}
// hasColumn 列是否存在
func hasColumn(table, column string) bool {
_, ok := columnOf(table, column)
return ok
}
// renameIndexTo 幂等地把索引起到目标名(唯一索引需要给出唯一列)。
// 返回是否真的改过名——调用方据此决定要不要打日志,避免每次启动都刷一行。
func renameIndexTo(table, from, to, uniqueOn string) (bool, error) {
if !DB.Migrator().HasIndex(table, from) {
return false, nil
}
if dialectName() == "mysql" {
if err := DB.Exec(fmt.Sprintf("ALTER TABLE %s RENAME INDEX %s TO %s", table, from, to)).Error; err != nil {
return false, err
}
return true, nil
}
// sqlite 不支持重命名索引,删了重建
if err := DB.Exec(fmt.Sprintf("DROP INDEX IF EXISTS %s", from)).Error; err != nil {
return false, err
}
if err := DB.Exec(fmt.Sprintf("CREATE UNIQUE INDEX IF NOT EXISTS %s ON %s(%s)", to, table, uniqueOn)).Error; err != nil {
return false, err
}
return true, nil
}
// ensureColumnType 确保列类型符合预期(只对能改类型的 MySQL 动手,sqlite 只做检查)
func ensureColumnType(table, column string, okPrefixes []string, mysqlDef string) error {
col, ok := columnOf(table, column)
if !ok {
return nil
}
lt := strings.ToLower(col.Type)
for _, p := range okPrefixes {
if strings.HasPrefix(lt, strings.ToLower(p)) {
return nil
}
}
if dialectName() != "mysql" {
log.Printf("[MIGRATE] %s.%s 类型是 %s(期望 %v),sqlite 无法在线改列类型,跳过", table, column, col.Type, okPrefixes)
return nil
}
if err := DB.Exec(fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s %s", table, column, mysqlDef)).Error; err != nil {
return err
}
log.Printf("[MIGRATE] %s.%s 已由 %s 改为 %s", table, column, col.Type, mysqlDef)
return nil
}
// relaxNotNull 把列改成可空。
//
// MySQL:直接 MODIFY。
// SQLite:不支持在线改 NOT NULL,但模型里该字段是可空指针时 GORM 的 AutoMigrate
// 会自行重建表,所以这里不需要重复一套重建逻辑——只要确认现状即可。
func relaxNotNull(table, column, mysqlDef string) error {
col, ok := columnOf(table, column)
if !ok || !col.NotNull {
return nil
}
if dialectName() != "mysql" {
log.Printf("[MIGRATE] %s.%s 仍是 NOT NULL(sqlite 由 AutoMigrate 重建表处理)", table, column)
return nil
}
if err := DB.Exec(fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s %s", table, column, mysqlDef)).Error; err != nil {
return err
}
log.Printf("[MIGRATE] %s.%s 已由 %s 改为可空", table, column, col.Type)
return nil
}
+269
View File
@@ -0,0 +1,269 @@
// Package doglic 签发/校验自签授权序列号(与 DogProtect 仓库 tools/dogkeygen、sdk/cpp/doglic.hpp 同一套格式)
//
// 序列号 = base64( (00 02 || 非零填充 || 00 || payload) ^ d mod n )
// payload = chunk..., 末尾 0xFF + sha1(前面全部字节) 前 4 字节倒序
//
// 密钥来自工程/授权文件里的 <LicenseManager Modulus=".." PrivateExp=".." PublicExp=".."/>(均为 base64 大端)。
package doglic
import (
"crypto/rand"
"crypto/sha1"
"encoding/base64"
"encoding/xml"
"fmt"
"math/big"
"os"
"strings"
"time"
)
// chunk 标记,与 runtime/licensing_manager.h 对齐
const (
ChunkVersion = 0x01
ChunkUserName = 0x02
ChunkEmail = 0x03
ChunkHWID = 0x04
ChunkExpDate = 0x05
ChunkRunningTime = 0x06
ChunkProductCode = 0x07
ChunkUserData = 0x08
ChunkMaxBuild = 0x09
ChunkEnd = 0xFF
)
// Keys 一套签名密钥
type Keys struct {
Modulus []byte // 大端
PublicExp []byte
PrivateExp []byte
ProductCode []byte // 可选,工程设置了 LockToKey 时要用
}
type licenseManagerXML struct {
LicenseManager struct {
Algorithm string `xml:"Algorithm,attr"`
Modulus string `xml:"Modulus,attr"`
PublicExp string `xml:"PublicExp,attr"`
PrivateExp string `xml:"PrivateExp,attr"`
ProductCode string `xml:"ProductCode,attr"`
} `xml:"LicenseManager"`
}
// LoadKeysFromFile 从 .dog / license.xml 里读密钥
func LoadKeysFromFile(path string) (*Keys, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var doc licenseManagerXML
if err := xml.Unmarshal(raw, &doc); err != nil {
return nil, fmt.Errorf("解析 %s 失败: %w", path, err)
}
lm := doc.LicenseManager
if lm.Modulus == "" || lm.PrivateExp == "" {
return nil, fmt.Errorf("%s 里没有 <LicenseManager Modulus/PrivateExp>", path)
}
dec := func(s string) ([]byte, error) { return base64.StdEncoding.DecodeString(strings.TrimSpace(s)) }
mod, err := dec(lm.Modulus)
if err != nil {
return nil, fmt.Errorf("Modulus base64: %w", err)
}
priv, err := dec(lm.PrivateExp)
if err != nil {
return nil, fmt.Errorf("PrivateExp base64: %w", err)
}
pub := []byte{0x01, 0x00, 0x01}
if lm.PublicExp != "" {
if v, err := dec(lm.PublicExp); err == nil && len(v) > 0 {
pub = v
}
}
var pc []byte
if lm.ProductCode != "" {
pc, _ = dec(lm.ProductCode)
}
return &Keys{Modulus: mod, PublicExp: pub, PrivateExp: priv, ProductCode: pc}, nil
}
// Request 签发参数
type Request struct {
UserName string
Email string
ExpDate time.Time // 零值 = 不限
MaxBuildDate time.Time
RunningTime int // 分钟,0 = 不限
HWID []byte // 绑机数据,nil = 不绑
UserData []byte // 首字节常作产品 ID
SerialVersion byte // 1 或 2,默认 1
}
// 日期编码:(年<<16)|(月<<8)|日
func encodeDate(t time.Time) uint32 {
if t.IsZero() {
return 0
}
return uint32(t.Year())<<16 | uint32(t.Month())<<8 | uint32(t.Day())
}
// Sign 生成序列号
func Sign(k *Keys, req Request) (string, error) {
n := new(big.Int).SetBytes(k.Modulus)
if n.Sign() == 0 {
return "", fmt.Errorf("modulus 为空")
}
modLen := len(k.Modulus)
payload := []byte{ChunkVersion, req.SerialVersion}
if payload[1] == 0 {
payload[1] = 1
}
if d := encodeDate(req.ExpDate); d != 0 {
payload = append(payload, ChunkExpDate, byte(d>>24), byte(d>>16), byte(d>>8), byte(d))
}
if d := encodeDate(req.MaxBuildDate); d != 0 {
payload = append(payload, ChunkMaxBuild, byte(d>>24), byte(d>>16), byte(d>>8), byte(d))
}
if req.RunningTime > 0 {
rt := req.RunningTime
if rt > 255 {
rt = 255
}
payload = append(payload, ChunkRunningTime, byte(rt))
}
pc := req.UserData
if len(k.ProductCode) == 8 {
payload = append(payload, ChunkProductCode)
payload = append(payload, k.ProductCode...)
}
if req.UserName != "" {
name := []byte(req.UserName)
if len(name) > 255 {
name = name[:255]
}
payload = append(payload, ChunkUserName, byte(len(name)))
payload = append(payload, name...)
}
if req.Email != "" {
mail := []byte(req.Email)
if len(mail) > 255 {
mail = mail[:255]
}
payload = append(payload, ChunkEmail, byte(len(mail)))
payload = append(payload, mail...)
}
if len(req.HWID) > 0 {
payload = append(payload, ChunkHWID, byte(len(req.HWID)))
payload = append(payload, req.HWID...)
}
if len(pc) > 0 {
payload = append(payload, ChunkUserData, byte(len(pc)))
payload = append(payload, pc...)
}
payload = append(payload, ChunkEnd)
sum := sha1.Sum(payload[:len(payload)-1])
payload = append(payload, sum[3], sum[2], sum[1], sum[0])
if len(payload)+11 > modLen {
return "", fmt.Errorf("payload 太长(%d),超过模长 %d", len(payload), modLen)
}
// PKCS#1 v1.5:00 02 || 非零填充 || 00 || payload
block := make([]byte, 0, modLen)
block = append(block, 0x00, 0x02)
padLen := modLen - len(payload) - 3
pad := make([]byte, padLen)
if _, err := rand.Read(pad); err != nil {
return "", err
}
for i := range pad {
pad[i] = pad[i]%255 + 1 // 非零
}
block = append(block, pad...)
block = append(block, 0x00)
block = append(block, payload...)
d := new(big.Int).SetBytes(k.PrivateExp)
m := new(big.Int).SetBytes(block)
sig := new(big.Int).Exp(m, d, n)
out := make([]byte, modLen)
sigBytes := sig.Bytes()
copy(out[modLen-len(sigBytes):], sigBytes)
return base64.StdEncoding.EncodeToString(out), nil
}
// Verify 用公钥校验(服务端自检/单测用;客户端同逻辑见 sdk/cpp/doglic.hpp)
func Verify(k *Keys, serial string) (bool, map[string]string, error) {
raw, err := base64.StdEncoding.DecodeString(serial)
if err != nil {
return false, nil, err
}
n := new(big.Int).SetBytes(k.Modulus)
e := new(big.Int).SetBytes(k.PublicExp)
m := new(big.Int).Exp(new(big.Int).SetBytes(raw), e, n)
block := make([]byte, len(k.Modulus))
mb := m.Bytes()
copy(block[len(block)-len(mb):], mb)
if len(block) < 3 || block[0] != 0x00 || block[1] != 0x02 {
return false, nil, fmt.Errorf("结构不对(不是 00 02 开头)")
}
pos := 2
for pos < len(block) && block[pos] != 0 {
pos++
}
if pos+1 >= len(block) {
return false, nil, fmt.Errorf("填充区没有 0x00 结束符")
}
pos++
p := block[pos:]
fields := map[string]string{}
i := 0
for i < len(p) {
tag := p[i]
switch tag {
case ChunkVersion:
fields["version"] = fmt.Sprintf("%d", p[i+1])
i += 2
case ChunkUserName, ChunkEmail:
n2 := int(p[i+1])
v := string(p[i+2 : i+2+n2])
if tag == ChunkUserName {
fields["user"] = v
} else {
fields["email"] = v
}
i += 2 + n2
case ChunkExpDate, ChunkMaxBuild:
d := uint32(p[i+1])<<24 | uint32(p[i+2])<<16 | uint32(p[i+3])<<8 | uint32(p[i+4])
key := "exp"
if tag == ChunkMaxBuild {
key = "maxbuild"
}
fields[key] = fmt.Sprintf("%04d-%02d-%02d", d>>16, (d>>8)&0xFF, d&0xFF)
i += 5
case ChunkRunningTime:
fields["running_time"] = fmt.Sprintf("%d", p[i+1])
i += 2
case ChunkHWID, ChunkUserData:
n2 := int(p[i+1])
fields[map[bool]string{true: "hwid", false: "userdata"}[tag == ChunkHWID]] = fmt.Sprintf("%x", p[i+2:i+2+n2])
i += 2 + n2
case ChunkProductCode:
fields["product_code"] = fmt.Sprintf("%x", p[i+1:i+9])
i += 9
case ChunkEnd:
sum := sha1.Sum(p[:i])
if p[i+1] != sum[3] || p[i+2] != sum[2] || p[i+3] != sum[1] || p[i+4] != sum[0] {
return false, fields, fmt.Errorf("校验和不匹配")
}
return true, fields, nil
default:
return false, fields, fmt.Errorf("未知 chunk 0x%02X", tag)
}
}
return false, fields, fmt.Errorf("缺少 END chunk")
}
+15 -15
View File
@@ -28,8 +28,8 @@ type Arch string
const (
ArchX86 Arch = "x86"
ArchX64 Arch = "x64"
ArchARM Arch = "arm"
ArchARM64 Arch = "arm64"
ArchARM Arch = "arm"
ArchARM64 Arch = "arm64"
ArchUniversal Arch = "universal"
)
@@ -58,13 +58,13 @@ type InjectResult struct {
// InjectService 注入服务
type InjectService struct {
ApktoolPath string
KeystorePath string
KeystorePass string
ApktoolPath string
KeystorePath string
KeystorePass string
KeystoreAlias string
KeyPass string
KeyPass string
ApksignerPath string
WorkDir string
WorkDir string
}
// NewInjectService 创建注入服务
@@ -76,12 +76,12 @@ func NewInjectService(workDir string) *InjectService {
}
return &InjectService{
WorkDir: absWorkDir,
ApktoolPath: getEnvOrDefault("APKTOOL_PATH", "apktool"),
KeystorePath: getEnvOrDefault("KEYSTORE_PATH", ""),
KeystorePass: getEnvOrDefault("KEYSTORE_PASS", "123456"),
WorkDir: absWorkDir,
ApktoolPath: getEnvOrDefault("APKTOOL_PATH", "apktool"),
KeystorePath: getEnvOrDefault("KEYSTORE_PATH", ""),
KeystorePass: getEnvOrDefault("KEYSTORE_PASS", "123456"),
KeystoreAlias: getEnvOrDefault("KEYSTORE_ALIAS", "mykey"),
KeyPass: getEnvOrDefault("KEY_PASS", "123456"),
KeyPass: getEnvOrDefault("KEY_PASS", "123456"),
ApksignerPath: getEnvOrDefault("APKSIGNER_PATH", "apksigner"),
}
}
@@ -309,9 +309,9 @@ func (s *InjectService) configureAndroid(decompileDir string, config InjectConfi
// 替换配置参数
replacements := map[string]string{
"[OpenClassName]": config.AppName,
"\"https://example.com\"": fmt.Sprintf("\"%s\"", config.VerifyURL),
"[AppKey]": config.AppKey,
"[OpenClassName]": config.AppName,
"\"https://example.com\"": fmt.Sprintf("\"%s\"", config.VerifyURL),
"[AppKey]": config.AppKey,
}
for old, new := range replacements {
+3 -3
View File
@@ -35,10 +35,10 @@ func AppCrypto() gin.HandlerFunc {
cryptoManager := crypto.NewCryptoManager(encryptType, app.EncryptKey)
shouldEncrypt := encryptType != crypto.EncryptTypeNone
fmt.Printf("[AppCrypto] AppKey: %s, EncryptType: %s, EncryptKey: %s, ShouldEncrypt: %v\n",
fmt.Printf("[AppCrypto] AppKey: %s, EncryptType: %s, EncryptKey: %s, ShouldEncrypt: %v\n",
appKey, app.EncryptType, app.EncryptKey, shouldEncrypt)
c.Set("should_encrypt_response", shouldEncrypt)
c.Set("crypto_manager", cryptoManager)
+261 -172
View File
@@ -27,11 +27,11 @@ type User struct {
ApiCallsResetAt *time.Time `json:"api_calls_reset_at"`
ApiToken string `gorm:"size:64" json:"api_token"`
ParentAgentID *uint `gorm:"index" json:"parent_agent_id"`
CanCreateAgent bool `gorm:"default:false" json:"can_create_agent"`
CanViewCloudData bool `gorm:"default:false" json:"can_view_cloud_data"`
Balance float64 `gorm:"default:0" json:"balance"`
TotalConsumption float64 `gorm:"default:0" json:"total_consumption"`
ParentAgentID *uint `gorm:"index" json:"parent_agent_id"`
CanCreateAgent bool `gorm:"default:false" json:"can_create_agent"`
CanViewCloudData bool `gorm:"default:false" json:"can_view_cloud_data"`
Balance float64 `gorm:"default:0" json:"balance"`
TotalConsumption float64 `gorm:"default:0" json:"total_consumption"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
@@ -48,6 +48,9 @@ type User struct {
type AppUser struct {
ID uint `gorm:"primaryKey" json:"id"`
Username string `gorm:"uniqueIndex:idx_app_user;size:50" json:"username"`
DisplayName string `gorm:"size:100" json:"display_name"` // 客服看到的主体标识:账号=用户名,卡密=卡密
SubjectType string `gorm:"size:20;default:account;index" json:"subject_type"` // account / card
Remark string `gorm:"size:255" json:"remark"` // 运营备注
Email string `gorm:"size:100" json:"email"`
Password string `gorm:"size:255" json:"-"`
DeviceID string `gorm:"size:100" json:"device_id"`
@@ -113,21 +116,21 @@ type SmsConfig struct {
}
type StorageConfig struct {
ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:100;not null" json:"name"`
Type string `gorm:"size:20;not null" json:"type"`
Endpoint string `gorm:"size:255" json:"endpoint"`
Bucket string `gorm:"size:100" json:"bucket"`
AccessKey string `gorm:"size:255" json:"access_key"`
SecretKey string `gorm:"size:255" json:"secret_key"`
Region string `gorm:"size:50" json:"region"`
PathPrefix string `gorm:"size:255" json:"path_prefix"`
IsDefault bool `gorm:"default:false" json:"is_default"`
Status string `gorm:"size:20;default:active" json:"status"`
Remark string `gorm:"size:500" json:"remark"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:100;not null" json:"name"`
Type string `gorm:"size:20;not null" json:"type"`
Endpoint string `gorm:"size:255" json:"endpoint"`
Bucket string `gorm:"size:100" json:"bucket"`
AccessKey string `gorm:"size:255" json:"access_key"`
SecretKey string `gorm:"size:255" json:"secret_key"`
Region string `gorm:"size:50" json:"region"`
PathPrefix string `gorm:"size:255" json:"path_prefix"`
IsDefault bool `gorm:"default:false" json:"is_default"`
Status string `gorm:"size:20;default:active" json:"status"`
Remark string `gorm:"size:500" json:"remark"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
// DynamicCode 动态代码模型
@@ -163,97 +166,103 @@ type UserLevel struct {
// Application 应用模型
type Application struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `json:"user_id"`
Name string `gorm:"size:100" json:"name"`
Description string `gorm:"type:text" json:"description"`
IconURL string `gorm:"size:255" json:"icon_url"`
AppKey string `gorm:"unique;size:50" json:"app_key"`
BillingType string `gorm:"size:20" json:"billing_type"`
LoginPolicy string `gorm:"size:20;default:loose" json:"login_policy"`
EncryptType string `gorm:"size:20" json:"encrypt_type"`
EncryptKey string `gorm:"size:255" json:"encrypt_key"`
BindType string `gorm:"size:20" json:"bind_type"`
MaxDevices int `gorm:"default:1" json:"max_devices"`
ChangeLimit int `gorm:"default:3" json:"change_limit"`
ChangeInterval int `gorm:"default:7" json:"change_interval"`
ChangeExceedAction string `gorm:"size:20;default:deny" json:"change_exceed_action"`
ChangeDeductAmount float64 `gorm:"default:1" json:"change_deduct_amount"`
MultiOpenMode string `gorm:"size:20;default:forbidden" json:"multi_open_mode"`
MaxInstances int `gorm:"default:1" json:"max_instances"`
EnableTrial bool `gorm:"default:false" json:"enable_trial"`
TrialBalance float64 `gorm:"default:0" json:"trial_balance"`
TrialDays int `gorm:"default:0" json:"trial_days"`
EnableFreePeriod bool `gorm:"default:false" json:"enable_free_period"`
FreePeriodType string `gorm:"size:20;default:range" json:"free_period_type"`
FreePeriodStart string `gorm:"size:50" json:"free_period_start"`
FreePeriodEnd string `gorm:"size:50" json:"free_period_end"`
FreePeriodWeekdays string `gorm:"size:50" json:"free_period_weekdays"`
FreePeriodStartTime string `gorm:"size:10" json:"free_period_start_time"`
FreePeriodEndTime string `gorm:"size:10" json:"free_period_end_time"`
HeartbeatInterval int `gorm:"default:60" json:"heartbeat_interval"`
HeartbeatTimeout int `gorm:"default:300" json:"heartbeat_timeout"`
MaxAttempts int `gorm:"default:5" json:"max_attempts"`
LockDuration int `gorm:"default:30" json:"lock_duration"`
Status string `gorm:"size:20;default:active" json:"status"`
DeductionMode string `gorm:"size:20;default:auto" json:"deduction_mode"`
DeductionType string `gorm:"size:20;default:login" json:"deduction_type"`
DeductionInterval int `gorm:"default:1" json:"deduction_interval"`
DeductionUnit string `gorm:"size:20;default:minute" json:"deduction_unit"`
DeductionAmount float64 `gorm:"default:1" json:"deduction_amount"`
AllowRegister bool `gorm:"default:true" json:"allow_register"`
EnableLoginVerify bool `gorm:"default:false" json:"enable_login_verify"`
EnableRegisterVerify bool `gorm:"default:false" json:"enable_register_verify"`
VerifyMethod string `gorm:"size:20;default:email" json:"verify_method"`
EmailConfigID *uint `json:"email_config_id"`
SmsConfigID *uint `json:"sms_config_id"`
EnablePasswordReset bool `gorm:"default:false" json:"enable_password_reset"`
PasswordResetMethod string `gorm:"size:20;default:email" json:"password_reset_method"`
PasswordResetEmailID *uint `json:"password_reset_email_id"`
PasswordResetSmsID *uint `json:"password_reset_sms_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `json:"user_id"`
Name string `gorm:"size:100" json:"name"`
Description string `gorm:"type:text" json:"description"`
IconURL string `gorm:"size:255" json:"icon_url"`
AppKey string `gorm:"unique;size:50" json:"app_key"`
BillingType string `gorm:"size:20" json:"billing_type"`
LoginPolicy string `gorm:"size:20;default:loose" json:"login_policy"`
LoginMode string `gorm:"size:20;default:account" json:"login_mode"` // account = 账号密码, card = 单卡直登, both = 两种都开
CardLoginBindDevice bool `gorm:"default:true" json:"card_login_bind_device"` // 卡密登录是否也受设备上限约束
CardLoginAllowPassword bool `gorm:"default:false" json:"card_login_allow_password"` // 卡密主体是否允许再设一个登录密码
EncryptType string `gorm:"size:20" json:"encrypt_type"`
EncryptKey string `gorm:"size:255" json:"encrypt_key"`
BindType string `gorm:"size:20" json:"bind_type"`
MaxDevices int `gorm:"default:1" json:"max_devices"`
ChangeLimit int `gorm:"default:3" json:"change_limit"`
ChangeInterval int `gorm:"default:7" json:"change_interval"`
ChangeExceedAction string `gorm:"size:20;default:deny" json:"change_exceed_action"`
ChangeDeductAmount float64 `gorm:"default:1" json:"change_deduct_amount"`
MultiOpenMode string `gorm:"size:20;default:forbidden" json:"multi_open_mode"`
MaxInstances int `gorm:"default:1" json:"max_instances"`
EnableTrial bool `gorm:"default:false" json:"enable_trial"`
TrialBalance float64 `gorm:"default:0" json:"trial_balance"`
TrialDays int `gorm:"default:0" json:"trial_days"`
EnableFreePeriod bool `gorm:"default:false" json:"enable_free_period"`
FreePeriodType string `gorm:"size:20;default:range" json:"free_period_type"`
FreePeriodStart string `gorm:"size:50" json:"free_period_start"`
FreePeriodEnd string `gorm:"size:50" json:"free_period_end"`
FreePeriodWeekdays string `gorm:"size:50" json:"free_period_weekdays"`
FreePeriodStartTime string `gorm:"size:10" json:"free_period_start_time"`
FreePeriodEndTime string `gorm:"size:10" json:"free_period_end_time"`
HeartbeatInterval int `gorm:"default:60" json:"heartbeat_interval"`
HeartbeatTimeout int `gorm:"default:300" json:"heartbeat_timeout"`
MaxAttempts int `gorm:"default:5" json:"max_attempts"`
LockDuration int `gorm:"default:30" json:"lock_duration"`
Status string `gorm:"size:20;default:active" json:"status"`
DeductionMode string `gorm:"size:20;default:auto" json:"deduction_mode"`
DeductionType string `gorm:"size:20;default:login" json:"deduction_type"`
DeductionInterval int `gorm:"default:1" json:"deduction_interval"`
DeductionUnit string `gorm:"size:20;default:minute" json:"deduction_unit"`
DeductionAmount float64 `gorm:"default:1" json:"deduction_amount"`
AllowRegister bool `gorm:"default:true" json:"allow_register"`
EnableLoginVerify bool `gorm:"default:false" json:"enable_login_verify"`
EnableRegisterVerify bool `gorm:"default:false" json:"enable_register_verify"`
VerifyMethod string `gorm:"size:20;default:email" json:"verify_method"`
EmailConfigID *uint `json:"email_config_id"`
SmsConfigID *uint `json:"sms_config_id"`
EnablePasswordReset bool `gorm:"default:false" json:"enable_password_reset"`
PasswordResetMethod string `gorm:"size:20;default:email" json:"password_reset_method"`
PasswordResetEmailID *uint `json:"password_reset_email_id"`
PasswordResetSmsID *uint `json:"password_reset_sms_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}
// Version 版本模型
type Version struct {
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `json:"application_id"`
Version string `gorm:"size:50" json:"version"`
FilePath string `gorm:"size:255" json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `gorm:"size:64" json:"file_hash"`
EntryFile string `gorm:"size:255" json:"entry_file"`
EntryFiles string `gorm:"type:text" json:"entry_files"` // JSON数组,可启动的入口文件
DesktopShortcutFiles string `gorm:"type:text" json:"desktop_shortcut_files"` // JSON数组,需要创建桌面快捷方式的文件
UpdateStrategy string `gorm:"size:20;default:optional" json:"update_strategy"`
UpdateType string `gorm:"size:20;default:full" json:"update_type"`
UpdateMethod string `gorm:"size:20;default:auto" json:"update_method"`
CustomDownloadURL string `gorm:"size:500" json:"custom_download_url"`
FullPackagePath string `gorm:"size:255" json:"full_package_path"`
FullPackageSize int64 `json:"full_package_size"`
FullPackageHash string `gorm:"size:64" json:"full_package_hash"`
DeltaPackagePath string `gorm:"size:255" json:"delta_package_path"`
DeltaPackageSize int64 `json:"delta_package_size"`
DeltaPackageHash string `gorm:"size:64" json:"delta_package_hash"`
Description string `gorm:"type:text" json:"description"`
Changelog string `gorm:"type:text" json:"changelog"`
PublishStatus string `gorm:"size:20;default:draft;index" json:"publish_status"` // draft, published, deprecated, superseded
SupersededBy *uint `json:"superseded_by"`
PublishedAt *time.Time `json:"published_at"`
DeprecatedAt *time.Time `json:"deprecated_at"`
BaseVersionID *uint `json:"base_version_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `json:"application_id"`
Version string `gorm:"size:50" json:"version"`
FilePath string `gorm:"size:255" json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `gorm:"size:64" json:"file_hash"`
EntryFile string `gorm:"size:255" json:"entry_file"`
EntryFiles string `gorm:"type:text" json:"entry_files"` // JSON数组,可启动的入口文件
DesktopShortcutFiles string `gorm:"type:text" json:"desktop_shortcut_files"` // JSON数组,需要创建桌面快捷方式的文件
UpdateStrategy string `gorm:"size:20;default:optional" json:"update_strategy"`
UpdateType string `gorm:"size:20;default:full" json:"update_type"`
UpdateMethod string `gorm:"size:20;default:auto" json:"update_method"`
CustomDownloadURL string `gorm:"size:500" json:"custom_download_url"`
FullPackagePath string `gorm:"size:255" json:"full_package_path"`
FullPackageSize int64 `json:"full_package_size"`
FullPackageHash string `gorm:"size:64" json:"full_package_hash"`
DeltaPackagePath string `gorm:"size:255" json:"delta_package_path"`
DeltaPackageSize int64 `json:"delta_package_size"`
DeltaPackageHash string `gorm:"size:64" json:"delta_package_hash"`
Description string `gorm:"type:text" json:"description"`
Changelog string `gorm:"type:text" json:"changelog"`
PublishStatus string `gorm:"size:20;default:draft;index" json:"publish_status"` // draft, published, deprecated, superseded
SupersededBy *uint `json:"superseded_by"`
PublishedAt *time.Time `json:"published_at"`
DeprecatedAt *time.Time `json:"deprecated_at"`
BaseVersionID *uint `json:"base_version_id"`
Protected bool `gorm:"default:false" json:"protected"` // 是否为加壳产物
SourceVersionID *uint `gorm:"index" json:"source_version_id"` // 加壳来源版本
ProtectTaskID *uint `json:"protect_task_id"` // 对应加壳任务
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
Files []VersionFile `gorm:"foreignKey:VersionID" json:"files,omitempty"`
BaseVersion *Version `gorm:"foreignKey:BaseVersionID" json:"base_version,omitempty"`
Superseder *Version `gorm:"foreignKey:SupersededBy" json:"superseder,omitempty"`
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
Files []VersionFile `gorm:"foreignKey:VersionID" json:"files,omitempty"`
BaseVersion *Version `gorm:"foreignKey:BaseVersionID" json:"base_version,omitempty"`
Superseder *Version `gorm:"foreignKey:SupersededBy" json:"superseder,omitempty"`
}
// VersionFile 版本文件模型
@@ -281,6 +290,7 @@ type CardType struct {
ApplicationID uint `json:"application_id"`
Name string `gorm:"size:100" json:"name"`
RechargeType string `gorm:"size:20;default:balance" json:"recharge_type"` // balance(余额充值), subscription(订阅充值)
Purpose string `gorm:"size:20;default:recharge" json:"purpose"` // recharge = 充值卡, credential = 登录卡
Value float64 `json:"value"` // 余额值或订阅时长(秒)
ValueUnit string `gorm:"size:20;default:day" json:"value_unit"` // 时长单位: day, month, year (仅订阅充值)
Price float64 `json:"price"`
@@ -300,6 +310,9 @@ type Card struct {
ApplicationID uint `gorm:"index;not null" json:"application_id"`
CardTypeID uint `gorm:"index;not null" json:"card_type_id"`
CardKey string `gorm:"unique;size:100" json:"card_key"`
Purpose string `gorm:"size:20;default:recharge;index" json:"purpose"` // recharge = 充值卡, credential = 登录卡
SubjectID *uint `gorm:"index" json:"subject_id"` // 登录卡激活后归属的主体(一卡一主体)
AppliedToSubjectID *uint `json:"applied_to_subject_id"` // 充值卡充给了哪个主体(对账用)
CreatorID uint `gorm:"index" json:"creator_id"`
AgentID *uint `gorm:"index" json:"agent_id"`
AppUserID *uint `gorm:"index" json:"app_user_id"`
@@ -374,6 +387,7 @@ type Log struct {
IPAddress string `gorm:"size:50" json:"ip_address"`
UserAgent string `gorm:"size:500" json:"user_agent"`
DeviceID string `gorm:"size:100" json:"device_id"`
CardTypeID *uint `gorm:"index" json:"card_type_id"` // 卡密登录失败时记下这是哪个卡型的卡,便于按卡型看爆破
Status string `gorm:"size:20;default:success" json:"status"` // success, failed, pending
Level string `gorm:"size:20;default:info" json:"level"` // info, warning, error
ErrorMessage string `gorm:"type:text" json:"error_message"`
@@ -382,9 +396,9 @@ type Log struct {
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
User *User `gorm:"foreignKey:UserID" json:"user"`
User *User `gorm:"foreignKey:UserID" json:"user"`
Application *Application `gorm:"foreignKey:ApplicationID" json:"application"`
AppUser *AppUser `gorm:"foreignKey:AppUserID" json:"app_user"`
AppUser *AppUser `gorm:"foreignKey:AppUserID" json:"app_user"`
}
// RechargeRecord 充值记录模型
@@ -507,9 +521,9 @@ type CloudConstant struct {
// RiskControlRule 风控规则模型
type RiskControlRule struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"index;not null" json:"user_id"` // 创建者ID
ApplicationID *uint `gorm:"index" json:"application_id"` // 应用ID,为空表示全局规则
Type string `gorm:"size:20;not null" json:"type"` // ip, device, user, region
UserID uint `gorm:"index;not null" json:"user_id"` // 创建者ID
ApplicationID *uint `gorm:"index" json:"application_id"` // 应用ID,为空表示全局规则
Type string `gorm:"size:20;not null" json:"type"` // ip, device, user, region
Value string `gorm:"size:255;not null" json:"value"`
Reason string `gorm:"size:500" json:"reason"`
Status string `gorm:"size:20;default:active" json:"status"` // active, inactive
@@ -546,11 +560,11 @@ type CloudVariable struct {
}
type CloudVariableRecord struct {
ID uint `gorm:"primaryKey" json:"id"`
CloudVariableID uint `gorm:"index;not null" json:"cloud_variable_id"`
AppUserID *uint `json:"app_user_id"`
Data string `gorm:"type:text" json:"data"`
CreatedAt time.Time `json:"created_at"`
ID uint `gorm:"primaryKey" json:"id"`
CloudVariableID uint `gorm:"index;not null" json:"cloud_variable_id"`
AppUserID *uint `json:"app_user_id"`
Data string `gorm:"type:text" json:"data"`
CreatedAt time.Time `json:"created_at"`
CloudVariable CloudVariable `gorm:"foreignKey:CloudVariableID" json:"cloud_variable,omitempty"`
}
@@ -679,7 +693,7 @@ type Package struct {
Name string `gorm:"size:100" json:"name"`
NameEn string `gorm:"size:100" json:"name_en"`
Price float64 `gorm:"default:0" json:"price"`
Currency string `gorm:"size:10;default:CNY" json:"currency"` // CNY, USD, EUR, GBP, JPY
Currency string `gorm:"size:10;default:CNY" json:"currency"` // CNY, USD, EUR, GBP, JPY
Period string `gorm:"size:20;default:permanent" json:"period"` // permanent, monthly, yearly
Description string `gorm:"size:255" json:"description"`
DescriptionEn string `gorm:"size:255" json:"description_en"`
@@ -711,23 +725,23 @@ type PackagePermission struct {
// Doc 文档模型
type Doc struct {
ID uint `gorm:"primaryKey" json:"id"`
CategoryID *uint `json:"category_id"`
Title string `gorm:"size:200" json:"title"`
TitleEn string `gorm:"size:200" json:"title_en"`
Slug string `gorm:"size:200;unique" json:"slug"`
Content string `gorm:"type:longtext" json:"content"`
ContentEn string `gorm:"type:longtext" json:"content_en"`
Summary string `gorm:"size:500" json:"summary"`
SummaryEn string `gorm:"size:500" json:"summary_en"`
Icon string `gorm:"size:50" json:"icon"`
Sort int `gorm:"default:0" json:"sort"`
Status string `gorm:"size:20;default:draft" json:"status"` // draft, published
ViewCount int `gorm:"default:0" json:"view_count"`
AuthorID *uint `json:"author_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
ID uint `gorm:"primaryKey" json:"id"`
CategoryID *uint `json:"category_id"`
Title string `gorm:"size:200" json:"title"`
TitleEn string `gorm:"size:200" json:"title_en"`
Slug string `gorm:"size:200;unique" json:"slug"`
Content string `gorm:"type:longtext" json:"content"`
ContentEn string `gorm:"type:longtext" json:"content_en"`
Summary string `gorm:"size:500" json:"summary"`
SummaryEn string `gorm:"size:500" json:"summary_en"`
Icon string `gorm:"size:50" json:"icon"`
Sort int `gorm:"default:0" json:"sort"`
Status string `gorm:"size:20;default:draft" json:"status"` // draft, published
ViewCount int `gorm:"default:0" json:"view_count"`
AuthorID *uint `json:"author_id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
Category *DocCategory `gorm:"foreignKey:CategoryID" json:"category,omitempty"`
Author *User `gorm:"foreignKey:AuthorID" json:"author,omitempty"`
@@ -753,14 +767,14 @@ type Captcha struct {
}
type EmailVerifyCode struct {
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `gorm:"index" json:"application_id"`
Email string `gorm:"size:100;index" json:"email"`
Code string `gorm:"size:10" json:"code"`
Purpose string `gorm:"size:20;default:register" json:"purpose"`
ExpiresAt time.Time `json:"expires_at"`
Used bool `gorm:"default:false" json:"used"`
CreatedAt time.Time `json:"created_at"`
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `gorm:"index" json:"application_id"`
Email string `gorm:"size:100;index" json:"email"`
Code string `gorm:"size:10" json:"code"`
Purpose string `gorm:"size:20;default:register" json:"purpose"`
ExpiresAt time.Time `json:"expires_at"`
Used bool `gorm:"default:false" json:"used"`
CreatedAt time.Time `json:"created_at"`
}
type SmsVerifyCode struct {
@@ -775,35 +789,35 @@ type SmsVerifyCode struct {
}
type AppSMTPConfig struct {
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `gorm:"unique" json:"application_id"`
Host string `gorm:"size:100" json:"host"`
Port int `gorm:"default:465" json:"port"`
User string `gorm:"size:100" json:"user"`
Password string `gorm:"size:255" json:"password"`
FromName string `gorm:"size:100" json:"from_name"`
FromEmail string `gorm:"size:100" json:"from_email"`
UseSSL bool `gorm:"default:true" json:"use_ssl"`
Status string `gorm:"size:20;default:active" json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `gorm:"unique" json:"application_id"`
Host string `gorm:"size:100" json:"host"`
Port int `gorm:"default:465" json:"port"`
User string `gorm:"size:100" json:"user"`
Password string `gorm:"size:255" json:"password"`
FromName string `gorm:"size:100" json:"from_name"`
FromEmail string `gorm:"size:100" json:"from_email"`
UseSSL bool `gorm:"default:true" json:"use_ssl"`
Status string `gorm:"size:20;default:active" json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}
type EmailTemplate struct {
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `gorm:"index" json:"application_id"`
Type string `gorm:"size:50;index" json:"type"`
Name string `gorm:"size:100" json:"name"`
Subject string `gorm:"size:200" json:"subject"`
Content string `gorm:"type:text" json:"content"`
IsDefault bool `gorm:"default:false" json:"is_default"`
Status string `gorm:"size:20;default:active" json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `gorm:"index" json:"application_id"`
Type string `gorm:"size:50;index" json:"type"`
Name string `gorm:"size:100" json:"name"`
Subject string `gorm:"size:200" json:"subject"`
Content string `gorm:"type:text" json:"content"`
IsDefault bool `gorm:"default:false" json:"is_default"`
Status string `gorm:"size:20;default:active" json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}
@@ -837,23 +851,30 @@ type UserDevice struct {
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
Sessions []DeviceSession `gorm:"foreignKey:DeviceID;references:ID" json:"sessions,omitempty"`
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
Sessions []DeviceSession `gorm:"foreignKey:UserDeviceID;references:ID" json:"sessions,omitempty"`
}
// DeviceSession 设备会话模型(多开实例,运行时)
// DeviceSession 一条「设备上的一个实例」的在线记录。
//
// 注意 UserDeviceID 的命名:它对应列 device_id,指向 user_devices.id。
// 早先这个字段叫 DeviceID,和 UserDevice.DeviceID(设备指纹字符串)同名,
// 导致 GORM 推断外键时选错对象,每次 AutoMigrate 都想把 user_devices.device_id
// 改成数值型(MySQL 报 1265)并 DROP 不存在的索引(1091)。
// 改名后关系不再有歧义;列名与索引名都用 tag 钉死,表结构保持原样。
type DeviceSession struct {
ID uint `gorm:"primaryKey" json:"id"`
DeviceID uint `gorm:"index" json:"device_id"`
UserDeviceID uint `gorm:"column:device_id;index:idx_device_sessions_device_id" json:"device_id"`
UserID uint `gorm:"index" json:"user_id"`
ApplicationID uint `gorm:"index" json:"application_id"`
InstanceID string `gorm:"size:100;uniqueIndex:idx_device_instance" json:"instance_id"`
InstanceID string `gorm:"size:100;unique" json:"instance_id"`
LastHeartbeat *time.Time `json:"last_heartbeat"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Device UserDevice `gorm:"foreignKey:DeviceID" json:"device,omitempty"`
Device UserDevice `gorm:"foreignKey:UserDeviceID;references:ID" json:"device,omitempty"`
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
}
@@ -890,6 +911,61 @@ type PackHistory struct {
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
}
// ProtectTask 加壳任务:给原始程序注入验证壳(改入口 + 内嵌壳 DLL + 双层 CRC32)
type ProtectTask struct {
ID uint `gorm:"primaryKey" json:"id"`
ApplicationID uint `gorm:"index" json:"application_id"`
UserID uint `gorm:"index" json:"user_id"`
VersionID uint `gorm:"index" json:"version_id"` // 来源版本(从哪个版本加壳)
SignProfileID *uint `json:"sign_profile_id"` // 产物重签使用的证书资产
CertIdentity int `gorm:"default:0" json:"cert_identity"` // 用证书文件里的第几套身份(0/1 = 第一套)
// ShellTheme 验证界面皮肤:classic(Direct2D 原版)/ dark / light / industrial(DuiLib 壳)
ShellTheme string `gorm:"size:32;default:classic" json:"shell_theme"`
SourceName string `gorm:"size:255" json:"source_name"`
SourceSize int64 `json:"source_size"`
Kind string `gorm:"size:16;default:pe" json:"kind"` // pe/apk/ipa/elf/macho
Arch string `gorm:"size:16" json:"arch"`
Status string `gorm:"size:20;default:pending" json:"status"` // pending/running/done/failed
Message string `gorm:"size:500" json:"message"`
OutputName string `gorm:"size:255" json:"output_name"`
OutputSize int64 `json:"output_size"`
OutputPath string `gorm:"size:500" json:"-"`
CrcVfy string `gorm:"size:16" json:"crc_vfy"`
CrcFile string `gorm:"size:16" json:"crc_file"`
StartedAt *time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
}
// SignProfile 签名证书资产(Windows pfx / iOS p12+mobileprovision)
// 证书与口令都加密落盘,库里只存元数据;私钥永不下发前端。
type SignProfile struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"index" json:"user_id"`
Platform string `gorm:"size:16;index" json:"platform"` // windows / ios
Name string `gorm:"size:100" json:"name"`
CertFormat string `gorm:"size:16" json:"cert_format"` // pfx / p12
CertPath string `gorm:"size:500" json:"-"` // 加密后的证书文件
PassPath string `gorm:"size:500" json:"-"` // 加密后的口令
ProfilePath string `gorm:"size:500" json:"-"` // 加密后的 mobileprovision(仅 iOS)
CrossPath string `gorm:"size:500" json:"-"` // 加密后的交叉签名证书(.cer,驱动签名用)
Subject string `gorm:"size:255" json:"subject"` // 证书主题(提交时解析,可为空)
// CertCount / KeyCount 这个 pfx 里到底装了什么:
// 链式包里证书多但私钥只有一把(正常,签名会带完整链);
// 多身份包里私钥多把,签名只会用第一套。
CertCount int `gorm:"default:0" json:"cert_count"`
KeyCount int `gorm:"default:0" json:"key_count"`
NotAfter *time.Time `json:"not_after"`
Status string `gorm:"size:20;default:active" json:"status"`
LastUsedAt *time.Time `json:"last_used_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// WebhookConfig Webhook配置
type WebhookConfig struct {
ID uint `gorm:"primaryKey" json:"id"`
@@ -982,8 +1058,8 @@ type StorageUsage struct {
type UsageAlertRecord struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `json:"user_id"`
Type string `gorm:"size:20" json:"type"` // api_calls, storage, package_expiry
Level string `gorm:"size:20" json:"level"` // warning, critical
Type string `gorm:"size:20" json:"type"` // api_calls, storage, package_expiry
Level string `gorm:"size:20" json:"level"` // warning, critical
Message string `gorm:"size:255" json:"message"`
Usage float64 `json:"usage"`
Limit float64 `json:"limit"`
@@ -1006,3 +1082,16 @@ type Notification struct {
User User `gorm:"foreignKey:UserID" json:"user,omitempty"`
}
// CertBlacklist 平台自己的证书黑名单。
// 微软的 Disallowed Trust List 是自动拉取的(见 protect.BanState),
// 这张表是运维手动拉黑的场景(比如发现某证书私钥泄露、被滥用)。
type CertBlacklist struct {
ID uint `gorm:"primaryKey" json:"id"`
Fingerprint string `gorm:"size:128;uniqueIndex" json:"fingerprint"` // 证书 SHA256 指纹
Subject string `gorm:"size:500" json:"subject"`
Reason string `gorm:"size:200" json:"reason"`
Note string `gorm:"size:500" json:"note"`
CreatedBy uint `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
}
+437
View File
@@ -0,0 +1,437 @@
package protect
// Android APK 注入:把验证壳(com.vfy.ShellApplication)合并进目标 APK
//
// 步骤与沙箱验证过的一致:
// 1) apktool d 目标 → 拿到文本 AndroidManifest.xml 与 smali
// 2) 把内嵌的壳 smali 树放进 dec/smali/com/vfy
// 3) 改 <application android:name="..."> 指向壳,原类名写进 assets/vfy_cfg.json
// 4) apktool b 回编译 → zipalign 4 对齐 → apksigner 重签(v1+v2+v3)
// 未重签的 APK 装不上,所以签名是必须步骤;默认用内嵌开发证书,可被配置覆盖。
import (
"archive/tar"
"archive/zip"
"bytes"
"compress/gzip"
"embed"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
)
//go:embed assets/shell_smali.tgz assets/vfy.keystore
var apkAssets embed.FS
const (
shellClassName = "com.vfy.ShellApplication"
defaultKsPass = "vfypass"
defaultKsAlias = "vfy"
cfgAssetName = "assets/vfy_cfg.json"
smaliShellDir = "com/vfy"
)
// ToolPaths 外部工具位置。支持两种部署形态:
//
// A. PATH 里有 apktool/apksigner 二进制(Debian 开发机)
// B. 只有 JRE + 两个 fat jar(Alpine 生产镜像)
type ToolPaths struct {
Java string
ApktoolJar string
SignerJar string // uber-apk-signer:对齐 + v1/v2/v3 重签一体
Apktool string // PATH 模式
Apksigner string // PATH 模式
Zipalign string // PATH 模式(可选)
Keystore string
KsPass string
KsAlias string
}
func envOr(env, def string) string {
if v := os.Getenv(env); v != "" {
return v
}
return def
}
func fileExists(p string) bool {
if p == "" {
return false
}
st, err := os.Stat(p)
return err == nil && !st.IsDir()
}
// Tools 解析工具路径(环境变量优先,其次 PATH,最后容器内固定路径)
func Tools() ToolPaths {
look := func(name string) string {
if p, err := exec.LookPath(name); err == nil {
return p
}
return ""
}
t := ToolPaths{
Java: look(envOr("PROTECT_JAVA", "java")),
Apktool: look(envOr("PROTECT_APKTOOL", "apktool")),
Apksigner: look(envOr("PROTECT_APKSIGNER", "apksigner")),
Zipalign: look(envOr("PROTECT_ZIPALIGN", "zipalign")),
ApktoolJar: os.Getenv("PROTECT_APKTOOL_JAR"),
SignerJar: os.Getenv("PROTECT_SIGNER_JAR"),
Keystore: os.Getenv("PROTECT_APK_KEYSTORE"),
}
if t.ApktoolJar == "" && fileExists("/app/tools/apktool.jar") {
t.ApktoolJar = "/app/tools/apktool.jar"
}
if t.SignerJar == "" && fileExists("/app/tools/uber-apk-signer.jar") {
t.SignerJar = "/app/tools/uber-apk-signer.jar"
}
t.KsPass = envOr("PROTECT_APK_KSPASS", defaultKsPass)
t.KsAlias = envOr("PROTECT_APK_KSALIAS", defaultKsAlias)
return t
}
func (t ToolPaths) hasApktool() bool {
return t.Apktool != "" || (t.Java != "" && fileExists(t.ApktoolJar))
}
func (t ToolPaths) hasSigner() bool {
return t.SignerJar != "" && t.Java != "" && fileExists(t.SignerJar) || t.Apksigner != ""
}
// MissingTools 返回缺哪些工具(给用户明确结论)
func MissingTools() []string {
t := Tools()
var miss []string
if !t.hasApktool() {
miss = append(miss, "apktool(或 JRE + apktool.jar)")
}
if !t.hasSigner() {
miss = append(miss, "签名器(uber-apk-signer.jar 或 apksigner)")
}
return miss
}
// ApkAvailable 当前环境能不能做 APK 注入
func ApkAvailable() bool { return len(MissingTools()) == 0 }
// apktoolCmd 返回可执行文件与前置参数
func (t ToolPaths) apktoolCmd() (string, []string) {
if t.Apktool != "" {
return t.Apktool, nil
}
return t.Java, []string{"-jar", t.ApktoolJar}
}
// AppNameRe 取 package 与 <application> 上的 android:name
var (
rePackage = regexp.MustCompile(`package="([^"]+)"`)
reAppTag = regexp.MustCompile(`(?s)<application\b[^>]*>`)
reNameAttr = regexp.MustCompile(`android:name="([^"]*)"`)
reAppNameAt = regexp.MustCompile(`android:name="[^"]*"`)
)
// patchManifestText 把 application 的 android:name 改成壳类,返回原类名(已补全包名)
func patchManifestText(manifest string) (patched string, originalApp string, err error) {
pkg := ""
if m := rePackage.FindStringSubmatch(manifest); m != nil {
pkg = m[1]
}
tag := reAppTag.FindString(manifest)
if tag == "" {
return "", "", fmt.Errorf("AndroidManifest 里没有 <application> 节点")
}
if m := reNameAttr.FindStringSubmatch(tag); m != nil {
originalApp = strings.TrimSpace(m[1])
}
// 相对名补全:.App → pkg.App;App → pkg.App
switch {
case strings.HasPrefix(originalApp, "."):
originalApp = pkg + originalApp
case originalApp != "" && !strings.Contains(originalApp, "."):
originalApp = pkg + "." + originalApp
}
var newTag string
if reNameAttr.MatchString(tag) {
newTag = reAppNameAt.ReplaceAllString(tag, `android:name="`+shellClassName+`"`)
newTag = reAppNameAt.ReplaceAllString(newTag, `android:name="`+shellClassName+`"`) // 防止多次替换偏差
} else {
newTag = strings.Replace(tag, "<application", `<application android:name="`+shellClassName+`"`, 1)
}
if newTag == tag {
return "", "", fmt.Errorf("改写 application 节点失败")
}
patched = strings.Replace(manifest, tag, newTag, 1)
return patched, originalApp, nil
}
// ReadApkManifestPkg 读 APK 的包名(不解压全包,走 zip 中心目录 + AXML 字符串池粗取)
func ReadApkManifestPkg(data []byte) string {
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return ""
}
for _, f := range zr.File {
if f.Name != "AndroidManifest.xml" || f.UncompressedSize64 > 8<<20 {
continue
}
rc, err := f.Open()
if err != nil {
return ""
}
defer rc.Close()
buf, err := io.ReadAll(rc)
if err != nil {
return ""
}
// AXML 字符串池里的 UTF-16 包名字符串:粗找形如 a.b.c 的片段
for _, cand := range utf16Strings(buf) {
if isLikelyPackage(cand) {
return cand
}
}
}
return ""
}
// utf16Strings 从二进制里扫出长度合理、只含可打印字符的 UTF-16LE 串
func utf16Strings(b []byte) []string {
var out []string
var cur []rune
flush := func() {
if len(cur) >= 3 {
out = append(out, string(cur))
}
cur = nil
}
for i := 0; i+1 < len(b); i += 2 {
c := rune(uint16(b[i]) | uint16(b[i+1])<<8)
if c >= 0x20 && c < 0x7f {
cur = append(cur, c)
} else {
flush()
}
}
flush()
return out
}
// patchAPK 执行完整注入,返回新 APK 字节
func patchAPK(raw, cfg []byte, workRoot string) ([]byte, Info, error) {
var info Info
miss := MissingTools()
if len(miss) > 0 {
return nil, info, &UnsupportedError{
Kind: KindAPK,
Arch: "universal",
Reason: "服务端缺少 Android 工具链:" + strings.Join(miss, "、"),
Needs: []string{"在镜像里 apk add openjdk17-jre-headless apksigner zipalign apktool"},
}
}
tools := Tools()
dir := filepath.Join(workRoot, "apk_"+time.Now().Format("150405"))
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, info, err
}
defer os.RemoveAll(dir)
inPath := filepath.Join(dir, "in.apk")
if err := os.WriteFile(inPath, raw, 0o644); err != nil {
return nil, info, err
}
decDir := filepath.Join(dir, "dec")
akExe, akPre := tools.apktoolCmd()
args := append([]string{}, akPre...)
out, err := runCmd(dir, akExe, append(args, "d", "-f", "-o", decDir, inPath)...)
if err != nil {
return nil, info, fmt.Errorf("apktool 反编译失败: %v: %s", err, tail(out, 400))
}
manPath := filepath.Join(decDir, "AndroidManifest.xml")
manBytes, err := os.ReadFile(manPath)
if err != nil {
return nil, info, fmt.Errorf("读取 AndroidManifest 失败: %w", err)
}
patched, originalApp, err := patchManifestText(string(manBytes))
if err != nil {
return nil, info, err
}
if err := os.WriteFile(manPath, []byte(patched), 0o644); err != nil {
return nil, info, err
}
if err := extractTarGz("assets/shell_smali.tgz", filepath.Join(decDir, "smali", "com")); err != nil {
return nil, info, fmt.Errorf("释放壳 smali 失败: %w", err)
}
cfgMap := map[string]interface{}{}
if len(cfg) > 0 {
_ = json.Unmarshal(cfg, &cfgMap)
}
cfgMap["original_app"] = originalApp
cfgMap["device_type"] = "android"
cfgBytes, _ := json.Marshal(cfgMap)
cfgPath := filepath.Join(decDir, cfgAssetName)
if err := os.MkdirAll(filepath.Dir(cfgPath), 0o755); err != nil {
return nil, info, err
}
if err := os.WriteFile(cfgPath, cfgBytes, 0o644); err != nil {
return nil, info, err
}
built := filepath.Join(dir, "rebuilt.apk")
if out, err := runCmd(dir, akExe, append(args, "b", decDir, "-o", built)...); err != nil {
return nil, info, fmt.Errorf("apktool 回编译失败: %v: %s", err, tail(out, 600))
}
// 证书:用户自带优先,否则用内嵌开发证书
ksPath := tools.Keystore
if ksPath == "" {
ksPath = filepath.Join(dir, "vfy.keystore")
ksBytes, err := apkAssets.ReadFile("assets/vfy.keystore")
if err != nil {
return nil, info, fmt.Errorf("读取内嵌证书失败: %w", err)
}
if err := os.WriteFile(ksPath, ksBytes, 0o600); err != nil {
return nil, info, err
}
}
signed := filepath.Join(dir, "signed.apk")
if tools.SignerJar != "" && fileExists(tools.SignerJar) && tools.Java != "" {
// uber-apk-signer:一次完成对齐 + v1/v2/v3 签名,输出到 -o 目录
signDir := filepath.Join(dir, "signed_out")
os.MkdirAll(signDir, 0o755)
sargs := []string{"-jar", tools.SignerJar, "--apks", built,
"--ks", ksPath, "--ksAlias", tools.KsAlias,
"--ksPass", tools.KsPass, "--ksKeyPass", tools.KsPass,
"-o", signDir, "--allowResign"}
if tools.Zipalign == "" {
sargs = append(sargs, "--skipZipAlign")
}
if out, err := runCmd(dir, tools.Java, sargs...); err != nil {
return nil, info, fmt.Errorf("签名失败: %v: %s", err, tail(out, 600))
}
entries, _ := os.ReadDir(signDir)
for _, e := range entries {
if strings.HasSuffix(e.Name(), ".apk") && !strings.HasSuffix(e.Name(), ".idsig") {
signed = filepath.Join(signDir, e.Name())
break
}
}
} else {
// PATH 模式:zipalign + apksigner
aligned := built
if tools.Zipalign != "" {
aligned = filepath.Join(dir, "aligned.apk")
if out, err := runCmd(dir, tools.Zipalign, "-f", "4", built, aligned); err != nil {
return nil, info, fmt.Errorf("zipalign 失败: %v: %s", err, tail(out, 400))
}
}
if out, err := runCmd(dir, tools.Apksigner, "sign",
"--ks", ksPath,
"--ks-pass", "pass:"+tools.KsPass,
"--key-pass", "pass:"+tools.KsPass,
"--out", signed, aligned); err != nil {
return nil, info, fmt.Errorf("apksigner 签名失败: %v: %s", err, tail(out, 600))
}
}
finalBytes, err := os.ReadFile(signed)
if err != nil {
return nil, info, err
}
info.Arch = "universal"
info.OriginalSource = len(raw)
info.OutSize = len(finalBytes)
info.Note = "APK 已注入壳并重签(签名证书 " + tools.KsAlias + ",原 Application: " + originalApp + ")"
return finalBytes, info, nil
}
// extractTarGz 把内嵌 tar.gz 释放到目标目录
func extractTarGz(asset, dest string) error {
raw, err := apkAssets.ReadFile(asset)
if err != nil {
return err
}
gz, err := gzip.NewReader(bytes.NewReader(raw))
if err != nil {
return err
}
defer gz.Close()
tr := tar.NewReader(gz)
for {
hdr, err := tr.Next()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
// 只允许相对路径,防目录穿越
clean := filepath.Clean(hdr.Name)
if strings.HasPrefix(clean, "..") || filepath.IsAbs(clean) {
continue
}
target := filepath.Join(dest, clean)
if hdr.Typeflag == tar.TypeDir {
os.MkdirAll(target, 0o755)
continue
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
f, err := os.Create(target)
if err != nil {
return err
}
io.Copy(f, tr)
f.Close()
}
}
// runCmd 跑外部命令,返回输出
func runCmd(dir, name string, args ...string) (string, error) {
cmd := exec.Command(name, args...)
cmd.Dir = dir
var buf bytes.Buffer
cmd.Stdout = &buf
cmd.Stderr = &buf
err := cmd.Run()
return buf.String(), err
}
func tail(s string, n int) string {
if len(s) <= n {
return s
}
return s[len(s)-n:]
}
// isLikelyPackage 判断像不像 Android 包名:每段小写字母开头、只含小写/数字/下划线,
// 且排除权限、action、category 这些同样长成点分串的名字
func isLikelyPackage(s string) bool {
if len(s) < 5 || len(s) > 80 || strings.Count(s, ".") < 1 {
return false
}
lower := strings.ToLower(s)
for _, bad := range []string{"android.permission", "intent.action", "intent.category",
"android.intent", "meta-data", "schemas.android"} {
if strings.Contains(lower, bad) {
return false
}
}
seg := regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
for _, part := range strings.Split(s, ".") {
if !seg.MatchString(part) {
return false
}
}
return true
}
+112
View File
@@ -0,0 +1,112 @@
package protect
import (
"archive/zip"
"bytes"
"os"
"path/filepath"
"strings"
"testing"
)
func TestPatchManifestText(t *testing.T) {
cases := []struct {
in string
wantOrig string
}{
{
`<manifest package="com.demo"><uses-permission android:name="android.permission.INTERNET"/><application android:label="A" android:name="com.demo.RealApp"></application></manifest>`,
"com.demo.RealApp",
},
{
`<manifest package="com.demo"><application android:name=".App"></application></manifest>`,
"com.demo.App",
},
{
`<manifest package="com.demo"><application android:name="OnlyName"></application></manifest>`,
"com.demo.OnlyName",
},
{
`<manifest package="com.demo"><application android:label="A"></application></manifest>`,
"",
},
}
for i, c := range cases {
out, orig, err := patchManifestText(c.in)
if err != nil {
t.Fatalf("case %d 报错: %v", i, err)
}
if !strings.Contains(out, `android:name="`+shellClassName+`"`) {
t.Fatalf("case %d 没写壳类: %s", i, out)
}
if orig != c.wantOrig {
t.Fatalf("case %d original_app=%q 期望 %q", i, orig, c.wantOrig)
}
// 权限的 android:name 不能被改坏
if strings.Contains(c.in, "android.permission.INTERNET") && !strings.Contains(out, "android.permission.INTERNET") {
t.Fatalf("case %d 把权限名改坏了", i)
}
}
}
func TestReadApkManifestPkg(t *testing.T) {
apk := os.Getenv("PROTECT_TEST_APK")
if apk == "" {
t.Skip("未设置 PROTECT_TEST_APK")
}
data, err := os.ReadFile(apk)
if err != nil {
t.Skip("读不到样本")
}
pkg := ReadApkManifestPkg(data)
if pkg == "" {
t.Fatalf("没读出包名")
}
t.Logf("包名: %s", pkg)
}
// E2E:真跑 apktool/apksigner(需要本机有工具链 + PROTECT_TEST_APK)
func TestPatchAPKE2E(t *testing.T) {
if os.Getenv("PROTECT_E2E") == "" {
t.Skip("未设置 PROTECT_E2E")
}
apk := os.Getenv("PROTECT_TEST_APK")
if apk == "" {
t.Skip("未设置 PROTECT_TEST_APK")
}
if !ApkAvailable() {
t.Fatalf("工具链缺失: %v", MissingTools())
}
raw, err := os.ReadFile(apk)
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
out, info, err := patchAPK(raw, []byte(`{"api":"http://127.0.0.1:18080/api/v1/app/seedapp01/login","name":"验证"}`), dir)
if err != nil {
t.Fatalf("注入失败: %v", err)
}
if len(out) == 0 {
t.Fatal("产物为空")
}
if info.Arch != "universal" || info.Note == "" {
t.Fatalf("Info 不完整: %+v", info)
}
// 产物结构校验
zr, err := zip.NewReader(bytes.NewReader(out), int64(len(out)))
if err != nil {
t.Fatalf("产物不是有效 zip: %v", err)
}
var hasCfg bool
for _, f := range zr.File {
if f.Name == "assets/vfy_cfg.json" {
hasCfg = true
}
}
if !hasCfg {
t.Fatal("产物里没有 assets/vfy_cfg.json")
}
outPath := filepath.Join(dir, "out.apk")
os.WriteFile(outPath, out, 0o644)
t.Logf("产物: %s (%d 字节) note=%s", outPath, len(out), info.Note)
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+140
View File
@@ -0,0 +1,140 @@
package protect
// ELF(Linux x86_64)注入:追加一个 PT_LOAD 段放壳代码 + 配置,改 e_entry 指过去
//
// 段内布局:[新的 program header 表][48 字节头][壳机器码][cfg JSON]
// 头字段(小端):
// 0..3 magic "VELF" | 4..7 ver | 8..15 stubSize | 16..23 壳代码 vaddr
// 24..31 cfgOff(相对头基址)| 32..39 cfgSize | 40..47 oep(原入口 vaddr)
//
// 为什么把 phdr 表搬进新段:绝大多数发行版二进制的 program header 表没有 PT_NULL 空位,
// 想在表里追加一项只能整表复制一份新位置。搬表后必须同步 PT_PHDR 和 e_phoff/e_phnum,
// 否则 glibc 在 exit 阶段会调用错地址崩溃(实测 PIE 必崩)。
import (
"bytes"
"debug/elf"
_ "embed"
"encoding/binary"
"fmt"
)
//go:embed assets/elfstub64.bin
var elfStub64 []byte
const (
elfHdrSize = 48
elfPageAlign = 0x1000
elfOffEntry = 0x18
elfOffPhoff = 0x20
elfOffPhents = 0x36
elfOffPhnum = 0x38
)
// PatchELF 注入 x86_64 ELF。signed 参数忽略(ELF 侧暂不处理签名)。
func PatchELF(target, cfg []byte) (out []byte, info Info, err error) {
stub := elfStub64
if len(stub) < elfHdrSize {
return nil, info, fmt.Errorf("缺少 ELF 壳资产")
}
f, perr := elf.NewFile(bytes.NewReader(target))
if perr != nil {
return nil, info, fmt.Errorf("解析 ELF 失败: %w", perr)
}
if f.Class != elf.ELFCLASS64 {
return nil, info, &UnsupportedError{Kind: KindELF, Arch: "x86", Reason: "暂只支持 x86_64 ELF(32 位需另编壳)"}
}
if f.Machine != elf.EM_X86_64 {
return nil, info, &UnsupportedError{Kind: KindELF, Arch: elfArch(target), Reason: "暂只支持 x86_64 ELF"}
}
if len(target) < 0x40 {
return nil, info, fmt.Errorf("文件太小,不是有效 ELF")
}
// 现有 PT_LOAD 的文件末尾 / 内存末尾
var maxEnd, maxVEnd uint64
for _, p := range f.Progs {
if p.Type == elf.PT_LOAD {
if p.Off+p.Filesz > maxEnd {
maxEnd = p.Off + p.Filesz
}
if p.Vaddr+p.Memsz > maxVEnd {
maxVEnd = p.Vaddr + p.Memsz
}
}
}
phoff := binary.LittleEndian.Uint64(target[elfOffPhoff:])
entSize := uint64(binary.LittleEndian.Uint16(target[elfOffPhents:]))
phnum := uint64(binary.LittleEndian.Uint16(target[elfOffPhnum:]))
if entSize != 56 {
return nil, info, fmt.Errorf("phdr 项大小异常: %d", entSize)
}
if phoff+phnum*entSize > uint64(len(target)) {
return nil, info, fmt.Errorf("program header 表越界")
}
oldPhdrs := target[phoff : phoff+phnum*entSize]
newPhdrLen := int(phnum+1) * int(entSize)
body := make([]byte, newPhdrLen)
body = append(body, stub...)
hdrAt := newPhdrLen
cfgOff := len(stub) // 相对头基址
body = append(body, cfg...)
copy(body, oldPhdrs)
copy(body[hdrAt:hdrAt+4], "VELF")
binary.LittleEndian.PutUint32(body[hdrAt+4:], 1)
binary.LittleEndian.PutUint64(body[hdrAt+8:], uint64(len(stub)))
binary.LittleEndian.PutUint64(body[hdrAt+24:], uint64(cfgOff))
binary.LittleEndian.PutUint64(body[hdrAt+32:], uint64(len(cfg)))
binary.LittleEndian.PutUint64(body[hdrAt+40:], f.Entry)
newOff := alignUp(maxEnd, elfPageAlign)
newVA := alignUp(maxVEnd, elfPageAlign)
binary.LittleEndian.PutUint64(body[hdrAt+16:], newVA+uint64(hdrAt)+elfHdrSize)
// 追加的 phdr
np := body[int(phnum)*int(entSize):]
binary.LittleEndian.PutUint32(np[0:], uint32(elf.PT_LOAD))
binary.LittleEndian.PutUint32(np[4:], 5) // R|X
binary.LittleEndian.PutUint64(np[8:], newOff)
binary.LittleEndian.PutUint64(np[16:], newVA)
binary.LittleEndian.PutUint64(np[24:], newVA)
binary.LittleEndian.PutUint64(np[32:], uint64(len(body)))
binary.LittleEndian.PutUint64(np[40:], uint64(len(body)))
binary.LittleEndian.PutUint64(np[48:], elfPageAlign)
// PT_PHDR 指向新表
for i := uint64(0); i < phnum; i++ {
e := body[i*entSize:]
if binary.LittleEndian.Uint32(e[0:]) == uint32(elf.PT_PHDR) {
binary.LittleEndian.PutUint64(e[8:], newOff)
binary.LittleEndian.PutUint64(e[16:], newVA)
binary.LittleEndian.PutUint64(e[24:], newVA)
binary.LittleEndian.PutUint64(e[32:], uint64(newPhdrLen))
binary.LittleEndian.PutUint64(e[40:], uint64(newPhdrLen))
}
}
out = append([]byte{}, target...)
for uint64(len(out)) < newOff {
out = append(out, 0)
}
out = append(out, body...)
binary.LittleEndian.PutUint64(out[elfOffPhoff:], newOff)
binary.LittleEndian.PutUint16(out[elfOffPhnum:], uint16(phnum+1))
binary.LittleEndian.PutUint64(out[elfOffEntry:], newVA+uint64(hdrAt)+elfHdrSize)
info.Arch = "x64"
info.EntryOld = f.Entry
info.EntryNew = newVA + uint64(hdrAt) + elfHdrSize
info.SecRVA = newVA
info.SecSize = uint32(len(body))
info.OutSize = len(out)
info.OriginalSource = len(target)
info.Note = "ELF 壳:http 走内置 socket(域名走系统 DNS),https 走系统 curl(口令经 stdin,不进 argv)"
return out, info, nil
}
func alignUp(v, a uint64) uint64 { return (v + a - 1) / a * a }
+71
View File
@@ -0,0 +1,71 @@
package protect
import (
"bytes"
"debug/elf"
"encoding/binary"
"os"
"testing"
)
// 结构测试:注入后 ELF 仍可解析、入口被改到新段、phdr 表项增加
func TestPatchELFStructure(t *testing.T) {
src := "/bin/true"
raw, err := os.ReadFile(src)
if err != nil {
t.Skip("没有 /bin/true,跳过")
}
cfg := []byte(`{"api":"http://127.0.0.1:1/x","name":"t"}`)
out, info, err := PatchELF(raw, cfg)
if err != nil {
t.Fatalf("PatchELF 失败: %v", err)
}
f, err := elf.NewFile(bytes.NewReader(out))
if err != nil {
t.Fatalf("产物不是合法 ELF: %v", err)
}
if f.Entry != info.EntryNew {
t.Fatalf("入口未指到壳: entry=%#x 期望 %#x", f.Entry, info.EntryNew)
}
if len(out) <= len(raw) {
t.Fatalf("产物未变长: %d → %d", len(raw), len(out))
}
// phdr 项数 +1
rawN := binary.LittleEndian.Uint16(raw[elfOffPhnum:])
outN := binary.LittleEndian.Uint16(out[elfOffPhnum:])
if outN != rawN+1 {
t.Fatalf("phdr 项数应为 %d,实际 %d", rawN+1, outN)
}
// 头 magic 写在壳代码前 48 字节
va := info.EntryNew - elfHdrSize
var found bool
for _, p := range f.Progs {
if p.Type == elf.PT_LOAD && p.Vaddr <= va && va < p.Vaddr+p.Filesz {
found = true
}
}
if !found {
t.Fatalf("壳代码 vaddr %#x 不在任何 PT_LOAD 内", va)
}
if info.Arch != "x64" {
t.Fatalf("arch 应为 x64,实际 %s", info.Arch)
}
}
// 非 x86_64 必须给出明确缺口而不是乱改
func TestPatchELFRejectsOtherArch(t *testing.T) {
// 造一个 aarch64 的假 ELF 头(只要有 class/machine 就够触发拦截)
buf := make([]byte, 0x200)
copy(buf, "\x7fELF")
buf[4] = 2 // 64 位
buf[5] = 1 // little endian
binary.LittleEndian.PutUint16(buf[0x10:], 2) // ET_EXEC
binary.LittleEndian.PutUint16(buf[0x12:], 183) // EM_AARCH64
binary.LittleEndian.PutUint64(buf[0x20:], 0x40) // e_phoff
binary.LittleEndian.PutUint16(buf[0x36:], 56) // e_phentsize
binary.LittleEndian.PutUint16(buf[0x38:], 1) // e_phnum
if _, _, err := PatchELF(buf, []byte(`{"api":"http://1.1.1.1/x"}`)); err == nil {
t.Fatal("aarch64 应当被拒绝")
}
}
+289
View File
@@ -0,0 +1,289 @@
package protect
// 多平台识别:PE / APK / IPA / ELF / Mach-O
// 目前只有 PE 具备注入能力,其余格式在这里统一识别并给出明确的缺口说明,
// 避免上层只报“不是有效的 Windows 程序”这种含糊错误。
import (
"archive/zip"
"bytes"
"encoding/binary"
"fmt"
"io"
"path/filepath"
"strings"
)
// Kind 程序包类型
type Kind string
const (
KindPE Kind = "pe" // Windows PE (exe/dll)
KindAPK Kind = "apk" // Android 应用包
KindIPA Kind = "ipa" // iOS 应用包
KindELF Kind = "elf" // Linux 可执行
KindMachO Kind = "macho" // macOS / iOS 可执行
KindUnknown Kind = "unknown" // 认不出
)
// Detected 识别结果
type Detected struct {
Kind Kind // 类型
Arch string // x64 / x86 / arm64 / universal / ""
}
// Detect 按内容 + 文件名识别类型
func DetectFile(data []byte, name string) Detected {
if len(data) < 4 {
return Detected{Kind: KindUnknown}
}
// 保险:先看是不是 ELF / Mach-O 之类裸可执行
switch {
case bytes.HasPrefix(data, []byte{0x7f, 'E', 'L', 'F'}):
return Detected{Kind: KindELF, Arch: elfArch(data)}
case bytes.HasPrefix(data, []byte{0xcf, 0xfa, 0xed, 0xfe}),
bytes.HasPrefix(data, []byte{0xce, 0xfa, 0xed, 0xfe}),
bytes.HasPrefix(data, []byte{0xca, 0xfe, 0xba, 0xbe}):
return Detected{Kind: KindMachO, Arch: machoArch(data)}
case bytes.HasPrefix(data, []byte{'M', 'Z'}):
if a, err := detectPEArch(data); err == nil {
return Detected{Kind: KindPE, Arch: a}
}
return Detected{Kind: KindPE}
case bytes.HasPrefix(data, []byte{'P', 'K', 0x03, 0x04}):
return detectZipFamily(data, name)
}
// 有些 ipa/apk 前置注释或空字节,退回扩展名
switch strings.ToLower(filepath.Ext(name)) {
case ".apk":
return Detected{Kind: KindAPK, Arch: "universal"}
case ".ipa":
return Detected{Kind: KindIPA, Arch: "universal"}
case ".exe", ".dll", ".sys":
return Detected{Kind: KindPE}
}
return Detected{Kind: KindUnknown}
}
// detectZipFamily 区分 APK / IPA / 普通 zip
func detectZipFamily(data []byte, name string) Detected {
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
// 头部损坏的 zip 仍然按扩展名兜底
switch strings.ToLower(filepath.Ext(name)) {
case ".apk":
return Detected{Kind: KindAPK, Arch: "universal"}
case ".ipa":
return Detected{Kind: KindIPA, Arch: "universal"}
}
return Detected{Kind: KindUnknown}
}
var hasManifest, hasDex, hasPayload bool
for _, f := range zr.File {
n := f.Name
switch {
case n == "AndroidManifest.xml":
hasManifest = true
case strings.HasSuffix(n, ".dex"):
hasDex = true
case strings.HasPrefix(n, "Payload/") && strings.Contains(n, ".app/"):
hasPayload = true
}
if hasManifest && hasDex && hasPayload {
break
}
}
if hasManifest && hasDex {
return Detected{Kind: KindAPK, Arch: "universal"}
}
if hasPayload {
return Detected{Kind: KindIPA, Arch: "universal"}
}
return Detected{Kind: KindUnknown}
}
// detectPEArch 返回 x64 / x86
func detectPEArch(data []byte) (string, error) {
if len(data) < 0x40 {
return "", fmt.Errorf("too short")
}
off := int(binary.LittleEndian.Uint32(data[0x3C:0x40]))
if off+6 > len(data) {
return "", fmt.Errorf("bad e_lfanew")
}
if !bytes.Equal(data[off:off+4], []byte{'P', 'E', 0, 0}) {
return "", fmt.Errorf("no PE signature")
}
machine := binary.LittleEndian.Uint16(data[off+4 : off+6])
switch machine {
case 0x8664:
return "x64", nil
case 0x14c:
return "x86", nil
case 0xaa64:
return "arm64", nil
}
return "", fmt.Errorf("machine 0x%x", machine)
}
func elfArch(data []byte) string {
if len(data) < 20 {
return ""
}
m := binary.LittleEndian.Uint16(data[18:20])
switch m {
case 0x3E:
return "x64"
case 0x03:
return "x86"
case 0xB7:
return "arm64"
case 0x28:
return "armv7"
}
return ""
}
func machoArch(data []byte) string {
if len(data) < 8 {
return ""
}
cpu := binary.LittleEndian.Uint32(data[4:8])
switch cpu {
case 0x01000007:
return "x64"
case 0x0100000C:
return "arm64"
case 0x00000007:
return "x86"
case 0x0000000C:
return "armv7"
}
return ""
}
// SupportsProtect 当前环境能不能真注入该类型
func SupportsProtect(k Kind) bool {
return Injectable(k) == nil
}
// Injectable 返回 nil 表示可以注入,否则给出具体缺口
func Injectable(k Kind) error {
switch k {
case KindPE, KindELF:
// ELF 目前只有 x86_64 壳,架构细节在 PatchELF 里再判
return nil
case KindIPA:
if SignTools().Zsign == "" {
return &UnsupportedError{
Kind: KindIPA,
Arch: "universal",
Reason: "服务端缺少 zsign,无法注入 dylib 并重签 IPA",
Needs: []string{"镜像里放进 zsign(musl 静态版)"},
}
}
return nil
case KindAPK:
if miss := MissingTools(); len(miss) > 0 {
return &UnsupportedError{
Kind: KindAPK,
Arch: "universal",
Reason: "服务端缺少 Android 工具链:" + strings.Join(miss, "、"),
Needs: []string{"镜像里 apk add openjdk17-jre-headless apksigner zipalign apktool"},
}
}
return nil
}
return unsupportedFor(Detected{Kind: k})
}
// UnsupportedError 未支持类型的具体缺口,给用户可直接执行的信息
type UnsupportedError struct {
Kind Kind
Arch string
Reason string
Needs []string
}
func (e *UnsupportedError) Error() string {
var b strings.Builder
arch := e.Arch
if arch == "" {
arch = "未知架构"
}
fmt.Fprintf(&b, "%s 已识别(%s)", kindLabel(e.Kind), arch)
if e.Reason != "" {
b.WriteString(";")
b.WriteString(e.Reason)
}
if len(e.Needs) > 0 {
b.WriteString(";需要:")
b.WriteString(strings.Join(e.Needs, "、"))
}
return b.String()
}
func kindLabel(k Kind) string {
switch k {
case KindPE:
return "Windows PE"
case KindAPK:
return "Android APK"
case KindIPA:
return "iOS IPA"
case KindELF:
return "Linux ELF"
case KindMachO:
return "Mach-O"
}
return "未知格式"
}
// unsupportedFor 生成各类型的缺口说明
func unsupportedFor(info Detected) *UnsupportedError {
switch info.Kind {
case KindAPK:
return &UnsupportedError{
Kind: info.Kind,
Arch: info.Arch,
Reason: "APK 注入要改 AndroidManifest 的 application 节点并追加验证 dex,改完必须重新签名才能安装",
Needs: []string{"服务端 apksigner(依赖 JDK)与签名证书(keystore)", "验证壳 dex(由 HookApplication.java 编译)"},
}
case KindIPA:
return &UnsupportedError{
Kind: info.Kind,
Arch: info.Arch,
Reason: "IPA 注入要往 Mach-O 加 LC_LOAD_DYLIB 并签名,未重签的包在真机上装不上",
Needs: []string{"iOS 证书(.p12)+ 描述文件(.mobileprovision)", "codesign/ldid 与 dylib 壳"},
}
case KindELF:
return &UnsupportedError{
Kind: info.Kind,
Arch: info.Arch,
Reason: "ELF 需要改入口 + 注入 SO,且要处理 PIE/RELRO",
}
case KindMachO:
return &UnsupportedError{
Kind: info.Kind,
Arch: info.Arch,
Reason: "Mach-O 需要加 LC_LOAD_DYLIB 并重签",
Needs: []string{"macOS/iOS 签名证书"},
}
}
return &UnsupportedError{Kind: info.Kind, Arch: info.Arch, Reason: "无法识别的容器格式"}
}
// readZipEntry 读取 zip 内某个条目的全部内容(大小受限)
func readZipEntry(zr *zip.Reader, name string) ([]byte, error) {
for _, f := range zr.File {
if f.Name == name {
rc, err := f.Open()
if err != nil {
return nil, err
}
defer rc.Close()
return io.ReadAll(io.LimitReader(rc, 64<<20))
}
}
return nil, fmt.Errorf("entry %s not found", name)
}
+79
View File
@@ -0,0 +1,79 @@
package protect
import (
"archive/zip"
"bytes"
"os"
"path/filepath"
"testing"
)
// 造一个只含指定文件名的 zip,用于类型识别
func fakeZip(names ...string) []byte {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, n := range names {
w, _ := zw.Create(n)
w.Write([]byte("x"))
}
zw.Close()
return buf.Bytes()
}
func TestDetectFile(t *testing.T) {
cases := []struct {
name string
data []byte
want Kind
arch string
}{
{"a.apk", fakeZip("AndroidManifest.xml", "classes.dex", "res/"), KindAPK, "universal"},
{"a.ipa", fakeZip("Payload/App.app/Info.plist", "Payload/App.app/App"), KindIPA, "universal"},
{"a.zip", fakeZip("readme.txt"), KindUnknown, ""},
{"a.elf", append([]byte{0x7f, 'E', 'L', 'F', 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0x3e, 0}, []byte("rest")...), KindELF, "x64"},
{"a.macho", []byte{0xcf, 0xfa, 0xed, 0xfe, 0x07, 0x00, 0x00, 0x01}, KindMachO, "x64"},
}
for _, c := range cases {
got := DetectFile(c.data, c.name)
if got.Kind != c.want {
t.Fatalf("%s: kind=%s 期望 %s", c.name, got.Kind, c.want)
}
if c.arch != "" && got.Arch != c.arch {
t.Fatalf("%s: arch=%s 期望 %s", c.name, got.Arch, c.arch)
}
}
}
func TestDetectPE(t *testing.T) {
// 用仓库自带的真 PE 样本(测试资产),没有就跳过
candidates := []string{
"/tmp/vt/v64.exe",
filepath.Join(os.Getenv("HOME"), "victim.exe"),
}
var data []byte
for _, p := range candidates {
if b, err := os.ReadFile(p); err == nil {
data = b
break
}
}
if data == nil {
t.Skip("没有可用的 PE 样本")
}
got := DetectFile(data, "x.exe")
if got.Kind != KindPE {
t.Fatalf("kind=%s 期望 pe", got.Kind)
}
if got.Arch != "x64" && got.Arch != "x86" {
t.Fatalf("arch=%s 异常", got.Arch)
}
}
func TestUnsupportedKindsRejected(t *testing.T) {
apk := fakeZip("AndroidManifest.xml", "classes.dex")
if _, _, err := PatchAuto(apk, []byte("{}"), "a.apk"); err == nil {
t.Fatal("APK 应当返回明确的不支持错误")
} else if _, ok := err.(*UnsupportedError); !ok {
t.Fatalf("错误类型应为 *UnsupportedError,实际 %T: %v", err, err)
}
}
+554
View File
@@ -0,0 +1,554 @@
package protect
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"encoding/asn1"
"encoding/pem"
"fmt"
"strings"
"time"
"software.sslmate.com/src/go-pkcs12"
)
// PFXIdentity 一套「私钥 + 对应证书」,也就是一个真正的签名身份。
type PFXIdentity struct {
Index int `json:"index"`
Subject string `json:"subject"`
NotAfter time.Time `json:"not_after"`
Expired bool `json:"expired"`
Usage CertUsage `json:"usage"` // 能签什么:应用 / 驱动 / 两者
}
// PFXInfo 一个证书文件里到底装了什么。
//
// 现实里这类文件有三种形态,必须区分清楚:
// 1. 单身份:一张叶子证书 + 它的私钥(最常见)
// 2. 链式:叶子证书 + 它的私钥 + 中间 CA / 根证书(证书多但私钥只有一把)
// —— 这种是好事,签名时会带完整链,验签更容易过
// 3. 多身份:好几套「私钥+证书」混在一个文件里
// —— 签名工具只会用其中一套,所以上传时按套拆成多条记录
type PFXInfo struct {
CertCount int `json:"cert_count"` // 证书总数(含链上的 CA)
KeyCount int `json:"key_count"` // 私钥总数(= 可签名身份数)
Identities []PFXIdentity `json:"identities"` // 每套可签名身份
LooseCerts int `json:"loose_certs"` // 配不到私钥的证书(链)
Signing PFXIdentity `json:"signing"` // 文件里第一套,工具默认用它
Note string `json:"note"`
Syntax string `json:"syntax"` // pfx / pem / pkcs7 / der-cert / der-key
}
// PFXError 带人话原因的解析错误。
// 上传接口把 Reason、Hint 直接回给用户,不要再让人猜「是不是口令错了」。
type PFXError struct {
Reason string // 到底哪里不对
Hint string // 下一步该做什么
Detail string // 原始错误,便于排查
}
func (e *PFXError) Error() string {
s := e.Reason
if e.Detail != "" {
s += "(" + e.Detail + ")"
}
return s
}
// SplitIdentity 一套可签名的身份,以及把它单独编码成 pfx 的结果。
type SplitIdentity struct {
Index int
Subject string
NotAfter time.Time
Expired bool
ChainLen int // 附带的链上证书张数
PFX []byte // 只有这一套私钥+证书(+链)的 pfx,口令同原文件
}
// material 解析出来的原始材料
type material struct {
certs []*x509.Certificate
keys []interface{}
syntax string
pw string // 实际生效的口令(拆分重打包时要沿用)
}
// loadMaterial 把上传的字节流解成「证书列表 + 私钥列表」。
//
// 容错顺序很关键,每一步失败都要能说出人话:
// 1. PEM 文本(不少人导出的是 .pem/.crt/.key,或把 pfx 存成了文本)→ 直接读
// 2. PKCS#12(真正的 pfx/p12)→ 依次试 原口令 / 去首尾空白口令 / 空口令
// 3. 都解不开 → 按文件魔数判断它到底是什么,给出具体原因
func loadMaterial(data []byte, password string) (*material, error) {
if len(data) == 0 {
return nil, &PFXError{Reason: "上传的文件是空的"}
}
trimmed := bytes.TrimLeft(data, "\xef\xbb\xbf \t\r\n")
// ① PEM 文本
if bytes.HasPrefix(trimmed, []byte("-----BEGIN")) {
m := &material{syntax: "pem", pw: password}
var encryptedKey bool
rest := trimmed
for {
var blk *pem.Block
blk, rest = pem.Decode(rest)
if blk == nil {
break
}
switch blk.Type {
case "CERTIFICATE":
if c, err := x509.ParseCertificate(blk.Bytes); err == nil {
m.certs = append(m.certs, c)
}
case "PRIVATE KEY", "RSA PRIVATE KEY", "EC PRIVATE KEY":
if k, err := parseAnyPrivateKey(blk.Bytes); err == nil {
m.keys = append(m.keys, k)
}
case "ENCRYPTED PRIVATE KEY":
encryptedKey = true
}
}
if encryptedKey && len(m.keys) == 0 {
return nil, &PFXError{
Reason: "这是 PEM 格式的加密私钥,当前只支持未加密的 PEM 或 pfx/p12",
Hint: "在导出界面选「导出为 PFX/P12」并设口令,上传那个文件即可",
}
}
if len(m.certs) == 0 && len(m.keys) == 0 {
return nil, &PFXError{
Reason: "这是 PEM 文本,但里面没有可用的证书或私钥",
Hint: "换导出工具给出的 .pfx/.p12 重试",
}
}
return m, nil
}
// ② PKCS#12:口令可能带首尾空格或全角,逐个候选试
cands := []string{password}
if t := strings.TrimSpace(password); t != password {
cands = append(cands, t)
}
if password != "" {
cands = append(cands, "")
}
// 逐个候选口令试。注意要分开记两类错误:
// - 口令错(decryption password incorrect)
// - 结构问题(比如 pfx 里根本没有 keyBag)
// 最后若存在结构问题,优先报结构问题——否则「只有证书的 pfx」会被
// 说成「口令不对」,人照着改口令永远改不好。
var pwErr, structErr error
for _, pw := range cands {
certs, keys, err := decodePKCS12(data, pw)
if err == nil {
return &material{certs: certs, keys: keys, syntax: "pfx", pw: pw}, nil
}
if isPasswordError(err) {
pwErr = err
} else if structErr == nil {
structErr = err
}
}
lastErr := structErr
if lastErr == nil {
lastErr = pwErr
}
// ③ 全试过了还不行:先判断它到底是什么,别一句「解析失败」了事
switch sniffKind(data) {
case "pkcs7":
return nil, &PFXError{
Reason: "这是 PKCS#7 / .cer 证书文件,里面只有证书、没有私钥,签不了名",
Hint: "签名必须用带私钥的 .pfx/.p12;私钥若在别处,请把证书和私钥一起导出成 pfx",
}
case "der-cert":
return nil, &PFXError{
Reason: "这是 DER 格式的单张证书(.cer/.crt),没有私钥,签不了名",
Hint: "导出带私钥的 .pfx/.p12 再上传",
}
case "der-key":
return nil, &PFXError{
Reason: "这是单独的私钥文件,缺少证书,签不了名",
Hint: "把证书和私钥一起导出成 .pfx/.p12",
}
case "zip":
return nil, &PFXError{Reason: "上传的是压缩包,不是证书文件", Hint: "解压后上传里面的 .pfx/.p12"}
case "pfx":
msg := ""
if structErr != nil {
msg = structErr.Error()
}
if strings.Contains(msg, "safe bag") || strings.Contains(msg, "authenticated safe") ||
strings.Contains(msg, "exactly one certificate") {
return nil, &PFXError{
Reason: "这个 pfx 里只有证书、没有私钥,签不了名",
Hint: "重新导出时勾上「导出私钥」,或用 openssl 检查:openssl pkcs12 -info -in 文件",
Detail: structErr.Error(),
}
}
if structErr == nil && pwErr != nil {
return nil, &PFXError{
Reason: "口令不对:pfx 的完整性校验没过",
Hint: "注意大小写与全角半角;若导出时单独设了口令,请用那个口令而不是登录口令",
Detail: lastErr.Error(),
}
}
return nil, &PFXError{
Reason: "这个 pfx 用的加密方式当前解不开(少见,通常是硬件令牌私钥或非常规导出参数)",
Hint: "用 openssl 重新导出:openssl pkcs12 -in 原.pfx -nodes -out tmp.pem 再 openssl pkcs12 -export -in tmp.pem -out 新.pfx",
Detail: lastErr.Error(),
}
}
return nil, &PFXError{
Reason: "文件不是 pfx/p12 格式",
Hint: "支持 .pfx/.p12(PKCS#12)以及含证书+私钥的 PEM;.cer/.crt 这类纯证书无法签名",
Detail: lastErr.Error(),
}
}
// decodePKCS12 用指定口令解 PKCS#12
func decodePKCS12(data []byte, password string) ([]*x509.Certificate, []interface{}, error) {
blocks, err := pkcs12.ToPEM(data, password)
if err != nil {
return nil, nil, err
}
var certs []*x509.Certificate
var keys []interface{}
for _, b := range blocks {
switch b.Type {
case "CERTIFICATE":
if c, e := x509.ParseCertificate(b.Bytes); e == nil {
certs = append(certs, c)
}
case "PRIVATE KEY", "RSA PRIVATE KEY", "EC PRIVATE KEY":
// go-pkcs12 的 ToPEM 把 RSA 私钥导成 PKCS#1、ECDSA 导成 SEC1,
// 但 block.Type 统一是 "PRIVATE KEY" —— 三种编码都要试一遍,
// 否则会把「有私钥」的 pfx 误判成「只有证书」。
if k, e := parseAnyPrivateKey(b.Bytes); e == nil {
keys = append(keys, k)
}
}
}
return certs, keys, nil
}
// sniffKind 按魔数判断文件到底是什么,用于给出准确的失败原因
func sniffKind(data []byte) string {
t := bytes.TrimLeft(data, "\xef\xbb\xbf \t\r\n")
if len(t) == 0 {
return "empty"
}
if bytes.HasPrefix(t, []byte("-----BEGIN")) {
return "pem"
}
if bytes.HasPrefix(t, []byte("PK\x03\x04")) || bytes.HasPrefix(t, []byte("Rar!")) {
return "zip"
}
if len(t) < 16 || t[0] != 0x30 {
return "unknown"
}
// PKCS#12 外层:SEQUENCE { INTEGER version, ContentInfo }
var pfx struct {
Version int
AuthSafe struct {
ContentType asn1.ObjectIdentifier
Content asn1.RawValue `asn1:"optional,tag:0"`
}
}
if _, err := asn1.Unmarshal(t, &pfx); err == nil && pfx.AuthSafe.ContentType != nil {
switch pfx.AuthSafe.ContentType.String() {
case "1.2.840.113549.1.7.1": // id-data —— PFX 的外壳
return "pfx"
case "1.2.840.113549.1.7.2": // id-signedData —— PKCS#7
return "pkcs7"
}
}
// PKCS#7 的 OID 常出现在开头,先认它再试单证书
if bytes.Contains(t[:minInt(64, len(t))], []byte{0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07}) {
return "pkcs7"
}
if _, err := x509.ParseCertificate(t); err == nil {
return "der-cert"
}
if _, err := x509.ParsePKCS1PrivateKey(t); err == nil {
return "der-key"
}
if _, err := x509.ParsePKCS8PrivateKey(t); err == nil {
return "der-key"
}
return "unknown"
}
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
// ParsePFX 解析上传的证书文件,给界面用:能不能签、有几套身份、到期时间。
//
// 关键点:不能简单取「第一个证书」当签名证书——链式文件里第一个
// 可能是中间 CA。这里按「公钥与私钥配对」来认叶子证书。
func ParsePFX(data []byte, password string) (PFXInfo, error) {
var info PFXInfo
m, err := loadMaterial(data, password)
if err != nil {
return info, err
}
info.Syntax = m.syntax
info.CertCount = len(m.certs)
info.KeyCount = len(m.keys)
matched := matchCerts(m.certs, m.keys)
info.LooseCerts = len(m.certs) - len(matched)
for i, c := range matched {
info.Identities = append(info.Identities, PFXIdentity{
Index: i + 1,
Subject: c.Subject.String(),
NotAfter: c.NotAfter,
Expired: c.NotAfter.Before(time.Now()),
Usage: ClassifyUsage(c),
})
}
// 保持文件内顺序,不要按到期时间重排:osslsigncode(OpenSSL PKCS12_parse)
// 取的是文件里的第一套私钥+证书,报告必须和它一致,否则说一套签一套。
switch {
case len(info.Identities) > 0:
info.Signing = info.Identities[0]
case len(m.certs) > 0:
c := m.certs[0]
info.Signing = PFXIdentity{Subject: c.Subject.String(), NotAfter: c.NotAfter,
Expired: c.NotAfter.Before(time.Now())}
}
switch {
case info.KeyCount == 0:
info.Note = "该文件里只有证书、没有私钥,无法用于签名"
case info.KeyCount == 1 && info.CertCount > 1:
info.Note = fmt.Sprintf("含 %d 张证书(1 套私钥 + %d 张链上证书),签名会带完整证书链", info.CertCount, info.LooseCerts)
case info.KeyCount > 1:
info.Note = fmt.Sprintf("含 %d 套可签名身份(私钥 %d 把),云端加密时可任选其中一套",
len(matched), info.KeyCount)
}
return info, nil
}
// SplitPFX 把文件里的每套「私钥+证书」拆成独立的单身份 pfx。
//
// 为什么需要拆:osslsigncode / OpenSSL 的 PKCS12_parse 只会取文件里第一套,
// 想用第二套签名就必须给它一个只含第二套的文件。拆的时候顺带把真正的
// 链证书(配不到私钥的那些)带进去,签名产物仍然有完整链。
func SplitPFX(data []byte, password string) ([]SplitIdentity, error) {
return SplitPFXWithPassword(data, password, "") // 空 = 沿用原口令
}
// SplitPFXWithPassword 同 SplitPFX,但可以用 newPassword 重新设置导出文件的口令。
// 批量导出时用户会指定一个统一口令,这里负责重打包。
func SplitPFXWithPassword(data []byte, password, newPassword string) ([]SplitIdentity, error) {
m, err := loadMaterial(data, password)
if err != nil {
return nil, err
}
if len(m.keys) == 0 {
return nil, &PFXError{
Reason: "这个文件里只有证书、没有私钥,签不了名",
Hint: "请导出带私钥的 .pfx/.p12",
}
}
// 给每把私钥找证书,记下哪些证书是「身份证书」
type pairing struct {
key interface{}
cert *x509.Certificate
}
var pairs []pairing
used := make(map[int]bool)
for _, k := range m.keys {
pub, ok := publicOf(k)
if !ok {
continue
}
for i, c := range m.certs {
if used[i] {
continue
}
if publicEqual(pub, c.PublicKey) {
pairs = append(pairs, pairing{key: k, cert: c})
used[i] = true
break
}
}
}
if len(pairs) == 0 {
return nil, &PFXError{
Reason: "私钥与证书不匹配:文件里的私钥找不到对应证书",
Hint: "确认证书与私钥来自同一次导出;重新导出 pfx 再试",
}
}
// 链 = 没有配到私钥的证书(中间 CA / 根)。
// 不能把「另一套身份的叶子证书」塞进链里 —— 那会让产物证书表里混进
// 另一个 CN,看起来像被两家都签过。
var chain []*x509.Certificate
for i, c := range m.certs {
if !used[i] {
chain = append(chain, c)
}
}
outPW := m.pw
if newPassword != "" {
outPW = newPassword
}
var out []SplitIdentity
for _, p := range pairs {
blob, eerr := pkcs12.Modern.Encode(p.key, p.cert, chain, outPW)
if eerr != nil {
// AES 编码失败时退到兼容模式(老工具只认 RC2/3DES)
blob, eerr = pkcs12.LegacyRC2.Encode(p.key, p.cert, chain, outPW)
}
if eerr != nil {
return nil, &PFXError{
Reason: fmt.Sprintf("重新打包第 %d 套证书失败", len(out)+1),
Detail: eerr.Error(),
}
}
out = append(out, SplitIdentity{
Index: len(out) + 1,
Subject: p.cert.Subject.String(),
NotAfter: p.cert.NotAfter,
Expired: p.cert.NotAfter.Before(time.Now()),
ChainLen: len(chain),
PFX: blob,
})
}
return out, nil
}
// matchCerts 找出「有对应私钥」的证书,保持文件内顺序
func matchCerts(certs []*x509.Certificate, keys []interface{}) []*x509.Certificate {
var out []*x509.Certificate
usedKey := make(map[int]bool)
for _, c := range certs {
for i, k := range keys {
if usedKey[i] {
continue
}
pub, ok := publicOf(k)
if ok && publicEqual(pub, c.PublicKey) {
out = append(out, c)
usedKey[i] = true
break
}
}
}
return out
}
// publicOf 取任意私钥对象的公钥部分
func publicOf(key interface{}) (interface{}, bool) {
switch k := key.(type) {
case *rsa.PrivateKey:
return &k.PublicKey, true
case *ecdsa.PrivateKey:
return &k.PublicKey, true
case ed25519.PrivateKey:
return k.Public(), true
case crypto.Signer:
return k.Public(), true
}
return nil, false
}
// publicEqual 比较两个公钥是否同一把
func publicEqual(a, b interface{}) bool {
type equaler interface{ Equal(crypto.PublicKey) bool }
if eq, ok := a.(equaler); ok {
if pk, ok2 := b.(crypto.PublicKey); ok2 {
return eq.Equal(pk)
}
}
return false
}
// parseAnyPrivateKey 依次尝试 PKCS#8 / PKCS#1 / SEC1 三种私钥编码
func parseAnyPrivateKey(der []byte) (interface{}, error) {
if k, err := x509.ParsePKCS8PrivateKey(der); err == nil {
return k, nil
}
if k, err := x509.ParsePKCS1PrivateKey(der); err == nil {
return k, nil
}
if k, err := x509.ParseECPrivateKey(der); err == nil {
return k, nil
}
return nil, fmt.Errorf("无法识别的私钥编码")
}
// isPasswordError 判断错误是不是「口令不对」
func isPasswordError(err error) bool {
if err == nil {
return false
}
if err == pkcs12.ErrIncorrectPassword || err == pkcs12.ErrDecryption {
return true
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "password") || strings.Contains(msg, "mac verify")
}
// IdentityDetail 一套身份的全部细节(含证书对象,供吊销检测等使用)
type IdentityDetail struct {
Index int
Subject string
NotAfter time.Time
Expired bool
Cert *x509.Certificate
Issuer *x509.Certificate // 包里能找到签发者就填,找不到为 nil
Revoke RevokeInfo // 未检测时 Status = not_checked
Ban RevokeInfo
Usage CertUsage // 应用 / 驱动
}
// ParseIdentitiesFull 解析出每套身份,并把包里能找到的签发者一并配上。
func ParseIdentitiesFull(data []byte, password string) ([]IdentityDetail, error) {
m, err := loadMaterial(data, password)
if err != nil {
return nil, err
}
matched := matchCerts(m.certs, m.keys)
var out []IdentityDetail
for i, c := range matched {
d := IdentityDetail{
Index: i + 1,
Subject: c.Subject.String(),
NotAfter: c.NotAfter,
Expired: c.NotAfter.Before(time.Now()),
Cert: c,
Revoke: RevokeInfo{Status: RevokeNotChecked},
Ban: RevokeInfo{Status: RevokeNotChecked},
Usage: ClassifyUsage(c),
}
// 在包内同一批证书里找签发者:能验通签名的那张就是
for _, cand := range m.certs {
if cand.Equal(c) {
continue
}
if err := c.CheckSignatureFrom(cand); err == nil {
d.Issuer = cand
break
}
}
out = append(out, d)
}
return out, nil
}
+62
View File
@@ -0,0 +1,62 @@
package protect
import (
"os"
"testing"
)
// 用真实文件验证三种 pfx 形态的识别结果。
// 依赖 /tmp/pfxlab 下的样本(单证书 / 链式 / 多身份),缺失则跳过。
func TestParsePFXShapes(t *testing.T) {
cases := []struct {
file string
pw string
certCount int
keyCount int
wantSubstr string
}{
{"/tmp/pfxlab/single.pfx", "testpass123", 1, 1, "Leaf Signer"},
{"/tmp/pfxlab/chain.pfx", "testpass123", 3, 1, "Leaf Signer"},
{"/tmp/pfxlab/multi.p12", "testpass123", 2, 2, "Signer"},
}
for _, c := range cases {
data, err := os.ReadFile(c.file)
if err != nil {
t.Logf("跳过 %s(样本不存在)", c.file)
continue
}
info, err := ParsePFX(data, c.pw)
if err != nil {
t.Fatalf("%s 解析失败: %v", c.file, err)
}
t.Logf("%s → 证书 %d 张 / 私钥 %d 把 / 身份 %d 套 / 实际签名=%q / 说明=%q",
c.file, info.CertCount, info.KeyCount, len(info.Identities), info.Signing.Subject, info.Note)
if info.CertCount != c.certCount {
t.Errorf("%s 证书数 = %d, 期望 %d", c.file, info.CertCount, c.certCount)
}
if info.KeyCount != c.keyCount {
t.Errorf("%s 私钥数 = %d, 期望 %d", c.file, info.KeyCount, c.keyCount)
}
if info.Signing.Subject == "" {
t.Errorf("%s 没认到签名证书", c.file)
}
}
}
// 只有证书没有私钥的文件必须被标出来(不能用它签名)
func TestParsePFXCertOnly(t *testing.T) {
data, err := os.ReadFile("/tmp/pfxlab/certonly.pfx")
if err != nil {
t.Skip("样本不存在")
}
info, err := ParsePFX(data, "testpass123")
if err != nil {
// 有些实现直接报错,也算识别出来了
t.Logf("cert-only 直接报错(可接受): %v", err)
return
}
t.Logf("cert-only → 证书 %d / 私钥 %d / 说明=%q", info.CertCount, info.KeyCount, info.Note)
if info.KeyCount != 0 {
t.Errorf("私钥数应为 0,实得 %d", info.KeyCount)
}
}
+532
View File
@@ -0,0 +1,532 @@
// Package protect:服务端给 PE 注入验证壳(改入口 + 内嵌壳 DLL + 双层 CRC32)
//
// 产物结构:原 exe 追加 .vfy 节 = [48B 头][引导 blob][壳 DLL][配置 JSON]
// 入口指向 .vfy 内的引导代码;引导代码反射加载 DLL(零落盘)。
package protect
import (
"bytes"
"debug/pe"
"embed"
"encoding/binary"
"fmt"
"hash/crc32"
"os"
"path/filepath"
"strings"
"time"
"verification-platform-backend/internal/model"
)
//go:embed assets/blob64.bin assets/blob32.bin assets/shell64.bin assets/shell32.bin assets/shell64_dui.bin
var assets embed.FS
const (
hdrSize = 48
crcOff = 36
secName = ".vfy"
shellVer = 8
secAttrib = 0x60000020 // CODE | EXECUTE | READ
)
// ShellThemes 可选的验证界面皮肤。classic = 原 Direct2D 壳,其余是 DuiLib 壳
var ShellThemes = map[string]string{
"classic": "经典(Direct2D 原版)",
"dark": "深色 · 竖排紧凑",
"light": "浅色 · 办公风",
"industrial": "工业蓝 · 设备授权",
"compact": "极简横幅 · 单行激活",
"split": "左右分栏 · 品牌竖栏",
"card": "宽扁卡片 · 双列说明",
"terminal": "终端风 · 命令行",
}
// ShellThemeOrder 主题的展示顺序(报错文案、前端下拉都按这个来)
var ShellThemeOrder = []string{"classic", "dark", "light", "industrial", "compact", "split", "card", "terminal"}
// ShellThemeList 返回「键=显示名」的有序切片,给前端/文档用
func ShellThemeList() []map[string]string {
out := make([]map[string]string, 0, len(ShellThemeOrder))
for _, k := range ShellThemeOrder {
out = append(out, map[string]string{"key": k, "label": ShellThemes[k]})
}
return out
}
// NormalizeTheme 校验并归一化主题名
func NormalizeTheme(theme string) string {
t := strings.ToLower(strings.TrimSpace(theme))
if t == "" {
return "classic"
}
if _, ok := ShellThemes[t]; ok {
return t
}
return ""
}
// Assets 取出指定架构的 blob 与壳 DLL(classic 版)
func Assets(arch string) (blob, dll []byte, err error) {
return AssetsThemed(arch, "classic")
}
// AssetsThemed 按主题取壳:DuiLib 版只有 x64,x86 仍回落到 classic
func AssetsThemed(arch, theme string) (blob, dll []byte, err error) {
var bp, dp string
switch arch {
case "x64":
bp, dp = "assets/blob64.bin", "assets/shell64.bin"
// DuiLib 壳只有 64 位构建
if theme != "" && theme != "classic" {
dp = "assets/shell64_dui.bin"
}
case "x86":
bp, dp = "assets/blob32.bin", "assets/shell32.bin"
default:
return nil, nil, fmt.Errorf("不支持的架构: %s", arch)
}
blob, err = assets.ReadFile(bp)
if err != nil {
return nil, nil, err
}
dll, err = assets.ReadFile(dp)
if err != nil {
return nil, nil, err
}
return blob, dll, nil
}
// HasVfy 判断 PE 里是不是已经有 .vfy 节(已被加过壳)。
// 二次加壳会在文件里留下两个 .vfy:旧壳的 cfg 指向老服务器、白占几百 KB,
// 目标机跳的却是新节,排查时极易被旧头误导,所以入口直接挡掉。
func HasVfy(target []byte) bool {
f, err := pe.NewFile(bytes.NewReader(target))
if err != nil {
return false
}
defer f.Close()
for _, s := range f.Sections {
if strings.HasPrefix(s.Name, secName) {
return true
}
}
return false
}
// DetectArch 兼容旧调用:只接受 PE,返回 x64/x86
func DetectArch(target []byte) (string, error) {
info := DetectFile(target, "")
if info.Kind != KindPE {
return "", unsupportedFor(info)
}
if info.Arch == "" {
return "", fmt.Errorf("无法识别的 PE 架构")
}
return info.Arch, nil
}
// Patch 把验证壳注入 target(按类型分发;目前只有 PE 具备注入实现)
func Patch(target, cfg []byte, arch string) (out []byte, info Info, err error) {
return PatchSigned(target, cfg, arch, false)
}
// PatchSigned signed=true 时写 flags.bit1 并留空 crcFile(供 Authenticode 重签)
func PatchSigned(target, cfg []byte, arch string, signed bool) (out []byte, info Info, err error) {
return PatchSignedThemed(target, cfg, arch, signed, "classic")
}
// PatchSignedThemed 同 PatchSigned,并指定验证界面主题
func PatchSignedThemed(target, cfg []byte, arch string, signed bool, theme string) (out []byte, info Info, err error) {
if arch == "" {
return nil, info, fmt.Errorf("缺少目标架构")
}
if theme == "" {
theme = "classic"
}
blob, dll, err := AssetsThemed(arch, theme)
if err != nil {
return nil, info, err
}
return patchWith(target, blob, dll, cfg, signed)
}
// PatchAuto 自动识别类型后注入;非 PE 返回 *UnsupportedError
func PatchAuto(target, cfg []byte, name string) (out []byte, info Info, err error) {
return PatchAutoSigned(target, cfg, name, false)
}
// PatchAutoSigned 自动识别类型并注入,signed 仅对 PE 有效
func PatchAutoSignedThemed(target, cfg []byte, name string, signed bool, theme string) (out []byte, info Info, err error) {
arch, err := DetectArch(target)
if err != nil {
return nil, info, err
}
out, info, err = PatchSignedThemed(target, cfg, arch, signed, theme)
if err != nil {
return nil, info, err
}
info.Arch = arch
return out, info, nil
}
func PatchAutoSigned(target, cfg []byte, name string, signed bool) (out []byte, info Info, err error) {
det := DetectFile(target, name)
switch det.Kind {
case KindPE:
return PatchSigned(target, cfg, det.Arch, signed)
case KindELF:
return PatchELF(target, cfg)
}
return nil, info, unsupportedFor(det)
}
// Info 打包结果摘要
type Info struct {
Arch string
EntryOld uint64
EntryNew uint64
SecRVA uint64
SecSize uint32
CrcVfy uint32
CrcFile uint32
OutSize int
OriginalSource int
Note string // 非 PE 的补充说明(例如 APK 重签信息)
}
func patchWith(raw, blob, dll, cfg []byte, signed bool) ([]byte, Info, error) {
var info Info
f, err := pe.NewFile(bytes.NewReader(raw))
if err != nil {
return nil, info, fmt.Errorf("解析 PE: %w", err)
}
is64 := f.Machine == pe.IMAGE_FILE_MACHINE_AMD64
is32 := f.Machine == pe.IMAGE_FILE_MACHINE_I386
if !is64 && !is32 {
return nil, info, fmt.Errorf("不支持的架构 machine=0x%x", f.Machine)
}
info.Arch = map[bool]string{true: "x64", false: "x86"}[is64]
info.OriginalSource = len(raw)
peOff := int(binary.LittleEndian.Uint32(raw[0x3C:0x40])) + 4 + 20
var numSections uint16
var sizeOfHeaders, fileAlign, sectAlign, entryRVA uint32
if is64 {
oh := f.OptionalHeader.(*pe.OptionalHeader64)
numSections, sizeOfHeaders = f.FileHeader.NumberOfSections, oh.SizeOfHeaders
fileAlign, sectAlign, entryRVA = oh.FileAlignment, oh.SectionAlignment, oh.AddressOfEntryPoint
} else {
oh := f.OptionalHeader.(*pe.OptionalHeader32)
numSections, sizeOfHeaders = f.FileHeader.NumberOfSections, oh.SizeOfHeaders
fileAlign, sectAlign, entryRVA = oh.FileAlignment, oh.SectionAlignment, oh.AddressOfEntryPoint
}
if fileAlign == 0 {
fileAlign = 0x200
}
if sectAlign == 0 {
sectAlign = 0x1000
}
var maxEnd, maxRVAEnd uint32
for _, s := range f.Sections {
if end := s.Offset + s.Size; end > maxEnd {
maxEnd = end
}
for _, e := range []uint32{s.VirtualAddress + s.VirtualSize, s.VirtualAddress + s.Size} {
if e > maxRVAEnd {
maxRVAEnd = e
}
}
}
newFileOff := align(maxEnd, fileAlign)
newRVA := align(maxRVAEnd, sectAlign)
shOff := uint32(peOff) + uint32(optSize(is64)) + uint32(numSections)*40
if shOff+40 > sizeOfHeaders {
return nil, info, fmt.Errorf("头部空间不足(SizeOfHeaders=0x%x)", sizeOfHeaders)
}
hdr := make([]byte, hdrSize)
copy(hdr[0:4], []byte("VFY4"))
binary.LittleEndian.PutUint32(hdr[4:], 4)
dllOff := uint32(hdrSize) + uint32(len(blob))
cfgOff := dllOff + uint32(len(dll))
binary.LittleEndian.PutUint32(hdr[8:], dllOff)
binary.LittleEndian.PutUint32(hdr[12:], uint32(len(dll)))
binary.LittleEndian.PutUint32(hdr[16:], cfgOff)
binary.LittleEndian.PutUint32(hdr[20:], uint32(len(cfg)))
binary.LittleEndian.PutUint32(hdr[24:], entryRVA)
binary.LittleEndian.PutUint32(hdr[28:], uint32(len(blob)))
flags := uint32(0)
if signed {
flags |= 2 // bit1:已签名构建,壳侧跳过整文件 CRC
}
binary.LittleEndian.PutUint32(hdr[32:], flags)
var sec bytes.Buffer
sec.Write(hdr)
sec.Write(blob)
sec.Write(dll)
sec.Write(cfg)
sectionData := sec.Bytes()
binary.LittleEndian.PutUint32(sectionData[crcOff:], 0)
binary.LittleEndian.PutUint32(sectionData[crcOff+4:], 0)
crcV := crcSkip(sectionData[:crcOff], sectionData[crcOff+8:])
binary.LittleEndian.PutUint32(sectionData[crcOff:], crcV)
padded := make([]byte, align(uint32(len(sectionData)), fileAlign))
copy(padded, sectionData)
out := make([]byte, 0, int(newFileOff)+len(padded))
out = append(out, raw...)
for uint32(len(out)) < newFileOff {
out = append(out, 0)
}
out = append(out, padded...)
sh := make([]byte, 40)
copy(sh[0:8], secName)
binary.LittleEndian.PutUint32(sh[8:], uint32(len(sectionData)))
binary.LittleEndian.PutUint32(sh[12:], newRVA)
binary.LittleEndian.PutUint32(sh[16:], uint32(len(padded)))
binary.LittleEndian.PutUint32(sh[20:], newFileOff)
binary.LittleEndian.PutUint32(sh[36:], secAttrib)
copy(out[shOff:], sh)
lfanew := int(binary.LittleEndian.Uint32(out[0x3C:0x40]))
binary.LittleEndian.PutUint16(out[lfanew+4+2:], numSections+1)
binary.LittleEndian.PutUint32(out[peOff+16:], newRVA+hdrSize)
newSizeOfImage := align(newRVA+uint32(len(sectionData)), sectAlign)
binary.LittleEndian.PutUint32(out[peOff+56:], newSizeOfImage)
curInit := binary.LittleEndian.Uint32(out[peOff+8:])
binary.LittleEndian.PutUint32(out[peOff+8:], curInit+uint32(len(padded)))
ckOff := peOff + 64
binary.LittleEndian.PutUint32(out[ckOff:], 0)
binary.LittleEndian.PutUint32(out[ckOff:], peChecksum(out))
skipAt := int(newFileOff) + crcOff
binary.LittleEndian.PutUint32(out[skipAt:], 0)
binary.LittleEndian.PutUint32(out[skipAt+4:], 0)
var crcF uint32
if !signed {
// 签名产物留空:Authenticode 会追加证书表,与整文件 CRC 互斥
crcF = crcSkip(out[:skipAt], out[skipAt+8:])
}
binary.LittleEndian.PutUint32(out[skipAt:], crcV)
binary.LittleEndian.PutUint32(out[skipAt+4:], crcF)
info.EntryOld = uint64(entryRVA)
info.EntryNew = uint64(newRVA) + hdrSize
info.SecRVA = uint64(newRVA)
info.SecSize = uint32(len(sectionData))
info.CrcVfy = crcV
info.CrcFile = crcF
info.OutSize = len(out)
return out, info, nil
}
// BuildCfg 生成壳配置(api 指向调用方所在站点)
func BuildCfg(appKey, appName, baseURL string) []byte {
return BuildCfgThemed(appKey, appName, baseURL, "classic")
}
// BuildCfgThemed 生成壳用的配置;theme 决定验证界面用哪套皮肤(DuiLib 壳读取)
func BuildCfgThemed(appKey, appName, baseURL, theme string) []byte {
return BuildCfgThemedVer(appKey, appName, baseURL, theme, "")
}
// BuildCfgThemedVer 额外带上目标程序的版本号。
// 只有登记了版本的程序才做自动更新比对;空版本号 = 壳不打扰用户。
func BuildCfgThemedVer(appKey, appName, baseURL, theme, ver string) []byte {
api := fmt.Sprintf("%s/api/v1/app/%s/login", strings.TrimRight(baseURL, "/"), appKey)
if theme == "" {
theme = "classic"
}
ver = strings.TrimSpace(ver)
cfg := fmt.Sprintf(`{"api":%q,"name":%q,"device_auto":1,"shell_ver":%d,"theme":%q,"ver":%q}`,
api, appName, shellVer, theme, ver)
return []byte(cfg)
}
// ---------- 任务存储与执行 ----------
type Runner struct {
Dir string
}
func NewRunner(dir string) *Runner {
if dir == "" {
dir = filepath.Join("data", "protect")
}
// 必须绝对:签名/打包工具是子进程,cwd 会被切到 workDir,
// 相对路径(默认 data/protect)在子进程里会解析到错误位置
// (实测 osslsigncode 报 Failed to read PKCS#12 file)。
if abs, err := filepath.Abs(dir); err == nil {
dir = abs
}
os.MkdirAll(dir, 0o755)
return &Runner{Dir: dir}
}
// Run 对已落盘的源文件加壳,返回产物路径与信息
func (r *Runner) Run(srcPath, outPath string, cfg []byte) (Info, error) {
return r.RunWithTask(nil, srcPath, outPath, cfg)
}
// RunWithTask 带任务上下文的执行:IPA 需要任务上的签名证书与壳 dylib
func (r *Runner) RunWithTask(task *model.ProtectTask, srcPath, outPath string, cfg []byte) (Info, error) {
src, err := os.ReadFile(srcPath)
if err != nil {
return Info{}, fmt.Errorf("读源文件: %w", err)
}
det := DetectFile(src, filepath.Base(srcPath))
var out []byte
var info Info
var perr error
if det.Kind == KindIPA {
var mat *Material
if task != nil && task.SignProfileID != nil {
mat, perr = LoadMaterial(*task.SignProfileID, task.CertIdentity)
if perr != nil {
return info, perr
}
defer mat.Close()
}
out, perr = SignIPA(src, mat, DylibForIOS(), filepath.Join(filepath.Dir(outPath), "ipa"))
if perr == nil {
info = Info{Arch: "universal", OriginalSource: len(src), OutSize: len(out),
Note: "IPA 已注入壳 dylib 并用你的证书重签"}
}
} else if det.Kind == KindAPK {
out, info, perr = patchAPK(src, cfg, filepath.Dir(outPath))
} else if det.Kind == KindPE && task != nil && IsDriverPE(src, filepath.Base(srcPath)) {
// 内核驱动(.sys / 子系统 NATIVE):绝不能塞用户态验证壳,注进去驱动直接加载失败。
// 驱动要的是 Authenticode 签名,所以这里只签名、不注入。
if task.SignProfileID == nil {
return info, fmt.Errorf("内核驱动只能签名、不能加密;请选择一张支持驱动签名用途的证书")
}
mat, merr := LoadMaterial(*task.SignProfileID, task.CertIdentity)
if merr != nil {
return info, merr
}
defer mat.Close()
var note string
out, note, perr = SignPE(src, mat, filepath.Join(filepath.Dir(outPath), "pe_sign"))
if perr != nil {
return info, perr
}
info = Info{Arch: det.Arch, OriginalSource: len(src), OutSize: len(out),
Note: "内核驱动仅签名(未注入验证壳)"}
if note != "" {
info.Note += "(" + note + ")"
}
} else {
// PE:任务带证书 → 走「签名构建」(flags.bit1,crcFile 留空),注入完成后再 Authenticode 重签
signed := det.Kind == KindPE && task != nil && task.SignProfileID != nil
theme := "classic"
if task != nil && task.ShellTheme != "" {
theme = task.ShellTheme
}
out, info, perr = PatchAutoSignedThemed(src, cfg, filepath.Base(srcPath), signed, theme)
if perr == nil && signed {
var mat *Material
mat, perr = LoadMaterial(*task.SignProfileID, task.CertIdentity)
if perr == nil {
defer mat.Close()
var note string
out, note, perr = SignPE(out, mat, filepath.Join(filepath.Dir(outPath), "pe_sign"))
if perr == nil {
info.Note = "已用你的证书做 Authenticode 重签"
if note != "" {
info.Note += "(" + note + ")"
}
}
}
}
}
if perr != nil {
err = perr
return info, err
}
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
return info, err
}
if err := os.WriteFile(outPath, out, 0o644); err != nil {
return info, fmt.Errorf("写产物: %w", err)
}
return info, nil
}
// SaveSource 把上传的原始程序落盘
func (r *Runner) SaveSource(taskID uint, name string, data []byte) (string, error) {
d := filepath.Join(r.Dir, fmt.Sprintf("%d", taskID))
if err := os.MkdirAll(d, 0o755); err != nil {
return "", err
}
base := filepath.Base(name)
if base == "" || base == "." || base == string(filepath.Separator) {
base = "app.exe"
}
p := filepath.Join(d, "src_"+base)
if err := os.WriteFile(p, data, 0o644); err != nil {
return "", err
}
return p, nil
}
// OutPath 产物路径
func (r *Runner) OutPath(taskID uint, name string) string {
base := filepath.Base(name)
if base == "" {
base = "app.exe"
}
if i := strings.LastIndex(base, "."); i > 0 {
base = base[:i] + "_protected" + base[i:]
} else {
// 无扩展名(常见于 Linux 可执行)不加 .exe
base += "_protected"
}
return filepath.Join(r.Dir, fmt.Sprintf("%d", taskID), base)
}
func (r *Runner) Now() time.Time { return time.Now() }
// ---------- 内部工具 ----------
func align(v, a uint32) uint32 {
if a == 0 {
return v
}
return (v + a - 1) / a * a
}
func optSize(is64 bool) int {
if is64 {
return 240
}
return 224
}
func crcSkip(chunks ...[]byte) uint32 {
h := crc32.NewIEEE()
for _, c := range chunks {
h.Write(c)
}
return h.Sum32()
}
func peChecksum(data []byte) uint32 {
var sum uint64
n := len(data)
i := 0
for ; i+1 < n; i += 2 {
sum += uint64(binary.LittleEndian.Uint16(data[i:]))
sum = (sum & 0xffff) + (sum >> 16)
}
if i < n {
sum += uint64(data[i])
sum = (sum & 0xffff) + (sum >> 16)
}
sum = (sum & 0xffff) + (sum >> 16)
return uint32(sum) + uint32(n)
}
+59
View File
@@ -0,0 +1,59 @@
package protect
import (
"os"
"path/filepath"
"testing"
)
// 用仓库内嵌资产对一个构造的最小 PE 走一遍 Patch,验证结构与 CRC 自洽
func TestPatchProducesValidHeader(t *testing.T) {
for _, arch := range []string{"x64", "x86"} {
blob, dll, err := Assets(arch)
if err != nil {
t.Fatalf("%s 资产缺失: %v", arch, err)
}
if len(blob) < 1000 || len(dll) < 100000 {
t.Fatalf("%s 资产异常: blob=%d dll=%d", arch, len(blob), len(dll))
}
}
}
// BuildCfg 必须生成可解析的 JSON 且带 device_auto
func TestBuildCfg(t *testing.T) {
cfg := BuildCfg("abc123", "客服助手", "https://v.example.com/")
s := string(cfg)
for _, want := range []string{
`"api":"https://v.example.com/api/v1/app/abc123/login"`,
`"device_auto":1`,
`"name":"客服助手"`,
} {
if !contains(s, want) {
t.Fatalf("cfg 缺少 %s,实际: %s", want, s)
}
}
}
func contains(s, sub string) bool {
return len(s) >= len(sub) && (func() bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
})()
}
// Runner 的产物命名与目录
func TestOutPath(t *testing.T) {
dir := t.TempDir()
r := NewRunner(dir)
p := r.OutPath(7, "拼多多客服助手.exe")
if filepath.Ext(p) != ".exe" || filepath.Dir(p) != filepath.Join(dir, "7") {
t.Fatalf("产物路径不符合预期: %s", p)
}
if _, err := os.Stat(filepath.Dir(p)); err == nil {
t.Fatalf("目录不应提前创建")
}
}
+211
View File
@@ -0,0 +1,211 @@
package protect
// 把加壳产物落成一条新版本记录:客户端按「版本记录 ID 递增」判定更新,
// 原地改已发布版本的入口文件在客户端不报 manifest_hash 时永远推不下去。
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/utils/contentstore"
)
// PublishOptions 生成版本的参数
type PublishOptions struct {
Version string // 留空则按来源版本自动进位
UpdateStrategy string // optional / forced(默认 optional)
UpdateType string // full / delta(默认 full)
UpdateMethod string // auto / manual(默认 auto)
Changelog string
PublishNow bool // 建好就直接发布
}
// PublishAsVersion 把任务产物写成新版本,返回创建出的版本
func PublishAsVersion(taskID uint, opts PublishOptions) (*model.Version, error) {
var task model.ProtectTask
if err := database.DB.First(&task, taskID).Error; err != nil {
return nil, fmt.Errorf("云端加密任务不存在")
}
if task.Status != "done" || task.OutputPath == "" {
return nil, fmt.Errorf("任务尚未完成,无法生成版本")
}
data, err := os.ReadFile(task.OutputPath)
if err != nil {
return nil, fmt.Errorf("读取产物失败: %w", err)
}
var app model.Application
if err := database.DB.First(&app, task.ApplicationID).Error; err != nil {
return nil, fmt.Errorf("应用不存在")
}
sum := sha256.Sum256(data)
hash := hex.EncodeToString(sum[:])
stored := contentstore.ContentFilePath(hash)
if stored == "" {
return nil, fmt.Errorf("内容哈希异常")
}
if err := os.MkdirAll(filepath.Dir(stored), 0o755); err != nil {
return nil, err
}
if err := os.WriteFile(stored, data, 0o644); err != nil {
return nil, fmt.Errorf("落盘产物失败: %w", err)
}
var src model.Version
hasSrc := task.VersionID > 0 && database.DB.First(&src, task.VersionID).Error == nil
versionStr := strings.TrimSpace(opts.Version)
autoBump := versionStr == ""
if autoBump {
switch {
case hasSrc:
versionStr = src.Version
default:
var latest model.Version
if database.DB.Where("application_id = ?", app.ID).Order("id DESC").First(&latest).Error == nil {
versionStr = latest.Version
} else {
versionStr = time.Now().Format("2006.01.02.1504")
}
}
// 自动进位要避开已存在的号:源版本 9.9.9 但 9.9.10 已被人占时继续往上找
for i := 0; i < 200; i++ {
next := BumpVersion(versionStr)
var used int64
database.DB.Model(&model.Version{}).
Where("application_id = ? AND version = ?", app.ID, next).Count(&used)
versionStr = next
if used == 0 {
break
}
}
}
var dup int64
database.DB.Model(&model.Version{}).
Where("application_id = ? AND version = ?", app.ID, versionStr).Count(&dup)
if dup > 0 {
return nil, fmt.Errorf("版本号 %s 已存在,请换一个", versionStr)
}
strategy := opts.UpdateStrategy
if strategy == "" {
strategy = "optional"
}
if strategy != "optional" && strategy != "forced" {
return nil, fmt.Errorf("update_strategy 只能是 optional 或 forced")
}
updateType := opts.UpdateType
if updateType == "" {
updateType = "full"
}
method := opts.UpdateMethod
if method == "" {
method = "auto"
}
entryName := filepath.Base(task.OutputName)
if entryName == "" {
entryName = "app_protected.exe"
}
srcID := task.VersionID
taskIDCopy := task.ID
v := model.Version{
ApplicationID: app.ID,
Version: versionStr,
FilePath: stored,
FileSize: int64(len(data)),
FileHash: hash,
EntryFile: entryName,
UpdateStrategy: strategy,
UpdateType: updateType,
UpdateMethod: method,
Changelog: opts.Changelog,
PublishStatus: "draft",
Protected: true,
ProtectTaskID: &taskIDCopy,
}
if srcID > 0 {
v.SourceVersionID = &srcID
}
if opts.PublishNow {
now := time.Now()
v.PublishStatus = "published"
v.PublishedAt = &now
}
if err := database.DB.Create(&v).Error; err != nil {
return nil, fmt.Errorf("创建版本失败: %w", err)
}
// 入口文件(加壳产物)
vf := model.VersionFile{
VersionID: v.ID,
FileName: entryName,
FilePath: contentstore.ContentFileURL(hash),
FileSize: int64(len(data)),
FileHash: hash,
FileType: "program",
IsRequired: true,
SortOrder: 0,
}
if err := database.DB.Create(&vf).Error; err != nil {
return nil, fmt.Errorf("写入版本文件失败: %w", err)
}
// 其余资源文件沿用来源版本(内容寻址,不重复占空间)
if hasSrc {
var srcFiles []model.VersionFile
database.DB.Where("version_id = ?", src.ID).Find(&srcFiles)
for _, f := range srcFiles {
if strings.EqualFold(filepath.Base(f.FileName), entryName) {
continue
}
if strings.EqualFold(filepath.Base(f.FileName), filepath.Base(src.EntryFile)) {
continue
}
cp := model.VersionFile{
VersionID: v.ID, FileName: f.FileName, FilePath: f.FilePath,
FileSize: f.FileSize, FileHash: f.FileHash, FileType: f.FileType,
IsRequired: f.IsRequired, SortOrder: f.SortOrder + 1,
}
database.DB.Create(&cp)
}
}
if opts.PublishNow && strategy == "forced" {
database.DB.Model(&model.Version{}).
Where("application_id = ? AND id < ? AND publish_status = ?", app.ID, v.ID, "published").
Updates(map[string]interface{}{
"publish_status": "superseded",
"superseded_by": v.ID,
"deprecated_at": time.Now(),
})
}
// 注意:不要回写 task.version_id —— 那一列表示「加壳来源版本」,
// 生成了哪个版本要靠 version.protect_task_id 反查。
return &v, nil
}
// BumpVersion 末段数字 +1:1.1.13 → 1.1.14;无数字则追加 .1
func BumpVersion(v string) string {
v = strings.TrimSpace(v)
if v == "" {
return "1.0.0"
}
parts := strings.Split(v, ".")
last := parts[len(parts)-1]
if n, err := strconv.Atoi(last); err == nil {
parts[len(parts)-1] = strconv.Itoa(n + 1)
return strings.Join(parts, ".")
}
return v + ".1"
}
+20
View File
@@ -0,0 +1,20 @@
package protect
import "testing"
func TestBumpVersion(t *testing.T) {
cases := map[string]string{
"1.1.13": "1.1.14",
"9.9.9": "9.9.10",
"2": "3",
"v1.2.3": "v1.2.4",
"1.0.0.99": "1.0.0.100",
"beta": "beta.1",
"": "1.0.0",
}
for in, want := range cases {
if got := BumpVersion(in); got != want {
t.Fatalf("BumpVersion(%q) = %q, 期望 %q", in, got, want)
}
}
}
+591
View File
@@ -0,0 +1,591 @@
package protect
// 吊销与拉黑检测。
//
// 为什么要单独做:证书「过期」和证书「被吊销」「进了黑名单」是三件事。
// - 过期:NotAfter 已过,签名照样能写进去(Windows 判定不受信任)
// - 吊销:CA 主动作废(私钥泄露 / 公司改名 / 违规),OCSP 或 CRL 会答 revoked
// - 拉黑:微软维护的 Disallowed Certificate Trust List(被吊销后仍被信任根里的机器信任
// 的证书都在这张表里),以及平台自己的黑名单
// 一张过期证书可能同时被吊销;泄露的代码签名证书通常三者全中。
//
// 现实约束:这批老证书的 OCSP/CRL 端点经常已经下线或拒答(实测 VeriSign 对
// 2010 年代的旧 CA 直接回 unauthorized),所以状态必须允许「查不到」,不能把
// 查不到当成没问题,也不能当成有问题。
import (
"bytes"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/x509"
"encoding/asn1"
"encoding/hex"
"encoding/pem"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"time"
"golang.org/x/crypto/ocsp"
)
// 吊销状态取值
const (
RevokeGood = "good" // 明确未吊销
RevokeRevoked = "revoked" // 明确已吊销
RevokeUnknown = "unknown" // 查不到(端点下线 / 拒答 / 没配 OCSO 与 CRL)
RevokeNotChecked = "not_checked" // 还没查过
)
// RevokeInfo 一张证书的吊销 / 拉黑结论
type RevokeInfo struct {
Status string `json:"status"` // good/revoked/unknown/not_checked
Source string `json:"source"` // ocsp / crl / msban / local / 空
Reason string `json:"reason"` // 吊销原因(keyCompromise 等)
Detail string `json:"detail"` // 人话说明
CheckedAt string `json:"checked_at"`
}
// 内存缓存:同一张证书没必要每次都去网络上问一遍
var (
revokeMu sync.RWMutex
revokeCache = map[string]cachedRevoke{}
revokeTTL = 6 * time.Hour
banMu sync.RWMutex
banSet = map[string]bool{}
banFetched time.Time
banTTL = 24 * time.Hour
)
type cachedRevoke struct {
info RevokeInfo
at time.Time
}
var httpClient = &http.Client{Timeout: 8 * time.Second}
// CheckRevocation 查一张证书的吊销状态。
// issuer 可以为 nil(不在证书包里时由 AIA 去取),取不到就只能回 unknown。
func CheckRevocation(cert *x509.Certificate, issuer *x509.Certificate) RevokeInfo {
key := fingerprintHex(cert)
// 「查不到」不能缓存 6 小时:CA 端点一时抽风就把结论钉死了,
// 未知结果只缓 10 分钟,明确结论才缓 6 小时。
revokeMu.RLock()
if c, ok := revokeCache[key]; ok {
ttl := revokeTTL
if c.info.Status == RevokeUnknown || c.info.Status == RevokeNotChecked {
ttl = 10 * time.Minute
}
if time.Since(c.at) < ttl {
revokeMu.RUnlock()
return c.info
}
}
revokeMu.RUnlock()
info := checkRevocationUncached(cert, issuer)
revokeMu.Lock()
revokeCache[key] = cachedRevoke{info: info, at: time.Now()}
revokeMu.Unlock()
return info
}
func checkRevocationUncached(cert *x509.Certificate, issuer *x509.Certificate) RevokeInfo {
now := time.Now().Format("2006-01-02 15:04:05")
if issuer == nil {
issuer = fetchIssuer(cert)
}
var details []string
// ① OCSP(首选:快、结论新)
if issuer != nil && len(cert.OCSPServer) > 0 {
if info, ok := tryOCSP(cert, issuer); ok {
info.CheckedAt = now
return info
}
details = append(details, "OCSP 无有效应答")
}
// ② CRL(回落)
if len(cert.CRLDistributionPoints) > 0 {
if info, ok := tryCRL(cert); ok {
info.CheckedAt = now
return info
}
details = append(details, "CRL 无有效应答")
}
if len(cert.OCSPServer) == 0 && len(cert.CRLDistributionPoints) == 0 {
details = append(details, "证书里没有 OCSP / CRL 地址")
}
if issuer == nil {
details = append(details, "拿不到签发者证书,无法验证应答")
}
return RevokeInfo{
Status: RevokeUnknown,
Detail: strings.Join(details, ";"),
CheckedAt: now,
}
}
// tryOCSP 发一次 OCSP 请求
func tryOCSP(cert, issuer *x509.Certificate) (RevokeInfo, bool) {
req, err := ocsp.CreateRequest(cert, issuer, nil)
if err != nil {
return RevokeInfo{}, false
}
for _, url := range cert.OCSPServer {
if !strings.HasPrefix(url, "http") {
continue
}
httpReq, err := http.NewRequest("POST", url, bytes.NewReader(req))
if err != nil {
continue
}
httpReq.Header.Set("Content-Type", "application/ocsp-request")
resp, err := httpClient.Do(httpReq)
if err != nil {
continue
}
body, rerr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
if rerr != nil || resp.StatusCode != 200 {
continue
}
parsed, perr := ocsp.ParseResponseForCert(body, cert, issuer)
if perr != nil {
continue
}
// 应答过期了就别当结论
if !parsed.NextUpdate.IsZero() && parsed.NextUpdate.Before(time.Now()) {
continue
}
switch parsed.Status {
case ocsp.Good:
return RevokeInfo{Status: RevokeGood, Source: "ocsp",
Detail: "OCSP 应答:未吊销(" + url + ")"}, true
case ocsp.Revoked:
return RevokeInfo{Status: RevokeRevoked, Source: "ocsp",
Reason: revokeReasonText(parsed.RevocationReason),
Detail: "OCSP 应答:已吊销,吊销时间 " + parsed.RevokedAt.Format("2006-01-02") + "(" + url + ")",
CheckedAt: time.Now().Format("2006-01-02 15:04:05")}, true
}
}
return RevokeInfo{}, false
}
// tryCRL 拉 CRL 判一次
func tryCRL(cert *x509.Certificate) (RevokeInfo, bool) {
for _, url := range cert.CRLDistributionPoints {
if !strings.HasPrefix(url, "http") {
continue
}
resp, err := httpClient.Get(url)
if err != nil {
continue
}
body, rerr := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
resp.Body.Close()
if rerr != nil || resp.StatusCode != 200 {
continue
}
crl, perr := parseCRL(body)
if perr != nil {
continue
}
if !crl.NextUpdate.IsZero() && crl.NextUpdate.Before(time.Now()) {
continue // CRL 本身过期,不能当结论
}
for _, e := range crl.RevokedCertificateEntries {
if e.SerialNumber.Cmp(cert.SerialNumber) == 0 {
return RevokeInfo{Status: RevokeRevoked, Source: "crl",
Reason: revokeReasonText(e.ReasonCode),
Detail: "CRL 里查到此序列号,吊销时间 " + e.RevocationTime.Format("2006-01-02"),
CheckedAt: time.Now().Format("2006-01-02 15:04:05")}, true
}
}
return RevokeInfo{Status: RevokeGood, Source: "crl",
Detail: "CRL 里没有此序列号(" + url + ")",
CheckedAt: time.Now().Format("2006-01-02 15:04:05")}, true
}
return RevokeInfo{}, false
}
// parseCRL 同时兼容 DER 与 PEM 两种 CRL
func parseCRL(data []byte) (*x509.RevocationList, error) {
if blk, _ := pem.Decode(data); blk != nil {
data = blk.Bytes
}
return x509.ParseRevocationList(data)
}
// fetchIssuer 从 AIA 的 caIssuers 地址把签发者证书取回来
func fetchIssuer(cert *x509.Certificate) *x509.Certificate {
for _, url := range cert.IssuingCertificateURL {
if !strings.HasPrefix(url, "http") {
continue
}
resp, err := httpClient.Get(url)
if err != nil {
continue
}
body, rerr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
if rerr != nil || resp.StatusCode != 200 {
continue
}
if c, err := x509.ParseCertificate(body); err == nil {
return c
}
// 常见形态是 PKCS#7 证书包
if blk, _ := pem.Decode(body); blk != nil {
if c, err := x509.ParseCertificate(blk.Bytes); err == nil {
return c
}
}
if certs := certsFromPKCS7(body); len(certs) > 0 {
return certs[0]
}
}
return nil
}
// certsFromPKCS7 从 PKCS#7 / certs-only 包里抠证书。
// 只认嵌着的证书结构,不做验签——这里只需要签发者公钥去校验 OCSP 应答。
func certsFromPKCS7(data []byte) []*x509.Certificate {
var out []*x509.Certificate
var ci struct {
ContentType asn1.ObjectIdentifier
Content asn1.RawValue `asn1:"explicit,tag:0"`
}
if _, err := asn1.Unmarshal(data, &ci); err != nil {
return nil
}
rest := ci.Content.Bytes
for len(rest) > 0 {
var raw asn1.RawValue
var err error
rest, err = asn1.Unmarshal(rest, &raw)
if err != nil {
break
}
if c, cerr := x509.ParseCertificate(raw.FullBytes); cerr == nil {
out = append(out, c)
continue
}
// 证书可能嵌在更深一层
inner := raw.Bytes
for len(inner) > 0 {
var r2 asn1.RawValue
var e2 error
inner, e2 = asn1.Unmarshal(inner, &r2)
if e2 != nil {
break
}
if c, cerr := x509.ParseCertificate(r2.FullBytes); cerr == nil {
out = append(out, c)
}
}
if len(out) >= 8 {
break
}
}
return out
}
func revokeReasonText(code int) string {
switch code {
case ocsp.KeyCompromise:
return "私钥泄露"
case ocsp.CACompromise:
return "CA 被攻破"
case ocsp.AffiliationChanged:
return "主体信息变更"
case ocsp.Superseded:
return "被新证书取代"
case ocsp.CessationOfOperation:
return "停止运营"
case ocsp.CertificateHold:
return "暂时冻结"
case ocsp.RemoveFromCRL:
return "已从 CRL 移除"
case ocsp.PrivilegeWithdrawn:
return "权限被撤销"
case ocsp.AACompromise:
return "属性机构被攻破"
}
if code == 0 {
return "未给出原因"
}
return fmt.Sprintf("原因码 %d", code)
}
func fingerprintHex(c *x509.Certificate) string {
s := sha256.Sum256(c.Raw)
return hex.EncodeToString(s[:])
}
// ---------------------------------------------------------------------------
// 微软拉黑名单(Disallowed Certificate Trust List)
//
// 这张表就是 Windows 判断「这张证书虽然链能验通,但已经被官方作废」的依据。
// 文件是 CAB 包里的一个 CTL(PKCS#7 signedData,contentType 1.3.6.1.4.1.311.10.1),
// 条目里存的是证书哈希。解 CAB 用系统 cabextract(Alpine 里 apk add cabextract)。
// ---------------------------------------------------------------------------
// DisallowedSet 返回微软拉黑名单里的证书哈希集合(hex 小写)。
// 缓存 24 小时;拉不到就返回上一次的结果(没有就返回空集合)。
func DisallowedSet(cacheDir string) map[string]bool {
banMu.RLock()
if time.Since(banFetched) < banTTL && len(banSet) > 0 {
out := banSet
banMu.RUnlock()
return out
}
banMu.RUnlock()
banMu.Lock()
defer banMu.Unlock()
// 磁盘缓存:多进程/重启后不用重新下载
file := filepath.Join(cacheDir, "msban.txt")
if cacheDir != "" {
if st, err := os.Stat(file); err == nil && time.Since(st.ModTime()) < banTTL {
if b, err := os.ReadFile(file); err == nil {
banSet = parseHashLines(b)
banFetched = time.Now()
return banSet
}
}
}
set, err := downloadDisallowed()
if err != nil || len(set) == 0 {
// 拉不到就沿用旧结果,别把「没查到」当成「没被拉黑」
if len(banSet) > 0 {
banFetched = time.Now()
return banSet
}
return map[string]bool{}
}
banSet = set
banFetched = time.Now()
if cacheDir != "" {
os.MkdirAll(cacheDir, 0o700)
var sb strings.Builder
for h := range set {
sb.WriteString(h + "\n")
}
os.WriteFile(file, []byte(sb.String()), 0o600)
}
return banSet
}
func parseHashLines(b []byte) map[string]bool {
out := map[string]bool{}
for _, line := range strings.Split(string(b), "\n") {
line = strings.TrimSpace(line)
if len(line) >= 32 {
out[strings.ToLower(line)] = true
}
}
return out
}
// downloadDisallowed 下载并解出 CTL,提取里面所有证书哈希
func downloadDisallowed() (map[string]bool, error) {
const url = "http://ctldl.windowsupdate.com/msdownload/update/v3/static/trustedr/en/disallowedcertstl.cab"
resp, err := httpClient.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("下载拉黑名单失败: HTTP %d", resp.StatusCode)
}
cab, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20))
if err != nil {
return nil, err
}
stl, err := cabExtractFirst(cab)
if err != nil {
return nil, err
}
return ctlHashes(stl), nil
}
// cabExtractFirst 用系统 cabextract 解出 CAB 里第一个文件
func cabExtractFirst(cab []byte) ([]byte, error) {
dir, err := os.MkdirTemp("", "msban_")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
src := filepath.Join(dir, "in.cab")
if err := os.WriteFile(src, cab, 0o600); err != nil {
return nil, err
}
if out, err := runCmd(dir, "cabextract", "-q", "-d", dir, src); err != nil {
return nil, fmt.Errorf("解 CAB 失败(镜像里需要 cabextract): %v %s", err, tail(out, 200))
}
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(strings.ToLower(e.Name()), ".stl") {
return os.ReadFile(filepath.Join(dir, e.Name()))
}
}
return nil, fmt.Errorf("CAB 里没找到 .stl")
}
// ctlHashes 从 CTL 里把所有证书哈希抠出来。
// 条目的哈希长度随算法变化(历史上有 16/20/32 字节),所以这里不写死长度,
// 统一收集 SEQUENCE 内的原始字节,再用多种算法分别比对。
func ctlHashes(der []byte) map[string]bool {
out := map[string]bool{}
i := 0
for i < len(der)-2 {
if der[i] != 0x04 { // OCTET STRING
i++
continue
}
l := int(der[i+1])
if l == 0x81 && i+2 < len(der) {
l = int(der[i+2])
i++
}
start := i + 2
if l >= 16 && l <= 64 && start+l <= len(der) {
h := der[start : start+l]
out[strings.ToLower(hex.EncodeToString(h))] = true
}
i = start + l
}
return out
}
// BanState 判断一张证书是否在微软拉黑名单或平台黑名单里
func BanState(cert *x509.Certificate, localFingerprints map[string]string) RevokeInfo {
fp := fingerprintHex(cert)
if localFingerprints != nil {
if reason, ok := localFingerprints[strings.ToLower(fp)]; ok {
return RevokeInfo{Status: RevokeRevoked, Source: "local",
Reason: "平台黑名单", Detail: "该证书已被本平台拉黑" + ifStr(reason, ":"+reason),
CheckedAt: time.Now().Format("2006-01-02 15:04:05")}
}
}
set := DisallowedSet("")
if len(set) == 0 {
return RevokeInfo{Status: RevokeNotChecked, Detail: "微软拉黑名单未获取到"}
}
md5sum := md5Hex(cert.Raw)
sha1sum := sha1Hex(cert.Raw)
for _, cand := range []string{
strings.ToLower(fp), // sha256 全量
strings.ToLower(fp[:32]), // sha256 前 16 字节
md5sum, // md5
sha1sum, // sha1
strings.ToLower(sha1sum[:32]), // sha1 前 16 字节
} {
if set[cand] {
return RevokeInfo{Status: RevokeRevoked, Source: "msban",
Reason: "微软拉黑名单",
Detail: "该证书在微软 Disallowed Certificate Trust List 里(Windows 会拒绝其签名)",
CheckedAt: time.Now().Format("2006-01-02 15:04:05")}
}
}
return RevokeInfo{Status: RevokeGood, Source: "msban",
Detail: "不在微软拉黑名单里", CheckedAt: time.Now().Format("2006-01-02 15:04:05")}
}
func ifStr(cond, s string) string {
if cond == "" {
return ""
}
return s
}
func md5Hex(b []byte) string {
sum := md5Sum(b)
return hex.EncodeToString(sum[:])
}
func sha1Hex(b []byte) string {
sum := sha1.Sum(b)
return hex.EncodeToString(sum[:])
}
func md5Sum(b []byte) [16]byte {
return md5.Sum(b)
}
// CheckProfileIdentity 对某条证书记录里的第 identity 套身份做吊销 + 拉黑检查。
// 供加壳前把关使用:已吊销 / 被拉黑的证书直接拦,查不到只提示不拦。
func CheckProfileIdentity(profileID uint, identity int, localBan map[string]string) (rev RevokeInfo, ban RevokeInfo, subject string, err error) {
dir := ProfileDir(profileID)
certData, err := ReadEncrypted(filepath.Join(dir, "cert.enc"))
if err != nil {
return rev, ban, "", fmt.Errorf("读取证书失败: %w", err)
}
password := ""
if b, e := ReadEncrypted(filepath.Join(dir, "pass.enc")); e == nil {
password = string(b)
}
full, err := ParseIdentitiesFull(certData, password)
if err != nil {
return rev, ban, "", err
}
if len(full) == 0 {
return rev, ban, "", fmt.Errorf("证书里没有可签名的身份")
}
if identity <= 0 {
identity = 1
}
if identity > len(full) {
return rev, ban, "", fmt.Errorf("证书里只有 %d 套身份", len(full))
}
d := full[identity-1]
return CheckRevocation(d.Cert, d.Issuer), BanState(d.Cert, localBan), d.Subject, nil
}
// ProfileIdentityUsage 取某条证书记录里第 identity 套身份的用途(应用/驱动)
func ProfileIdentityUsage(profileID uint, identity int) (CertUsage, string, error) {
dir := ProfileDir(profileID)
certData, err := ReadEncrypted(filepath.Join(dir, "cert.enc"))
if err != nil {
return CertUsage{}, "", fmt.Errorf("读取证书失败: %w", err)
}
password := ""
if b, e := ReadEncrypted(filepath.Join(dir, "pass.enc")); e == nil {
password = string(b)
}
full, err := ParseIdentitiesFull(certData, password)
if err != nil {
return CertUsage{}, "", err
}
if len(full) == 0 {
return CertUsage{}, "", fmt.Errorf("证书里没有可签名的身份")
}
if identity <= 0 {
identity = 1
}
if identity > len(full) {
return CertUsage{}, "", fmt.Errorf("证书里只有 %d 套身份", len(full))
}
return full[identity-1].Usage, full[identity-1].Subject, nil
}
+249
View File
@@ -0,0 +1,249 @@
package protect
// 签名层:Windows 走 osslsigncode(Authenticode),iOS 走 zsign(注 dylib + 重签)。
// 两者都不在发行版仓库里,镜像里通过多阶段构建产出:
// zsign https://github.com/zhlynn/zsign 的 musl 静态版
// osslsigncode https://github.com/mtrojnar/osslsigncode 源码编译
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// SignToolPaths 签名工具位置
type SignToolPaths struct {
OsslSigncode string
Zsign string
}
// SignTools 解析签名工具(PATH 优先,其次 /app/tools 固定路径)
func SignTools() SignToolPaths {
look := func(env, name string) string {
if v := os.Getenv(env); v != "" {
return v
}
if p, err := exec.LookPath(name); err == nil {
return p
}
if fileExists("/app/tools/" + name) {
return "/app/tools/" + name
}
return ""
}
return SignToolPaths{
OsslSigncode: look("PROTECT_OSSLSIGNCODE", "osslsigncode"),
Zsign: look("PROTECT_ZSIGN", "zsign"),
}
}
// Material 解密后的证书材料(临时明文文件,用完必须清理)
type Material struct {
CertPath string // p12/pfx
Password string
CrossPath string // 交叉签名证书(.cer/.pem),内核驱动签名用 -ac 带上
ProfilePath string // mobileprovision(仅 iOS)
Platform string
tmpDir string
}
// Close 清理临时明文
func (m *Material) Close() {
if m != nil && m.tmpDir != "" {
os.RemoveAll(m.tmpDir)
}
}
// LoadMaterial 把证书资产解密到临时目录(0600),返回的材料用完必须 Close。
//
// identity 是证书文件里的第几套身份(0/1 = 第一套)。一个 pfx 里可能装几十套
// 「私钥+证书」(驱动签名打包这类文件很常见),而 osslsigncode/OpenSSL 只认
// 文件里第一套 —— 所以选其它套时必须先把它单独拆出来再交给签名工具。
func LoadMaterial(profileID uint, identity ...int) (*Material, error) {
if profileID == 0 {
return nil, fmt.Errorf("没有指定签名证书")
}
dir := ProfileDir(profileID)
if abs, err := filepath.Abs(dir); err == nil {
dir = abs
}
certEnc := filepath.Join(dir, "cert.enc")
cert, err := ReadEncrypted(certEnc)
if err != nil {
return nil, fmt.Errorf("读取证书失败: %w", err)
}
tmpRoot := filepath.Join(Default().Dir, "tmp")
if abs, err := filepath.Abs(tmpRoot); err == nil {
tmpRoot = abs
}
if err := os.MkdirAll(tmpRoot, 0o700); err != nil {
return nil, err
}
tmp, err := os.MkdirTemp(tmpRoot, "sign_")
if err != nil {
return nil, err
}
m := &Material{tmpDir: tmp}
m.CertPath = filepath.Join(tmp, "cert.p12")
if pass, err := ReadEncrypted(filepath.Join(dir, "pass.enc")); err == nil {
m.Password = string(pass)
}
// 选中了非第一套身份:把那一套单独拆出来给签名工具
want := 1
if len(identity) > 0 && identity[0] > 0 {
want = identity[0]
}
if want > 1 {
ids, serr := SplitPFX(cert, m.Password)
if serr != nil {
m.Close()
return nil, fmt.Errorf("拆分证书身份失败: %w", serr)
}
if want > len(ids) {
m.Close()
return nil, fmt.Errorf("证书文件里只有 %d 套身份,选不到第 %d 套", len(ids), want)
}
cert = ids[want-1].PFX
}
if err := os.WriteFile(m.CertPath, cert, 0o600); err != nil {
m.Close()
return nil, err
}
// 交叉签名证书:驱动签名要它才能连到微软的驱动信任根
if cross, err := ReadEncrypted(filepath.Join(dir, "cross.enc")); err == nil && len(cross) > 0 {
m.CrossPath = filepath.Join(tmp, "cross.cer")
if werr := os.WriteFile(m.CrossPath, cross, 0o600); werr != nil {
m.Close()
return nil, werr
}
}
if prof, err := ReadEncrypted(filepath.Join(dir, "profile.enc")); err == nil && len(prof) > 0 {
m.ProfilePath = filepath.Join(tmp, "profile.mobileprovision")
if err := os.WriteFile(m.ProfilePath, prof, 0o600); err != nil {
m.Close()
return nil, err
}
}
return m, nil
}
// SignPE Authenticode 重签(会重写校验和并追加证书表)
//
// 注意:签名会追加证书表并改动 PE 校验和,而壳的 crcFile 覆盖整个文件,
// 二者互斥。带签名的产物要跳过 crcFile 校验(壳侧以 WinVerifyTrust 兜底),
// 这条规则由调用方决定,这里只负责签名本身。
func SignPE(data []byte, m *Material, workDir string) (out []byte, note string, err error) {
t := SignTools()
if t.OsslSigncode == "" {
return nil, "", &UnsupportedError{
Kind: KindPE,
Arch: "x64",
Reason: "服务端没有 osslsigncode,无法做 Authenticode 重签",
Needs: []string{"镜像里多阶段构建 osslsigncode"},
}
}
if m == nil || m.CertPath == "" {
return nil, "", fmt.Errorf("没有可用的签名证书")
}
if err := os.MkdirAll(workDir, 0o755); err != nil {
return nil, "", err
}
in := filepath.Join(workDir, "unsigned.exe")
outPath := filepath.Join(workDir, "signed.exe")
if err := os.WriteFile(in, data, 0o644); err != nil {
return nil, "", err
}
args := []string{"sign", "-pkcs12", m.CertPath, "-in", in, "-out", outPath, "-h", "sha256"}
if m.Password != "" {
args = append(args, "-pass", m.Password)
}
// 交叉签名证书(微软发布的 *-CrossCert):内核驱动签名必须带上,
// 否则签名链到不了微软的驱动信任根,Windows 不认。
if m.CrossPath != "" && fileExists(m.CrossPath) {
args = append(args, "-ac", m.CrossPath)
}
if out2, err := runCmd(workDir, t.OsslSigncode, args...); err != nil {
return nil, "", fmt.Errorf("osslsigncode 签名失败: %v: %s", err, tail(out2, 500))
}
// 验签只作为提示:自签名证书或缺少中间证书会让链校验失败,但签名本身是写进去了,
// 不能因为链不受信就把整个任务判失败(真实 CA 证书会通过)。
if logs, err := runCmd(workDir, t.OsslSigncode, "verify", outPath); err != nil {
note = "签名已写入;证书链校验未通过(自签名或缺中间证书): " + tail(strings.ReplaceAll(logs, "\n", " "), 200)
}
data, rerr := os.ReadFile(outPath)
return data, note, rerr
}
// SignIPA 用 zsign 注入 dylib 并重签整个 app bundle
func SignIPA(ipa []byte, m *Material, dylib []byte, workDir string) ([]byte, error) {
t := SignTools()
if t.Zsign == "" {
return nil, &UnsupportedError{
Kind: KindIPA,
Arch: "universal",
Reason: "服务端没有 zsign,无法注入 dylib 并重签 IPA",
Needs: []string{"镜像里放进 zsign(musl 静态版)"},
}
}
if m == nil || m.ProfilePath == "" {
return nil, &UnsupportedError{
Kind: KindIPA,
Arch: "universal",
Reason: "IPA 必须用 iOS 证书(.p12)与描述文件(.mobileprovision)重签,缺一不可",
Needs: []string{"在「签名证书」里上传 iOS 证书与描述文件,并在加壳任务里选中"},
}
}
if len(dylib) == 0 {
return nil, &UnsupportedError{
Kind: KindIPA,
Arch: "universal",
Reason: "没有 iOS 验证壳 dylib:dylib 需要用 iOS SDK 编译(Linux 上无 SDK)",
Needs: []string{"上传 POST /dev/sign-profiles 时附带的 dylib,或配置 PROTECT_IOS_DYLIB 指向已有 dylib"},
}
}
if err := os.MkdirAll(workDir, 0o755); err != nil {
return nil, err
}
in := filepath.Join(workDir, "in.ipa")
if err := os.WriteFile(in, ipa, 0o644); err != nil {
return nil, err
}
dylibPath := filepath.Join(workDir, "vfy.dylib")
if err := os.WriteFile(dylibPath, dylib, 0o644); err != nil {
return nil, err
}
out := filepath.Join(workDir, "out.ipa")
args := []string{"-k", m.CertPath, "-m", m.ProfilePath, "-l", dylibPath, "-o", out, "-f"}
if m.Password != "" {
args = append(args, "-p", m.Password)
}
args = append(args, in)
if logs, err := runCmd(workDir, t.Zsign, args...); err != nil {
return nil, fmt.Errorf("zsign 签名失败: %v: %s", err, tail(logs, 800))
}
data, err := os.ReadFile(out)
if err != nil {
return nil, fmt.Errorf("读取签名后的 IPA 失败: %w", err)
}
return data, nil
}
// DylibForIOS 取 iOS 壳 dylib:优先配置路径,其次 assets(当前为空)
func DylibForIOS() []byte {
if p := os.Getenv("PROTECT_IOS_DYLIB"); p != "" {
if b, err := os.ReadFile(p); err == nil {
return b
}
}
if fileExists("/app/tools/vfy_ios.dylib") {
if b, err := os.ReadFile("/app/tools/vfy_ios.dylib"); err == nil {
return b
}
}
return nil
}
+131
View File
@@ -0,0 +1,131 @@
package protect
// 证书资产:p12/pfx/mobileprovision 与口令一律 AES-256-GCM 加密落盘,
// 主密钥由 app.jwt_secret 派生(配置里已有,不需要额外密钥管理)。
// 数据库只存路径与元数据,私钥与口令永不出现在任何响应里。
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"verification-platform-backend/internal/config"
)
// masterKey 从 jwt_secret 派生 32 字节主密钥
func masterKey() ([]byte, error) {
secret := config.GetString("app.jwt_secret")
if secret == "" || secret == "your-secret-key" {
return nil, fmt.Errorf("app.jwt_secret 未配置,无法加密证书资产")
}
sum := sha256.Sum256([]byte("vfy-protect-signkey|" + secret))
return sum[:], nil
}
// EncryptBytes 返回 nonce||ciphertext
func EncryptBytes(plain []byte) ([]byte, error) {
key, err := masterKey()
if err != nil {
return nil, err
}
return encryptWithKey(key, plain)
}
// encryptWithKey 用指定密钥加密(便于单测,不读配置)
func encryptWithKey(key, plain []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return gcm.Seal(nonce, nonce, plain, nil), nil
}
// DecryptBytes 解 nonce||ciphertext
func DecryptBytes(enc []byte) ([]byte, error) {
key, err := masterKey()
if err != nil {
return nil, err
}
return decryptWithKey(key, enc)
}
// decryptWithKey 用指定密钥解密
func decryptWithKey(key, enc []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
if len(enc) < gcm.NonceSize() {
return nil, fmt.Errorf("密文损坏")
}
nonce, body := enc[:gcm.NonceSize()], enc[gcm.NonceSize():]
return gcm.Open(nil, nonce, body, nil)
}
// WriteEncrypted 加密写文件(0600)
func WriteEncrypted(path string, plain []byte) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
enc, err := EncryptBytes(plain)
if err != nil {
return err
}
return os.WriteFile(path, enc, 0o600)
}
// ReadEncrypted 读并解密
func ReadEncrypted(path string) ([]byte, error) {
enc, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return DecryptBytes(enc)
}
// ProfileDir 单个证书资产的目录
func ProfileDir(id uint) string {
return filepath.Join(Default().Dir, "keys", fmt.Sprintf("profile_%d", id))
}
// Fingerprint 只用于日志:不泄露内容,便于排查是不是同一份证书
func Fingerprint(b []byte) string {
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:6])
}
// 平台常量
const (
PlatformWindows = "windows"
PlatformIOS = "ios"
)
// NormalizePlatform 归一化平台名
func NormalizePlatform(p string) (string, error) {
switch strings.ToLower(strings.TrimSpace(p)) {
case "windows", "win", "pe":
return PlatformWindows, nil
case "ios", "ipa":
return PlatformIOS, nil
}
return "", fmt.Errorf("platform 只能是 windows 或 ios")
}
+90
View File
@@ -0,0 +1,90 @@
package protect
import (
"bytes"
"crypto/rand"
"os"
"path/filepath"
"testing"
)
func TestEncryptRoundTrip(t *testing.T) {
key := make([]byte, 32)
rand.Read(key)
plain := []byte("pfxpass-测试-1234")
enc, err := encryptWithKey(key, plain)
if err != nil {
t.Fatalf("加密失败: %v", err)
}
if len(enc) != len(plain)+12+16 {
t.Fatalf("密文长度异常: %d(期望 %d)", len(enc), len(plain)+28)
}
if bytes.Contains(enc, plain) {
t.Fatal("密文里出现了明文")
}
got, err := decryptWithKey(key, enc)
if err != nil {
t.Fatalf("解密失败: %v", err)
}
if !bytes.Equal(got, plain) {
t.Fatalf("往返不一致: %q", got)
}
// 换密钥必须解不开
bad := make([]byte, 32)
rand.Read(bad)
if _, err := decryptWithKey(bad, enc); err == nil {
t.Fatal("错误密钥竟然解开了")
}
// 篡改一字节必须失败
enc[len(enc)-1] ^= 0xFF
if _, err := decryptWithKey(key, enc); err == nil {
t.Fatal("篡改后的密文没被检出")
}
}
func TestWriteReadEncryptedFile(t *testing.T) {
key := make([]byte, 32)
rand.Read(key)
dir := t.TempDir()
p := filepath.Join(dir, "sub", "pass.enc")
plain := []byte("secret-pass")
enc, err := encryptWithKey(key, plain)
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, enc, 0o600); err != nil {
t.Fatal(err)
}
st, err := os.Stat(p)
if err != nil {
t.Fatal(err)
}
if st.Mode().Perm() != 0o600 {
t.Fatalf("权限应为 0600,实际 %o", st.Mode().Perm())
}
raw, _ := os.ReadFile(p)
got, err := decryptWithKey(key, raw)
if err != nil || !bytes.Equal(got, plain) {
t.Fatalf("文件往返失败: %v", err)
}
}
func TestNormalizePlatform(t *testing.T) {
cases := map[string]string{
"windows": PlatformWindows, "win": PlatformWindows, "PE": PlatformWindows,
"ios": PlatformIOS, "ipa": PlatformIOS,
}
for in, want := range cases {
got, err := NormalizePlatform(in)
if err != nil || got != want {
t.Fatalf("%s → %s (%v),期望 %s", in, got, err, want)
}
}
if _, err := NormalizePlatform("android"); err == nil {
t.Fatal("android 不该被接受(请用加壳任务类型自动判断)")
}
}
+203
View File
@@ -0,0 +1,203 @@
package protect
import (
"strings"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"time"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
)
var (
runnerOnce sync.Once
shared *Runner
)
// Default 返回进程内共享的 Runner(目录可用 PROTECT_DIR 覆盖,默认 data/protect)
func Default() *Runner {
runnerOnce.Do(func() { shared = NewRunner(os.Getenv("PROTECT_DIR")) })
return shared
}
// createTask 建库记录 + 把源文件落盘,返回任务与源文件路径
func createTask(app *model.Application, userID uint, srcName string, data []byte, signProfileID *uint, certIdentity int, theme string) (*model.ProtectTask, string, error) {
det := DetectFile(data, srcName)
if det.Kind == KindUnknown {
return nil, "", fmt.Errorf("无法识别的文件格式(既不是 PE,也不是 APK/IPA/ELF/Mach-O)")
}
if err := Injectable(det.Kind); err != nil {
return nil, "", err
}
if det.Kind == KindPE && HasVfy(data) {
return nil, "", fmt.Errorf("这个文件已经是云端加密后的产物(带 .vfy 节),请上传未加密的原始程序")
}
// 签名证书必须在建任务时就落库:execute 是 go 协程,事后 UPDATE 有窗口
// 被它读到 NULL,导致证书被静默忽略(任务照样成功,只是没重签)。
task := &model.ProtectTask{
ApplicationID: app.ID,
UserID: userID,
SourceName: filepath.Base(srcName),
SourceSize: int64(len(data)),
Kind: string(det.Kind),
Arch: det.Arch,
Status: "pending",
SignProfileID: signProfileID,
CertIdentity: certIdentity,
ShellTheme: theme,
}
if err := database.DB.Create(task).Error; err != nil {
return nil, "", fmt.Errorf("创建任务失败: %w", err)
}
srcPath, err := Default().SaveSource(task.ID, srcName, data)
if err != nil {
database.DB.Model(task).Updates(map[string]interface{}{"status": "failed", "message": "保存源文件失败"})
return task, "", fmt.Errorf("保存源文件失败: %w", err)
}
return task, srcPath, nil
}
// execute 真正跑加壳并回写任务状态
func execute(taskID uint, srcPath, srcName string, cfg []byte) (Info, error) {
r := Default()
now := time.Now()
database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).
Updates(map[string]interface{}{"status": "running", "started_at": &now})
outPath := r.OutPath(taskID, srcName)
var tk model.ProtectTask
database.DB.First(&tk, taskID)
info, err := r.RunWithTask(&tk, srcPath, outPath, cfg)
if err != nil {
log.Printf("[protect] task %d failed: %v", taskID, err)
fin := time.Now()
database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).Updates(map[string]interface{}{
"status": "failed", "message": err.Error(), "finished_at": &fin,
})
return info, err
}
fin := time.Now()
database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).Updates(map[string]interface{}{
"status": "done",
"message": infoMessage(info),
"output_name": filepath.Base(outPath),
"output_size": int64(info.OutSize),
"output_path": outPath,
"crc_vfy": fmt.Sprintf("%08x", info.CrcVfy),
"crc_file": fmt.Sprintf("%08x", info.CrcFile),
"finished_at": &fin,
"arch": info.Arch,
})
log.Printf("[protect] task %d done: %s (%d → %d 字节)", taskID, outPath, info.OriginalSource, info.OutSize)
return info, nil
}
// CreateAndRun 建任务 → 落盘源文件 → 异步加壳。返回的任务状态为 pending。
func CreateAndRun(app *model.Application, userID uint, srcName string, data []byte, baseURL string) (*model.ProtectTask, error) {
return CreateAndRunSigned(app, userID, srcName, data, baseURL, nil)
}
// CreateAndRunSigned 同 CreateAndRun,但带重签证书(nil = 不重签)。
// 证书在建任务时就写进 task,execute 协程启动即可见,没有竞态。
func CreateAndRunSigned(app *model.Application, userID uint, srcName string, data []byte, baseURL string, signProfileID *uint) (*model.ProtectTask, error) {
return CreateAndRunSignedIdentity(app, userID, srcName, data, baseURL, signProfileID, 0)
}
// CreateAndRunSignedIdentity 同 CreateAndRunSigned,并指定证书文件里的第几套身份(0/1 = 第一套)
func CreateAndRunSignedIdentity(app *model.Application, userID uint, srcName string, data []byte, baseURL string, signProfileID *uint, certIdentity int) (*model.ProtectTask, error) {
return CreateAndRunThemed(app, userID, srcName, data, baseURL, signProfileID, certIdentity, "classic")
}
// CreateAndRunThemed 同 CreateAndRunSignedIdentity,并指定验证界面皮肤
func CreateAndRunThemed(app *model.Application, userID uint, srcName string, data []byte, baseURL string, signProfileID *uint, certIdentity int, theme string) (*model.ProtectTask, error) {
return CreateAndRunThemedVer(app, userID, srcName, data, baseURL, signProfileID, certIdentity, theme, "")
}
// CreateAndRunThemedVer 同上,并显式指定「程序版本」(壳拿它做自动更新比对;空则不比对)
func CreateAndRunThemedVer(app *model.Application, userID uint, srcName string, data []byte, baseURL string, signProfileID *uint, certIdentity int, theme, programVer string) (*model.ProtectTask, error) {
if theme == "" {
theme = "classic"
}
task, srcPath, err := createTask(app, userID, srcName, data, signProfileID, certIdentity, theme)
if err != nil {
return task, err
}
ver := strings.TrimSpace(programVer)
if ver == "" {
ver = programVersion(task.VersionID) // 没手填就退回来源版本的版本号
}
cfg := BuildCfgThemedVer(app.AppKey, app.Name, baseURL, theme, ver)
go execute(task.ID, srcPath, srcName, cfg)
return task, nil
}
// CreateAndRunSync 同步加壳(MCP 这类需要立刻拿到结果调用方用)
func CreateAndRunSync(app *model.Application, userID uint, srcName string, data []byte, baseURL string) (*model.ProtectTask, Info, error) {
return CreateAndRunSyncWithVersion(app, userID, srcName, data, baseURL, 0)
}
// CreateAndRunSyncWithVersion 同步加壳并记录来源版本(versionID 可为 0)
func CreateAndRunSyncWithVersion(app *model.Application, userID uint, srcName string, data []byte, baseURL string, versionID uint) (*model.ProtectTask, Info, error) {
return CreateAndRunSyncWithSign(app, userID, srcName, data, baseURL, versionID, nil)
}
// CreateAndRunSyncWithSign 同步加壳,可带证书与来源版本
func CreateAndRunSyncWithSign(app *model.Application, userID uint, srcName string, data []byte, baseURL string, versionID uint, signProfileID *uint) (*model.ProtectTask, Info, error) {
return CreateAndRunSyncThemed(app, userID, srcName, data, baseURL, versionID, signProfileID, "classic")
}
// CreateAndRunSyncThemed 同步加壳 + 皮肤
func CreateAndRunSyncThemed(app *model.Application, userID uint, srcName string, data []byte, baseURL string, versionID uint, signProfileID *uint, theme string) (*model.ProtectTask, Info, error) {
if theme == "" {
theme = "classic"
}
task, srcPath, err := createTask(app, userID, srcName, data, signProfileID, 0, theme)
if err != nil {
return task, Info{}, err
}
if versionID > 0 && task != nil {
database.DB.Model(task).Update("version_id", versionID)
task.VersionID = versionID
}
info, err := execute(task.ID, srcPath, srcName, BuildCfgThemedVer(app.AppKey, app.Name, baseURL, theme, programVersion(task.VersionID)))
if err != nil {
return task, info, err
}
return task, info, nil
}
// programVersion 取来源版本的版本号;没有来源版本就返回空(壳不做更新比对)
func programVersion(versionID uint) string {
if versionID == 0 {
return ""
}
var v model.Version
if err := database.DB.First(&v, versionID).Error; err != nil {
return ""
}
return v.Version
}
// WaitSource 等源文件出现(版本包按需解包是异步的,最多等 3 秒)
func WaitSource(path string) error {
for i := 0; i < 10; i++ {
if st, err := os.Stat(path); err == nil && st.Size() > 0 {
return nil
}
time.Sleep(300 * time.Millisecond)
}
return fmt.Errorf("源文件不存在: %s", path)
}
// infoMessage 任务备注:PE 报入口变化,其他类型用各自说明
func infoMessage(info Info) string {
if info.Note != "" {
return info.Note
}
return fmt.Sprintf("入口 0x%x → 0x%x,.vfy RVA=0x%x", info.EntryOld, info.EntryNew, info.SecRVA)
}
+172
View File
@@ -0,0 +1,172 @@
package protect
// 证书用途分类:应用签名 vs 驱动签名。
//
// 这是两套不同的东西,靠证书里的 Extended Key Usage(EKU)区分:
// - 应用(用户态 exe/dll/msi/脚本):EKU 里要有 Code Signing
// (id-kp-codeSigning 1.3.6.1.5.5.7.3.3,老微软证书用
// 1.3.6.1.4.1.311.2.1.21 个人代码签名 / 1.3.6.1.4.1.311.2.1.22 商业代码签名)
// - 驱动(内核态 .sys):EKU 里要有 Kernel Mode Code Signing
// 1.3.6.1.4.1.311.61.1.1(少数还带 ELAM 1.3.6.1.4.1.311.61.4.1)
//
// 一张证书可以两种都有(少见),也可能只有其中一种。**没有 EKU 扩展的老证书**
// 按通用处理(历史上 Windows 对无 EKU 的证书不做用途限制),但要单独标出来。
import (
"crypto/x509"
"encoding/asn1"
"strings"
)
// 用途判定结果
type CertUsage struct {
App bool `json:"app"` // 可签应用(exe/dll)
Driver bool `json:"driver"` // 可签内核驱动(.sys)
NoEKU bool `json:"no_eku"` // 证书里没有 EKU 扩展(老证书,按通用处理)
HasEKUExt bool `json:"has_eku_ext"` // 有 EKU 扩展
OIDs []string `json:"oids"` // EKU 里的用途 OID
Label string `json:"label"` // 应用 / 驱动 / 应用+驱动 / 不可用
IsCA bool `json:"is_ca"` // 是 CA 证书(不能当签名证书用)
DetailNote string `json:"detail_note"` // 补充说明
}
var (
oidEKUCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
oidEKUMSCodeSigningCert = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 21} // Microsoft Individual Code Signing
oidMSCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22} // Microsoft Commercial Code Signing
oidKPPlatformCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 13}
oidKPWindowsSystemComponent = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 6} // Windows System Component Verification
oidKPKernelModeCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1} // Kernel Mode Code Signing
oidKPHardwareDriverExt = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 2} // 驱动扩展
oidKPELAM = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 4, 1} // Early Launch Anti-Malware
oidKPHALExtension = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 8, 1} // HAL 扩展
oidKPCodeIntegrity = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 5} // Windows Hardware Driver Verification
)
// ClassifyUsage 判断一张证书能签什么
func ClassifyUsage(c *x509.Certificate) CertUsage {
u := CertUsage{
IsCA: c.IsCA || (c.KeyUsage&x509.KeyUsageCertSign) != 0,
}
for _, oid := range c.UnknownExtKeyUsage {
u.OIDs = append(u.OIDs, oid.String())
switch {
case oid.Equal(oidEKUCodeSigning), oid.Equal(oidEKUMSCodeSigningCert), oid.Equal(oidMSCommercialCodeSigning):
u.App = true
case oid.Equal(oidKPKernelModeCodeSigning), oid.Equal(oidKPHardwareDriverExt),
oid.Equal(oidKPELAM), oid.Equal(oidKPHALExtension), oid.Equal(oidKPWindowsSystemComponent),
oid.Equal(oidKPCodeIntegrity):
u.Driver = true
}
}
// Go 会把认识的 EKU 解析进 ExtKeyUsage,不留在 UnknownExtKeyUsage。
// 注意 x509.ExtKeyUsageMicrosoftKernelCodeSigning(13) 就是 KMCS,
// 只看 UnknownExtKeyUsage 会把驱动证书误判成「应用」。
for _, e := range c.ExtKeyUsage {
switch e {
case x509.ExtKeyUsageCodeSigning:
u.App = true
if !containsStr(u.OIDs, oidEKUCodeSigning.String()) {
u.OIDs = append(u.OIDs, oidEKUCodeSigning.String())
}
case x509.ExtKeyUsageMicrosoftCommercialCodeSigning: // 12 = 1.3.6.1.4.1.311.2.1.22
u.App = true
if !containsStr(u.OIDs, oidMSCommercialCodeSigning.String()) {
u.OIDs = append(u.OIDs, oidMSCommercialCodeSigning.String())
}
case x509.ExtKeyUsageMicrosoftKernelCodeSigning: // 13 = 1.3.6.1.4.1.311.61.1.1(KMCS)
u.Driver = true
if !containsStr(u.OIDs, oidKPKernelModeCodeSigning.String()) {
u.OIDs = append(u.OIDs, oidKPKernelModeCodeSigning.String())
}
}
}
// 有没有 EKU 扩展?没有就是历史证书,Windows 不按用途限制
for _, ext := range c.Extensions {
if ext.Id.Equal(asn1.ObjectIdentifier{2, 5, 29, 37}) { // 2.5.29.37 extKeyUsage
u.HasEKUExt = true
break
}
}
if !u.HasEKUExt {
u.NoEKU = true
// 无 EKU:按通用处理(能签应用;驱动要 KMCS,无 EKU 的老证书历史上也能签驱动)
u.App = true
u.Driver = true
u.DetailNote = "证书里没有 EKU 扩展(多为早期证书),按通用用途处理"
}
switch {
case u.IsCA && !u.HasEKUExt:
// 没有任何 EKU 的 CA 证书:这是签发者,不是签名者,不能拿去签代码
u.Label = "CA 证书(不能签名)"
u.App, u.Driver = false, false
case u.IsCA:
// 带明确 EKU 的自签证书(自建 CA 签发的测试证书常见)照样能签,
// 只是链不会被信任;这里不拦,但要说明
u.DetailNote = strings.TrimSpace(u.DetailNote + " 该证书本身也带 CA 标记,签出的产物链不会被系统信任")
case u.App && u.Driver && !u.NoEKU:
u.Label = "应用 + 驱动"
case u.App && u.Driver:
u.Label = "应用 + 驱动(未声明用途)"
case u.App:
u.Label = "应用"
case u.Driver:
u.Label = "驱动"
default:
u.Label = "不可用于代码签名"
u.DetailNote = strings.TrimSpace(u.DetailNote + " 证书的 EKU 里没有代码签名用途")
}
return u
}
func containsStr(list []string, s string) bool {
for _, v := range list {
if v == s {
return true
}
}
return false
}
// WantsDriver 某个文件名是否属于「驱动」范畴
func WantsDriver(name string) bool {
n := strings.ToLower(name)
return strings.HasSuffix(n, ".sys") || strings.HasSuffix(n, ".cat") ||
strings.HasSuffix(n, ".inf") || strings.HasSuffix(n, ".efi")
}
// PESubsystem 取 PE 的子系统编号:1 = NATIVE(驱动),2 = GUI,3 = CONSOLE
func PESubsystem(data []byte) (uint16, bool) {
if len(data) < 0x40 || data[0] != 'M' || data[1] != 'Z' {
return 0, false
}
peOff := int(uint32(data[0x3c]) | uint32(data[0x3d])<<8 | uint32(data[0x3e])<<16 | uint32(data[0x3f])<<24)
if peOff <= 0 || peOff+0x40 > len(data) {
return 0, false
}
if data[peOff] != 'P' || data[peOff+1] != 'E' || data[peOff+2] != 0 || data[peOff+3] != 0 {
return 0, false
}
optOff := peOff + 24
magic := uint16(data[optOff]) | uint16(data[optOff+1])<<8
// PE32 子系统在 OptionalHeader + 0x44;PE32+ 在 +0x44 也是(68)
if magic != 0x10b && magic != 0x20b {
return 0, false
}
if optOff+0x46 > len(data) {
return 0, false
}
return uint16(data[optOff+0x44]) | uint16(data[optOff+0x45])<<8, true
}
// IsDriverPE 判断一个 PE 是不是内核驱动(子系统 NATIVE 或 .sys 扩展名)
func IsDriverPE(data []byte, name string) bool {
if sub, ok := PESubsystem(data); ok && sub == 1 {
return true
}
return strings.HasSuffix(strings.ToLower(name), ".sys")
}
+17 -17
View File
@@ -199,7 +199,7 @@ func handleGetAgentRequests(c *gin.Context) {
AgentID uint `json:"agent_id"`
AgentName string `json:"agent_name"`
AgentEmail string `json:"agent_email"`
AdminID uint `json:"admin_id"`
AdminID uint `json:"admin_id"`
ApplicationID uint `json:"application_id"`
AppName string `json:"app_name"`
Type string `json:"type"`
@@ -230,7 +230,7 @@ func handleGetAgentRequests(c *gin.Context) {
AgentID: req.AgentID,
AgentName: agentName,
AgentEmail: agentEmail,
AdminID: req.AdminID,
AdminID: req.AdminID,
ApplicationID: req.ApplicationID,
AppName: appName,
Type: req.Type,
@@ -271,8 +271,8 @@ func handleGetMyRequests(c *gin.Context) {
type RequestResponse struct {
ID uint `json:"id"`
AgentID uint `json:"agent_id"`
AdminID uint `json:"admin_id"`
AdminName string `json:"admin_name"`
AdminID uint `json:"admin_id"`
AdminName string `json:"admin_name"`
ApplicationID uint `json:"application_id"`
AppName string `json:"app_name"`
Type string `json:"type"`
@@ -297,8 +297,8 @@ func handleGetMyRequests(c *gin.Context) {
result = append(result, RequestResponse{
ID: req.ID,
AgentID: req.AgentID,
AdminID: req.AdminID,
AdminName: AdminName,
AdminID: req.AdminID,
AdminName: AdminName,
ApplicationID: req.ApplicationID,
AppName: appName,
Type: req.Type,
@@ -357,7 +357,7 @@ func handleInviteAgent(c *gin.Context) {
request := model.AgentApplicationRequest{
AgentID: req.AgentID,
AdminID: userID,
AdminID: userID,
ApplicationID: req.ApplicationID,
Type: "invite",
Status: "pending",
@@ -383,7 +383,7 @@ func handleInviteAgent(c *gin.Context) {
func handleRequestAuthorization(c *gin.Context) {
userID := c.GetUint("user_id")
var req struct {
AdminID uint `json:"admin_id"`
AdminID uint `json:"admin_id"`
ApplicationID uint `json:"application_id"`
Message string `json:"message"`
}
@@ -423,7 +423,7 @@ func handleRequestAuthorization(c *gin.Context) {
request := model.AgentApplicationRequest{
AgentID: userID,
AdminID: req.AdminID,
AdminID: req.AdminID,
ApplicationID: req.ApplicationID,
Type: "request",
Status: "pending",
@@ -436,13 +436,13 @@ func handleRequestAuthorization(c *gin.Context) {
}
response.Success(c, gin.H{
"id": request.ID,
"id": request.ID,
"admin_id": request.AdminID,
"admin_name": Admin.Username,
"app_id": request.ApplicationID,
"app_name": app.Name,
"type": request.Type,
"status": request.Status,
"app_id": request.ApplicationID,
"app_name": app.Name,
"type": request.Type,
"status": request.Status,
})
}
@@ -471,7 +471,7 @@ func handleApproveRequest(c *gin.Context) {
agentApp := model.AgentApplication{
AgentID: req.AgentID,
ApplicationID: req.ApplicationID,
AdminID: userID,
AdminID: userID,
Discount: 1.0,
Status: "active",
IsReceived: true,
@@ -629,8 +629,8 @@ func handleUpdateAgentApp(c *gin.Context) {
agentAppID := c.Param("id")
var reqBody struct {
Discount *float64 `json:"discount"`
Status *string `json:"status"`
Discount *float64 `json:"discount"`
Status *string `json:"status"`
}
if err := c.ShouldBindJSON(&reqBody); err != nil {
response.Error(c, 400, "参数错误")
+28 -28
View File
@@ -42,8 +42,8 @@ type AgentTreeNode struct {
CreatedAt string `json:"created_at"`
LastLoginAt string `json:"last_login_at"`
Balance float64 `json:"balance"`
CanCreateAgent bool `json:"can_create_agent"`
CanViewCloudData bool `json:"can_view_cloud_data"`
CanCreateAgent bool `json:"can_create_agent"`
CanViewCloudData bool `json:"can_view_cloud_data"`
CardsCount int `json:"cards_count"`
ChildAgentsCount int `json:"child_agents_count"`
Children []AgentTreeNode `json:"children,omitempty"`
@@ -154,9 +154,9 @@ func handleGetAgents(c *gin.Context) {
LastLoginAt: lastLoginAt,
Balance: user.Balance,
TotalConsumption: user.TotalConsumption,
CanCreateAgent: user.CanCreateAgent,
CanViewCloudData: user.CanViewCloudData,
CardsCount: cardsCountMap[user.ID],
CanCreateAgent: user.CanCreateAgent,
CanViewCloudData: user.CanViewCloudData,
CardsCount: cardsCountMap[user.ID],
ChildAgentsCount: childCountMap[user.ID],
})
}
@@ -232,9 +232,9 @@ func handleGetAgentsTree(c *gin.Context) {
CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
LastLoginAt: lastLoginAt,
Balance: user.Balance,
CanCreateAgent: user.CanCreateAgent,
CanViewCloudData: user.CanViewCloudData,
CardsCount: int(cardsCount),
CanCreateAgent: user.CanCreateAgent,
CanViewCloudData: user.CanViewCloudData,
CardsCount: int(cardsCount),
ChildAgentsCount: int(childAgentsCount),
}
@@ -404,22 +404,22 @@ func handleGetAgentDetail(c *gin.Context) {
}
response.Success(c, gin.H{
"id": user.ID,
"username": user.Username,
"email": email,
"avatar": user.Avatar,
"status": user.Status,
"role": user.Role,
"parent_agent_id": user.ParentAgentID,
"parent_agent_name": parentAgentName,
"can_create_agent": user.CanCreateAgent,
"can_view_cloud_data": user.CanViewCloudData,
"balance": user.Balance,
"created_at": user.CreatedAt.Format("2006-01-02 15:04:05"),
"last_login_at": lastLoginAt,
"cards": cardsResponse,
"cards_count": len(cardsResponse),
"child_agents_count": len(childAgents),
"id": user.ID,
"username": user.Username,
"email": email,
"avatar": user.Avatar,
"status": user.Status,
"role": user.Role,
"parent_agent_id": user.ParentAgentID,
"parent_agent_name": parentAgentName,
"can_create_agent": user.CanCreateAgent,
"can_view_cloud_data": user.CanViewCloudData,
"balance": user.Balance,
"created_at": user.CreatedAt.Format("2006-01-02 15:04:05"),
"last_login_at": lastLoginAt,
"cards": cardsResponse,
"cards_count": len(cardsResponse),
"child_agents_count": len(childAgents),
})
}
@@ -724,9 +724,9 @@ func handleRechargeAgent(c *gin.Context) {
service.LogOperation(c, "recharge", "agent", &user.ID, fmt.Sprintf("为代理充值: %.2f, 余额: %.2f -> %.2f", req.Amount, user.Balance, newBalance), nil)
response.Success(c, gin.H{
"balance": newBalance,
"recharge": req.Amount,
"agent_id": user.ID,
"agent_name": user.Username,
"balance": newBalance,
"recharge": req.Amount,
"agent_id": user.ID,
"agent_name": user.Username,
})
}
+13 -13
View File
@@ -136,11 +136,11 @@ func handleGetAllAnnouncements(c *gin.Context) {
}
response.Success(c, gin.H{
"announcements": result,
"total": total,
"active_count": activeCount,
"announcements": result,
"total": total,
"active_count": activeCount,
"inactive_count": inactiveCount,
"top_count": topCount,
"top_count": topCount,
})
}
@@ -168,16 +168,16 @@ func handleGetAnnouncementByID(c *gin.Context) {
}
response.Success(c, gin.H{
"id": announcement.ID,
"application_id": announcement.ApplicationID,
"id": announcement.ID,
"application_id": announcement.ApplicationID,
"application_name": appNameMap[announcement.ApplicationID],
"title": announcement.Title,
"content": announcement.Content,
"type": announcement.Type,
"status": announcement.Status,
"is_top": announcement.IsTop,
"created_at": announcement.CreatedAt,
"updated_at": announcement.UpdatedAt,
"title": announcement.Title,
"content": announcement.Content,
"type": announcement.Type,
"status": announcement.Status,
"is_top": announcement.IsTop,
"created_at": announcement.CreatedAt,
"updated_at": announcement.UpdatedAt,
})
}
+154 -140
View File
@@ -89,48 +89,48 @@ func handleCreateApplication(c *gin.Context) {
userID := c.GetUint("user_id")
var req struct {
Name string `form:"name" json:"name"`
Description string `form:"description" json:"description"`
BillingType string `form:"billing_type" json:"billing_type"`
LoginPolicy string `form:"login_policy" json:"login_policy"`
EncryptType string `form:"encrypt_type" json:"encrypt_type"`
EncryptKey string `form:"encrypt_key" json:"encrypt_key"`
BindType string `form:"bind_type" json:"bind_type"`
MaxDevices string `form:"max_devices" json:"max_devices"`
ChangeLimit string `form:"change_limit" json:"change_limit"`
ChangeInterval string `form:"change_interval" json:"change_interval"`
ChangeExceedAction string `form:"change_exceed_action" json:"change_exceed_action"`
ChangeDeductAmount string `form:"change_deduct_amount" json:"change_deduct_amount"`
MultiOpenMode string `form:"multi_open_mode" json:"multi_open_mode"`
MaxInstances string `form:"max_instances" json:"max_instances"`
EnableTrial string `form:"enable_trial" json:"enable_trial"`
TrialBalance string `form:"trial_balance" json:"trial_balance"`
TrialDays string `form:"trial_days" json:"trial_days"`
EnableFreePeriod string `form:"enable_free_period" json:"enable_free_period"`
FreePeriodType string `form:"free_period_type" json:"free_period_type"`
FreePeriodStart string `form:"free_period_start" json:"free_period_start"`
FreePeriodEnd string `form:"free_period_end" json:"free_period_end"`
FreePeriodWeekdays string `form:"free_period_weekdays" json:"free_period_weekdays"`
FreePeriodStartTime string `form:"free_period_start_time" json:"free_period_start_time"`
FreePeriodEndTime string `form:"free_period_end_time" json:"free_period_end_time"`
HeartbeatInterval string `form:"heartbeat_interval" json:"heartbeat_interval"`
HeartbeatTimeout string `form:"heartbeat_timeout" json:"heartbeat_timeout"`
MaxAttempts string `form:"max_attempts" json:"max_attempts"`
LockDuration string `form:"lock_duration" json:"lock_duration"`
DeductionMode string `form:"deduction_mode" json:"deduction_mode"`
DeductionType string `form:"deduction_type" json:"deduction_type"`
DeductionInterval string `form:"deduction_interval" json:"deduction_interval"`
DeductionUnit string `form:"deduction_unit" json:"deduction_unit"`
DeductionAmount string `form:"deduction_amount" json:"deduction_amount"`
DeductionCycle string `form:"deduction_cycle" json:"deduction_cycle"`
AllowRegister string `form:"allow_register" json:"allow_register"`
EnableLoginVerify string `form:"enable_login_verify" json:"enable_login_verify"`
EnableRegisterVerify string `form:"enable_register_verify" json:"enable_register_verify"`
EnablePasswordReset string `form:"enable_password_reset" json:"enable_password_reset"`
PasswordResetMethod string `form:"password_reset_method" json:"password_reset_method"`
PasswordResetEmailID uint `form:"password_reset_email_id" json:"password_reset_email_id"`
PasswordResetSmsID uint `form:"password_reset_sms_id" json:"password_reset_sms_id"`
Status string `form:"status" json:"status"`
Name string `form:"name" json:"name"`
Description string `form:"description" json:"description"`
BillingType string `form:"billing_type" json:"billing_type"`
LoginPolicy string `form:"login_policy" json:"login_policy"`
EncryptType string `form:"encrypt_type" json:"encrypt_type"`
EncryptKey string `form:"encrypt_key" json:"encrypt_key"`
BindType string `form:"bind_type" json:"bind_type"`
MaxDevices string `form:"max_devices" json:"max_devices"`
ChangeLimit string `form:"change_limit" json:"change_limit"`
ChangeInterval string `form:"change_interval" json:"change_interval"`
ChangeExceedAction string `form:"change_exceed_action" json:"change_exceed_action"`
ChangeDeductAmount string `form:"change_deduct_amount" json:"change_deduct_amount"`
MultiOpenMode string `form:"multi_open_mode" json:"multi_open_mode"`
MaxInstances string `form:"max_instances" json:"max_instances"`
EnableTrial string `form:"enable_trial" json:"enable_trial"`
TrialBalance string `form:"trial_balance" json:"trial_balance"`
TrialDays string `form:"trial_days" json:"trial_days"`
EnableFreePeriod string `form:"enable_free_period" json:"enable_free_period"`
FreePeriodType string `form:"free_period_type" json:"free_period_type"`
FreePeriodStart string `form:"free_period_start" json:"free_period_start"`
FreePeriodEnd string `form:"free_period_end" json:"free_period_end"`
FreePeriodWeekdays string `form:"free_period_weekdays" json:"free_period_weekdays"`
FreePeriodStartTime string `form:"free_period_start_time" json:"free_period_start_time"`
FreePeriodEndTime string `form:"free_period_end_time" json:"free_period_end_time"`
HeartbeatInterval string `form:"heartbeat_interval" json:"heartbeat_interval"`
HeartbeatTimeout string `form:"heartbeat_timeout" json:"heartbeat_timeout"`
MaxAttempts string `form:"max_attempts" json:"max_attempts"`
LockDuration string `form:"lock_duration" json:"lock_duration"`
DeductionMode string `form:"deduction_mode" json:"deduction_mode"`
DeductionType string `form:"deduction_type" json:"deduction_type"`
DeductionInterval string `form:"deduction_interval" json:"deduction_interval"`
DeductionUnit string `form:"deduction_unit" json:"deduction_unit"`
DeductionAmount string `form:"deduction_amount" json:"deduction_amount"`
DeductionCycle string `form:"deduction_cycle" json:"deduction_cycle"`
AllowRegister string `form:"allow_register" json:"allow_register"`
EnableLoginVerify string `form:"enable_login_verify" json:"enable_login_verify"`
EnableRegisterVerify string `form:"enable_register_verify" json:"enable_register_verify"`
EnablePasswordReset string `form:"enable_password_reset" json:"enable_password_reset"`
PasswordResetMethod string `form:"password_reset_method" json:"password_reset_method"`
PasswordResetEmailID uint `form:"password_reset_email_id" json:"password_reset_email_id"`
PasswordResetSmsID uint `form:"password_reset_sms_id" json:"password_reset_sms_id"`
Status string `form:"status" json:"status"`
}
if err := c.ShouldBind(&req); err != nil {
response.Error(c, 400, "参数错误: "+err.Error())
@@ -205,49 +205,49 @@ func handleCreateApplication(c *gin.Context) {
}
app := model.Application{
UserID: userID,
Name: req.Name,
Description: req.Description,
AppKey: appKey,
EncryptKey: encryptKey,
BillingType: req.BillingType,
LoginPolicy: loginPolicy,
EncryptType: encryptType,
BindType: req.BindType,
MaxDevices: maxDevices,
ChangeLimit: changeLimit,
ChangeInterval: changeInterval,
ChangeExceedAction: changeExceedAction,
ChangeDeductAmount: changeDeductAmount,
MultiOpenMode: multiOpenMode,
MaxInstances: maxInstances,
EnableTrial: enableTrial,
TrialBalance: trialBalance,
TrialDays: trialDays,
EnableFreePeriod: enableFreePeriod,
FreePeriodType: req.FreePeriodType,
FreePeriodStart: req.FreePeriodStart,
FreePeriodEnd: req.FreePeriodEnd,
FreePeriodWeekdays: req.FreePeriodWeekdays,
FreePeriodStartTime: req.FreePeriodStartTime,
FreePeriodEndTime: req.FreePeriodEndTime,
HeartbeatInterval: heartbeatInterval,
HeartbeatTimeout: heartbeatTimeout,
MaxAttempts: maxAttempts,
LockDuration: lockDuration,
DeductionMode: req.DeductionMode,
DeductionType: req.DeductionType,
DeductionInterval: deductionInterval,
DeductionUnit: deductionUnit,
DeductionAmount: deductionAmount,
AllowRegister: allowRegister,
EnableLoginVerify: enableLoginVerify,
EnableRegisterVerify: enableRegisterVerify,
EnablePasswordReset: enablePasswordReset,
PasswordResetMethod: passwordResetMethod,
PasswordResetEmailID: passwordResetEmailID,
PasswordResetSmsID: passwordResetSmsID,
Status: "active",
UserID: userID,
Name: req.Name,
Description: req.Description,
AppKey: appKey,
EncryptKey: encryptKey,
BillingType: req.BillingType,
LoginPolicy: loginPolicy,
EncryptType: encryptType,
BindType: req.BindType,
MaxDevices: maxDevices,
ChangeLimit: changeLimit,
ChangeInterval: changeInterval,
ChangeExceedAction: changeExceedAction,
ChangeDeductAmount: changeDeductAmount,
MultiOpenMode: multiOpenMode,
MaxInstances: maxInstances,
EnableTrial: enableTrial,
TrialBalance: trialBalance,
TrialDays: trialDays,
EnableFreePeriod: enableFreePeriod,
FreePeriodType: req.FreePeriodType,
FreePeriodStart: req.FreePeriodStart,
FreePeriodEnd: req.FreePeriodEnd,
FreePeriodWeekdays: req.FreePeriodWeekdays,
FreePeriodStartTime: req.FreePeriodStartTime,
FreePeriodEndTime: req.FreePeriodEndTime,
HeartbeatInterval: heartbeatInterval,
HeartbeatTimeout: heartbeatTimeout,
MaxAttempts: maxAttempts,
LockDuration: lockDuration,
DeductionMode: req.DeductionMode,
DeductionType: req.DeductionType,
DeductionInterval: deductionInterval,
DeductionUnit: deductionUnit,
DeductionAmount: deductionAmount,
AllowRegister: allowRegister,
EnableLoginVerify: enableLoginVerify,
EnableRegisterVerify: enableRegisterVerify,
EnablePasswordReset: enablePasswordReset,
PasswordResetMethod: passwordResetMethod,
PasswordResetEmailID: passwordResetEmailID,
PasswordResetSmsID: passwordResetSmsID,
Status: "active",
}
if err := database.DB.Create(&app).Error; err != nil {
@@ -297,50 +297,53 @@ func generateSecretKey() string {
func handleUpdateApplication(c *gin.Context) {
userID := c.GetUint("user_id")
var req struct {
Name string `form:"name" json:"name"`
Description string `form:"description" json:"description"`
BillingType string `form:"billing_type" json:"billing_type"`
LoginPolicy string `form:"login_policy" json:"login_policy"`
AllowRegister bool `form:"allow_register" json:"allow_register"`
EnableLoginVerify bool `form:"enable_login_verify" json:"enable_login_verify"`
EnableRegisterVerify bool `form:"enable_register_verify" json:"enable_register_verify"`
VerifyMethod string `form:"verify_method" json:"verify_method"`
EmailConfigID *uint `form:"email_config_id" json:"email_config_id"`
SmsConfigID *uint `form:"sms_config_id" json:"sms_config_id"`
EncryptType string `form:"encrypt_type" json:"encrypt_type"`
EncryptKey string `form:"encrypt_key" json:"encrypt_key"`
BindType string `form:"bind_type" json:"bind_type"`
MaxDevices int `form:"max_devices" json:"max_devices"`
ChangeLimit int `form:"change_limit" json:"change_limit"`
ChangeInterval int `form:"change_interval" json:"change_interval"`
ChangeExceedAction string `form:"change_exceed_action" json:"change_exceed_action"`
ChangeDeductAmount float64 `form:"change_deduct_amount" json:"change_deduct_amount"`
MultiOpenMode string `form:"multi_open_mode" json:"multi_open_mode"`
MaxInstances int `form:"max_instances" json:"max_instances"`
EnableTrial bool `form:"enable_trial" json:"enable_trial"`
TrialBalance float64 `form:"trial_balance" json:"trial_balance"`
TrialDays int `form:"trial_days" json:"trial_days"`
EnableFreePeriod bool `form:"enable_free_period" json:"enable_free_period"`
FreePeriodType string `form:"free_period_type" json:"free_period_type"`
FreePeriodStart string `form:"free_period_start" json:"free_period_start"`
FreePeriodEnd string `form:"free_period_end" json:"free_period_end"`
FreePeriodWeekdays string `form:"free_period_weekdays" json:"free_period_weekdays"`
FreePeriodStartTime string `form:"free_period_start_time" json:"free_period_start_time"`
FreePeriodEndTime string `form:"free_period_end_time" json:"free_period_end_time"`
HeartbeatInterval int `form:"heartbeat_interval" json:"heartbeat_interval"`
HeartbeatTimeout int `form:"heartbeat_timeout" json:"heartbeat_timeout"`
MaxAttempts int `form:"max_attempts" json:"max_attempts"`
LockDuration int `form:"lock_duration" json:"lock_duration"`
Status string `form:"status" json:"status"`
DeductionMode string `form:"deduction_mode" json:"deduction_mode"`
DeductionType string `form:"deduction_type" json:"deduction_type"`
DeductionInterval int `form:"deduction_interval" json:"deduction_interval"`
DeductionUnit string `form:"deduction_unit" json:"deduction_unit"`
DeductionAmount float64 `form:"deduction_amount" json:"deduction_amount"`
EnablePasswordReset bool `form:"enable_password_reset" json:"enable_password_reset"`
PasswordResetMethod string `form:"password_reset_method" json:"password_reset_method"`
PasswordResetEmailID *uint `form:"password_reset_email_id" json:"password_reset_email_id"`
PasswordResetSmsID *uint `form:"password_reset_sms_id" json:"password_reset_sms_id"`
Name string `form:"name" json:"name"`
Description string `form:"description" json:"description"`
BillingType string `form:"billing_type" json:"billing_type"`
LoginPolicy string `form:"login_policy" json:"login_policy"`
LoginMode string `form:"login_mode" json:"login_mode"`
CardLoginBindDevice *bool `form:"card_login_bind_device" json:"card_login_bind_device"`
CardLoginAllowPassword *bool `form:"card_login_allow_password" json:"card_login_allow_password"`
AllowRegister bool `form:"allow_register" json:"allow_register"`
EnableLoginVerify bool `form:"enable_login_verify" json:"enable_login_verify"`
EnableRegisterVerify bool `form:"enable_register_verify" json:"enable_register_verify"`
VerifyMethod string `form:"verify_method" json:"verify_method"`
EmailConfigID *uint `form:"email_config_id" json:"email_config_id"`
SmsConfigID *uint `form:"sms_config_id" json:"sms_config_id"`
EncryptType string `form:"encrypt_type" json:"encrypt_type"`
EncryptKey string `form:"encrypt_key" json:"encrypt_key"`
BindType string `form:"bind_type" json:"bind_type"`
MaxDevices int `form:"max_devices" json:"max_devices"`
ChangeLimit int `form:"change_limit" json:"change_limit"`
ChangeInterval int `form:"change_interval" json:"change_interval"`
ChangeExceedAction string `form:"change_exceed_action" json:"change_exceed_action"`
ChangeDeductAmount float64 `form:"change_deduct_amount" json:"change_deduct_amount"`
MultiOpenMode string `form:"multi_open_mode" json:"multi_open_mode"`
MaxInstances int `form:"max_instances" json:"max_instances"`
EnableTrial bool `form:"enable_trial" json:"enable_trial"`
TrialBalance float64 `form:"trial_balance" json:"trial_balance"`
TrialDays int `form:"trial_days" json:"trial_days"`
EnableFreePeriod bool `form:"enable_free_period" json:"enable_free_period"`
FreePeriodType string `form:"free_period_type" json:"free_period_type"`
FreePeriodStart string `form:"free_period_start" json:"free_period_start"`
FreePeriodEnd string `form:"free_period_end" json:"free_period_end"`
FreePeriodWeekdays string `form:"free_period_weekdays" json:"free_period_weekdays"`
FreePeriodStartTime string `form:"free_period_start_time" json:"free_period_start_time"`
FreePeriodEndTime string `form:"free_period_end_time" json:"free_period_end_time"`
HeartbeatInterval int `form:"heartbeat_interval" json:"heartbeat_interval"`
HeartbeatTimeout int `form:"heartbeat_timeout" json:"heartbeat_timeout"`
MaxAttempts int `form:"max_attempts" json:"max_attempts"`
LockDuration int `form:"lock_duration" json:"lock_duration"`
Status string `form:"status" json:"status"`
DeductionMode string `form:"deduction_mode" json:"deduction_mode"`
DeductionType string `form:"deduction_type" json:"deduction_type"`
DeductionInterval int `form:"deduction_interval" json:"deduction_interval"`
DeductionUnit string `form:"deduction_unit" json:"deduction_unit"`
DeductionAmount float64 `form:"deduction_amount" json:"deduction_amount"`
EnablePasswordReset bool `form:"enable_password_reset" json:"enable_password_reset"`
PasswordResetMethod string `form:"password_reset_method" json:"password_reset_method"`
PasswordResetEmailID *uint `form:"password_reset_email_id" json:"password_reset_email_id"`
PasswordResetSmsID *uint `form:"password_reset_sms_id" json:"password_reset_sms_id"`
}
contentType := c.GetHeader("Content-Type")
@@ -375,6 +378,18 @@ func handleUpdateApplication(c *gin.Context) {
if req.BillingType != "" {
app.BillingType = req.BillingType
}
if req.LoginMode != "" {
switch req.LoginMode {
case "account", "card", "both":
app.LoginMode = req.LoginMode
}
}
if req.CardLoginBindDevice != nil {
app.CardLoginBindDevice = *req.CardLoginBindDevice
}
if req.CardLoginAllowPassword != nil {
app.CardLoginAllowPassword = *req.CardLoginAllowPassword
}
if req.LoginPolicy != "" {
app.LoginPolicy = req.LoginPolicy
}
@@ -950,7 +965,7 @@ func handleCreateVersion(c *gin.Context) {
Version: req.Version,
Description: req.Description,
FilePath: filePath,
PublishStatus: "draft",
PublishStatus: "draft",
FileSize: fileSize,
}
@@ -997,9 +1012,9 @@ func handleUpdateVersion(c *gin.Context) {
}
var req struct {
Version string `json:"version"`
Description string `json:"description"`
FilePath string `json:"file_path"`
Version string `json:"version"`
Description string `json:"description"`
FilePath string `json:"file_path"`
PublishStatus string `json:"publish_status"`
}
if err := c.ShouldBindJSON(&req); err != nil {
@@ -1045,7 +1060,6 @@ func handleDeleteVersion(c *gin.Context) {
response.Success(c, nil)
}
func handleManualDeduct(c *gin.Context) {
userID := c.GetUint("user_id")
appID := c.Param("id")
@@ -1107,12 +1121,12 @@ func handleManualDeduct(c *gin.Context) {
database.DB.Where("id = ?", user.ID).First(&user)
record := model.ConsumptionRecord{
UserID: user.ID,
ApplicationID: app.ID,
Amount: req.Amount,
Type: "manual_deduct",
Description: req.Description,
BalanceAfter: user.Balance,
UserID: user.ID,
ApplicationID: app.ID,
Amount: req.Amount,
Type: "manual_deduct",
Description: req.Description,
BalanceAfter: user.Balance,
}
if err := database.DB.Create(&record).Error; err != nil {
+230 -19
View File
@@ -3,7 +3,9 @@ package admin
import (
"fmt"
"log"
"math/rand"
"strconv"
"strings"
"time"
"verification-platform-backend/internal/database"
@@ -38,6 +40,8 @@ func SetupCardRoutes(r *gin.RouterGroup) {
cards.DELETE("/batch", handleBatchDeleteCards)
cards.POST("/use", handleUseCard)
cards.GET("/export", handleExportCards)
cards.POST("/:id/reissue", handleReissueCard)
cards.GET("/security", handleCardSecurity)
}
}
@@ -158,6 +162,7 @@ func handleGetCardTypes(c *gin.Context) {
"application_id": ct.ApplicationID,
"name": ct.Name,
"recharge_type": ct.RechargeType,
"purpose": ct.Purpose,
"value": ct.Value,
"value_unit": ct.ValueUnit,
"price": ct.Price,
@@ -212,13 +217,14 @@ func handleGetCardType(c *gin.Context) {
func handleCreateCardType(c *gin.Context) {
userID := c.GetUint("user_id")
var req struct {
Name string `json:"name"`
Description string `json:"description"`
RechargeType string `json:"recharge_type"`
Value float64 `json:"value"`
ValueUnit string `json:"value_unit"`
Price float64 `json:"price"`
ApplicationID uint `json:"application_id"`
Name string `json:"name"`
Description string `json:"description"`
RechargeType string `json:"recharge_type"`
Purpose string `json:"purpose"`
Value float64 `json:"value"`
ValueUnit string `json:"value_unit"`
Price float64 `json:"price"`
ApplicationID uint `json:"application_id"`
}
if err := c.ShouldBindJSON(&req); err != nil {
fmt.Printf("创建卡密类型参数错误: %v\n", err)
@@ -275,6 +281,7 @@ func handleCreateCardType(c *gin.Context) {
Name: req.Name,
Description: req.Description,
RechargeType: rechargeType,
Purpose: normalizeCardPurpose(req.Purpose),
Value: req.Value,
ValueUnit: valueUnit,
Price: req.Price,
@@ -294,14 +301,14 @@ func handleCreateCardType(c *gin.Context) {
func handleUpdateCardType(c *gin.Context) {
userID := c.GetUint("user_id")
var req struct {
Name string `json:"name"`
Description string `json:"description"`
RechargeType string `json:"recharge_type"`
Value float64 `json:"value"`
ValueUnit string `json:"value_unit"`
Price float64 `json:"price"`
ApplicationID uint `json:"application_id"`
Status string `json:"status"`
Name string `json:"name"`
Description string `json:"description"`
RechargeType string `json:"recharge_type"`
Value float64 `json:"value"`
ValueUnit string `json:"value_unit"`
Price float64 `json:"price"`
ApplicationID uint `json:"application_id"`
Status string `json:"status"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, 400, "参数错误")
@@ -361,20 +368,20 @@ func handleUpdateCardType(c *gin.Context) {
func handleDeleteCardType(c *gin.Context) {
userID := c.GetUint("user_id")
id := c.Param("id")
var cardType model.CardType
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&cardType).Error; err != nil {
response.Error(c, 404, "卡密类型不存在")
return
}
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).Delete(&model.CardType{}).Error; err != nil {
response.Error(c, 500, "删除卡密类型失败")
return
}
service.LogOperationWithApp(c, &cardType.ApplicationID, "delete", "card_type", &cardType.ID, fmt.Sprintf("删除卡密类型: %s", cardType.Name), nil)
response.Success(c, nil)
}
@@ -807,12 +814,17 @@ func handleBatchGenerateCards(c *gin.Context) {
cards := make([]model.Card, 0, req.Count)
for i := 0; i < req.Count; i++ {
cardKey := req.Prefix + utils.GenerateRandomString(req.Length)
purpose := cardType.Purpose
if purpose == "" {
purpose = "recharge"
}
card := model.Card{
ApplicationID: req.ApplicationID,
CardTypeID: req.CardTypeID,
CardKey: cardKey,
CreatorID: effectiveUserID,
Status: "unused",
Purpose: purpose,
}
cards = append(cards, card)
}
@@ -839,7 +851,12 @@ func handleBatchGenerateCards(c *gin.Context) {
cards := make([]model.Card, 0, req.Count)
for i := 0; i < req.Count; i++ {
cardKey := req.Prefix + utils.GenerateRandomString(req.Length)
purpose := cardType.Purpose
if purpose == "" {
purpose = "recharge"
}
card := model.Card{
Purpose: purpose,
ApplicationID: req.ApplicationID,
CardTypeID: req.CardTypeID,
CardKey: cardKey,
@@ -1085,3 +1102,197 @@ func handleBatchDeleteCards(c *gin.Context) {
response.Success(c, gin.H{"deleted_count": len(validIDs)})
}
// normalizeCardPurpose 卡型用途白名单:recharge(充值卡) / credential(登录卡)
func normalizeCardPurpose(v string) string {
switch v {
case "credential":
return "credential"
default:
return "recharge"
}
}
// handleReissueCard 作废旧卡密并补发一张新卡:主体、余额、到期、设备全部保留,
// 只是换了一把钥匙 —— 卡密泄露时用这个,不要让用户重新买/重新绑定。
func handleReissueCard(c *gin.Context) {
userID := c.GetUint("user_id")
id, err := strconv.Atoi(c.Param("id"))
if err != nil {
response.Error(c, 400, "卡密ID无效")
return
}
var card model.Card
if err := database.DB.Where("id = ? AND creator_id = ?", id, userID).First(&card).Error; err != nil {
response.Error(c, 404, "卡密不存在")
return
}
if card.Purpose != "credential" {
response.Error(c, 400, "只有登录卡需要补发,充值卡直接作废即可")
return
}
if card.SubjectID == nil {
response.Error(c, 400, "这张卡还没有被激活,直接作废就行")
return
}
var ct model.CardType
if err := database.DB.First(&ct, card.CardTypeID).Error; err != nil {
response.Error(c, 404, "卡密类型不存在")
return
}
newKey := generateCardKeyForType(&ct)
if newKey == "" {
response.Error(c, 500, "生成新卡密失败")
return
}
tx := database.DB.Begin()
if err := tx.Model(&model.Card{}).Where("id = ?", card.ID).Update("status", "void").Error; err != nil {
tx.Rollback()
response.Error(c, 500, "作废旧卡密失败")
return
}
newCard := model.Card{
ApplicationID: card.ApplicationID,
CardTypeID: card.CardTypeID,
CardKey: newKey,
Purpose: "credential",
CreatorID: card.CreatorID,
AgentID: card.AgentID,
SubjectID: card.SubjectID, // 同一个主体,换钥匙不换人
Status: "used",
}
now := time.Now()
newCard.UsedAt = &now
if err := tx.Create(&newCard).Error; err != nil {
tx.Rollback()
response.Error(c, 500, "生成新卡密失败")
return
}
tx.Commit()
// 主体的展示标识跟着换成新卡密,客服看到的还是「一个主体 + 当前有效卡密」
if err := database.DB.Model(&model.AppUser{}).Where("id = ?", *card.SubjectID).
Update("display_name", newKey).Error; err != nil {
log.Printf("[CARD] 更新主体 display_name 失败: %v", err)
}
service.LogVerification(c, &card.ApplicationID, card.SubjectID, "card_reissue",
fmt.Sprintf("作废卡密 %s 并补发 %s", card.CardKey, newKey), "", nil)
response.Success(c, gin.H{
"message": "已作废旧卡密并补发新卡密",
"old_key": card.CardKey,
"new_key": newKey,
"subject": card.SubjectID,
})
}
// handleCardSecurity 卡密安全概览:卡的状态分布 + 最近的卡密登录失败次数(爆破迹象)
func handleCardSecurity(c *gin.Context) {
userID := c.GetUint("user_id")
appID := c.Query("application_id")
q := database.DB.Model(&model.Card{}).Where("creator_id = ?", userID)
if appID != "" {
if v, err := strconv.Atoi(appID); err == nil {
q = q.Where("application_id = ?", v)
}
}
type purposeStat struct {
Purpose string `json:"purpose"`
Status string `json:"status"`
Count int64 `json:"count"`
}
var stats []purposeStat
q.Select("purpose, status, count(*) as count").Group("purpose, status").Scan(&stats)
var credentialTotal, credentialUsed, credentialVoid, rechargeTotal int64
for _, s := range stats {
if s.Purpose == "credential" {
credentialTotal += s.Count
switch s.Status {
case "used":
credentialUsed += s.Count
case "void":
credentialVoid += s.Count
}
} else {
rechargeTotal += s.Count
}
}
// 失败次数直接从验证日志数:卡密分支的失败文案固定以「登录失败: 卡密」开头
since := time.Now().Add(-24 * time.Hour)
var failCount int64
lf := database.DB.Model(&model.Log{}).
Where("log_type = ? AND action = ? AND details LIKE ? AND created_at >= ?", "verification", "login_failed", "登录失败: 卡密%", since)
if appID != "" {
if v, err := strconv.Atoi(appID); err == nil {
lf = lf.Where("application_id = ?", v)
}
}
lf.Count(&failCount)
// 按卡型看失败分布:哪个卡型被刷得最狠,一眼能看出来
type typeFail struct {
CardTypeID uint `json:"card_type_id"`
Name string `json:"name"`
Count int64 `json:"count"`
}
var byType []typeFail
tf := database.DB.Model(&model.Log{}).
Select("logs.card_type_id as card_type_id, card_types.name as name, count(*) as count").
Joins("JOIN card_types ON card_types.id = logs.card_type_id").
Where("logs.log_type = ? AND logs.action = ? AND logs.created_at >= ?", "verification", "login_failed", since).
Group("logs.card_type_id, card_types.name").
Order("count DESC").
Limit(5)
if appID != "" {
if v, err := strconv.Atoi(appID); err == nil {
tf = tf.Where("logs.application_id = ?", v)
}
}
tf.Scan(&byType)
response.Success(c, gin.H{
"failed_by_type": byType,
"credential_total": credentialTotal,
"credential_used": credentialUsed,
"credential_void": credentialVoid,
"recharge_total": rechargeTotal,
"failed_24h": failCount,
"breakdown": stats,
})
}
// generateCardKeyForType 生成一把新的登录卡密:定长、去掉易混字符(0/O/1/I/l),
// 带前缀便于人工核对,撞库重试几次。
func generateCardKeyForType(ct *model.CardType) string {
const alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
prefix := "VFY-"
for attempt := 0; attempt < 8; attempt++ {
var b strings.Builder
b.WriteString(prefix)
for i := 0; i < 4; i++ {
if i > 0 {
b.WriteString("-")
}
for j := 0; j < 4; j++ {
b.WriteByte(alphabet[rand.Intn(len(alphabet))])
}
}
key := b.String()
var exists int64
database.DB.Model(&model.Card{}).Where("card_key = ?", key).Count(&exists)
if exists == 0 {
return key
}
}
return ""
}
+197
View File
@@ -0,0 +1,197 @@
package admin
// 批量导出证书身份:把一个 pfx 里选中的每套「私钥+证书」重新打包成独立的
// pfx(用用户指定的统一口令),再打成一个 zip 下载。
//
// 为什么需要:一个驱动签名包里可能装几十套证书,用户往往要拿去 Windows 上
// 用 signtool 单独试签,一个个导太麻烦。这里按套导出,文件名带序号和 CN,
// 一眼能对上是哪张证书。
import (
"archive/zip"
"bytes"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/protect"
"verification-platform-backend/pkg/response"
)
// 文件名里不能出现的字符
var unsafeName = regexp.MustCompile(`[\\/:*?"<>|\r\n\t]+`)
// HandleExportIdentities 批量导出选中身份
//
// POST /dev/sign-profiles/:id/export
//
// { "identities": [1,2,3] 或 "all", "password": "导出用的口令",
// "skip_revoked": true, "check_revoked": true }
//
// 响应:application/zip,内含 <序号>_<CN>.pfx
func HandleExportIdentities(c *gin.Context) {
userID := c.GetUint("user_id")
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
response.ParamError(c, "证书 ID 不合法")
return
}
var req struct {
Identities []int `json:"identities"`
All bool `json:"all"`
Password string `json:"password"`
SkipRevoked bool `json:"skip_revoked"`
CheckRevoked bool `json:"check_revoked"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.ParamError(c, "参数格式不对")
return
}
if req.Password == "" {
response.ParamError(c, "请设置导出文件的密码(导出的是带私钥的 pfx,必须有口令)")
return
}
if len(req.Password) > 64 {
response.ParamError(c, "密码过长(最多 64 字符)")
return
}
var sp model.SignProfile
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&sp).Error; err != nil {
response.NotFound(c, "证书不存在")
return
}
certData, err := protect.ReadEncrypted(sp.CertPath)
if err != nil {
response.InternalError(c, "读取证书失败")
return
}
password := ""
if b, e := protect.ReadEncrypted(sp.PassPath); e == nil {
password = string(b)
}
// 用新口令重打包所有身份
all, serr := protect.SplitPFXWithPassword(certData, password, req.Password)
if serr != nil {
response.InternalError(c, "导出失败:"+serr.Error())
return
}
if len(all) == 0 {
response.ParamError(c, "这个文件里没有可导出的身份")
return
}
// 选中哪些
want := map[int]bool{}
for _, i := range req.Identities {
want[i] = true
}
// 需要先知道吊销状态(用户可要求跳过已吊销)
var details []protect.IdentityDetail
if req.CheckRevoked || req.SkipRevoked {
if d, derr := protect.ParseIdentitiesFull(certData, password); derr == nil {
details = d
}
}
revokedIdx := map[int]bool{}
ban := localBanMap()
for _, d := range details {
if protect.CheckRevocation(d.Cert, d.Issuer).Status == protect.RevokeRevoked {
revokedIdx[d.Index] = true
continue
}
if protect.BanState(d.Cert, ban).Status == protect.RevokeRevoked {
revokedIdx[d.Index] = true
}
}
buf := &bytes.Buffer{}
zw := zip.NewWriter(buf)
added := 0
skipped := 0
for _, it := range all {
if !req.All && len(want) > 0 && !want[it.Index] {
continue
}
if req.SkipRevoked && revokedIdx[it.Index] {
skipped++
continue
}
name := fmt.Sprintf("%03d_%s.pfx", it.Index, safeFileStem(cnFromSubject(it.Subject)))
w, werr := zw.Create(name)
if werr != nil {
response.InternalError(c, "打包失败:"+werr.Error())
return
}
if _, werr = w.Write(it.PFX); werr != nil {
response.InternalError(c, "写包失败:"+werr.Error())
return
}
added++
}
// 附一份清单,方便核对导出了哪些、口令是什么(口令只写在包里,不进日志)
var readme strings.Builder
readme.WriteString("证书批量导出\n")
readme.WriteString("导出时间:" + time.Now().Format("2006-01-02 15:04:05") + "\n")
readme.WriteString("来源记录:" + sp.Name + "\n")
readme.WriteString("文件口令:" + req.Password + "\n")
if skipped > 0 {
readme.WriteString(fmt.Sprintf("已跳过 %d 套(已吊销/已拉黑)\n", skipped))
}
readme.WriteString("\n用法(Windows):\n")
readme.WriteString(" signtool sign /f 001_xxx.pfx /p 口令 /fd sha256 /tr http://timestamp.digicert.com /td sha256 程序.exe\n")
readme.WriteString(" 驱动加 -ac 交叉证书:/ac MSCV-VSClass3.cer\n")
if w, werr := zw.Create("README.txt"); werr == nil {
w.Write([]byte(readme.String()))
}
if err := zw.Close(); err != nil {
response.InternalError(c, "打包失败:"+err.Error())
return
}
if added == 0 {
response.ParamError(c, "没有可导出的身份(可能都被跳过或没选中)")
return
}
fname := fmt.Sprintf("%s_身份导出_%s.zip", safeFileStem(cnFromSubject(sp.Subject)), time.Now().Format("20060102_150405"))
c.Header("Content-Type", "application/zip")
c.Header("Content-Disposition", "attachment; filename=\""+fname+"\"")
c.Header("X-Exported", strconv.Itoa(added))
c.Data(200, "application/zip", buf.Bytes())
}
// cnFromSubject 从 "C=CN, O=xx, CN=yyy" 里取 CN
func cnFromSubject(subject string) string {
for _, part := range strings.Split(subject, ",") {
part = strings.TrimSpace(part)
if strings.HasPrefix(part, "CN=") {
return strings.TrimPrefix(part, "CN=")
}
}
if subject == "" {
return "证书"
}
return subject
}
// safeFileStem 把 CN 变成安全的文件名片段
func safeFileStem(s string) string {
s = unsafeName.ReplaceAllString(s, "_")
s = strings.TrimSpace(s)
if len(s) > 60 {
s = s[:60]
}
if s == "" || s == "." || s == ".." {
s = "证书"
}
return s
}
@@ -22,6 +22,8 @@ func SetupRoutes(r *gin.RouterGroup) {
SetupUsageRoutes(r)
SetupAnnouncementRoutes(r)
SetupVersionRoutes(r)
SetupProtectRoutes(r)
SetupSignProfileRoutes(r)
SetupProfileRoutes(r)
SetupEmailRoutes(r)
SetupSystemSettingsRoutes(r)
+2 -2
View File
@@ -431,7 +431,7 @@ func HandleGetSessions(c *gin.Context) {
sessionsWithDetails := make([]SessionWithDetails, 0, len(sessions))
for _, session := range sessions {
var device model.UserDevice
if err := database.DB.First(&device, session.DeviceID).Error; err != nil {
if err := database.DB.First(&device, session.UserDeviceID).Error; err != nil {
continue
}
@@ -459,7 +459,7 @@ func HandleGetSessions(c *gin.Context) {
deviceIDMatch := strings.Contains(strings.ToLower(device.DeviceID), searchLower)
usernameMatch := strings.Contains(strings.ToLower(user.Username), searchLower)
deviceNameMatch := strings.Contains(strings.ToLower(device.DeviceName), searchLower)
if !instanceIDMatch && !deviceIDMatch && !usernameMatch && !deviceNameMatch {
continue
}
+1 -1
View File
@@ -1,4 +1,4 @@
package admin
package admin
import (
"errors"
+9 -9
View File
@@ -91,11 +91,11 @@ func handleUpdateEmailConfig(c *gin.Context) {
}
var req struct {
EnableEmailVerify bool `json:"enable_email_verify"`
RequireEmailVerify bool `json:"require_email_verify"`
EnablePasswordReset bool `json:"enable_password_reset"`
PasswordResetMethod string `json:"password_reset_method"`
SMTPConfig *struct {
EnableEmailVerify bool `json:"enable_email_verify"`
RequireEmailVerify bool `json:"require_email_verify"`
EnablePasswordReset bool `json:"enable_password_reset"`
PasswordResetMethod string `json:"password_reset_method"`
SMTPConfig *struct {
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
@@ -112,10 +112,10 @@ func handleUpdateEmailConfig(c *gin.Context) {
}
updates := map[string]interface{}{
"enable_email_verify": req.EnableEmailVerify,
"require_email_verify": req.RequireEmailVerify,
"enable_password_reset": req.EnablePasswordReset,
"password_reset_method": req.PasswordResetMethod,
"enable_email_verify": req.EnableEmailVerify,
"require_email_verify": req.RequireEmailVerify,
"enable_password_reset": req.EnablePasswordReset,
"password_reset_method": req.PasswordResetMethod,
}
if err := database.DB.Model(&app).Updates(updates).Error; err != nil {
+1 -1
View File
@@ -1,4 +1,4 @@
package admin
package admin
import (
"bytes"
@@ -0,0 +1,194 @@
package admin
// 把所有证书记录里的「每一套签名身份」拉平成一张表。
//
// 一个 pfx 里可能装几十套证书(驱动签名包常见),用户要的是「一眼看到全部证书」,
// 而不是先点某个文件再看里面。所以这里提供扁平列表:每行就是一套身份,
// 带来源文件、到期、可签类型,吊销/拉黑状态按需检测。
import (
"strconv"
"strings"
"github.com/gin-gonic/gin"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/protect"
"verification-platform-backend/pkg/response"
)
// FlatIdentity 扁平列表里的一行
type FlatIdentity struct {
Key string `json:"key"` // "profileID:index"
ProfileID uint `json:"profile_id"`
ProfileName string `json:"profile_name"`
Platform string `json:"platform"`
HasCross bool `json:"has_cross"`
Index int `json:"index"`
Subject string `json:"subject"`
CN string `json:"cn"`
NotAfter string `json:"not_after"`
Expired bool `json:"expired"`
Usage string `json:"usage_label"`
UsageApp bool `json:"usage_app"`
UsageDriver bool `json:"usage_driver"`
ParseError string `json:"parse_error,omitempty"`
}
// HandleFlatIdentities 全部证书身份(分页)
//
// GET /dev/sign-profiles/identities-flat?page=1&page_size=50
func HandleFlatIdentities(c *gin.Context) {
userID := c.GetUint("user_id")
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
size, _ := strconv.Atoi(c.DefaultQuery("page_size", "50"))
if page < 1 {
page = 1
}
if size < 1 || size > 200 {
size = 50
}
var profiles []model.SignProfile
if err := database.DB.Where("user_id = ?", userID).Order("id desc").Find(&profiles).Error; err != nil {
response.InternalError(c, "读取证书失败")
return
}
all := make([]FlatIdentity, 0, len(profiles)*4)
for _, sp := range profiles {
certData, err := protect.ReadEncrypted(sp.CertPath)
if err != nil {
all = append(all, FlatIdentity{
Key: strconv.FormatUint(uint64(sp.ID), 10) + ":0", ProfileID: sp.ID,
ProfileName: sp.Name, Platform: sp.Platform, HasCross: sp.CrossPath != "",
Subject: sp.Subject, CN: cnFromSubject(sp.Subject), ParseError: "读取证书失败",
})
continue
}
password := ""
if b, e := protect.ReadEncrypted(sp.PassPath); e == nil {
password = string(b)
}
full, perr := protect.ParseIdentitiesFull(certData, password)
if perr != nil || len(full) == 0 {
all = append(all, FlatIdentity{
Key: strconv.FormatUint(uint64(sp.ID), 10) + ":0", ProfileID: sp.ID,
ProfileName: sp.Name, Platform: sp.Platform, HasCross: sp.CrossPath != "",
Subject: sp.Subject, CN: cnFromSubject(sp.Subject), ParseError: "解析失败",
})
continue
}
for _, d := range full {
all = append(all, FlatIdentity{
Key: strconv.FormatUint(uint64(sp.ID), 10) + ":" + strconv.Itoa(d.Index),
ProfileID: sp.ID,
ProfileName: sp.Name,
Platform: sp.Platform,
HasCross: sp.CrossPath != "",
Index: d.Index,
Subject: d.Subject,
CN: cnFromSubject(d.Subject),
NotAfter: d.NotAfter.Format("2006-01-02"),
Expired: d.Expired,
Usage: d.Usage.Label,
UsageApp: d.Usage.App,
UsageDriver: d.Usage.Driver,
})
}
}
total := len(all)
from := (page - 1) * size
if from > total {
from = total
}
to := from + size
if to > total {
to = total
}
response.Success(c, gin.H{
"total": total,
"page": page,
"page_size": size,
"items": all[from:to],
})
}
// HandleCheckIdentities 批量检测指定身份的吊销 / 拉黑(单次最多 20 个)
//
// POST /dev/sign-profiles/identities-check
//
// { "keys": ["12:3", "12:7", "15:1"] }
func HandleCheckIdentities(c *gin.Context) {
userID := c.GetUint("user_id")
var req struct {
Keys []string `json:"keys"`
}
if err := c.ShouldBindJSON(&req); err != nil || len(req.Keys) == 0 {
response.ParamError(c, "请提供要检测的身份(key = profileID:index)")
return
}
if len(req.Keys) > 20 {
req.Keys = req.Keys[:20] // 一批最多 20,剩下的前端接着要
}
// 按 profile 分组,减少重复解析
byProfile := map[uint][]int{}
order := []string{}
for _, k := range req.Keys {
parts := strings.Split(k, ":")
if len(parts) != 2 {
continue
}
pid, err1 := strconv.ParseUint(parts[0], 10, 64)
idx, err2 := strconv.Atoi(parts[1])
if err1 != nil || err2 != nil {
continue
}
byProfile[uint(pid)] = append(byProfile[uint(pid)], idx)
order = append(order, k)
}
out := map[string]gin.H{}
ban := localBanMap()
for pid, idxs := range byProfile {
var sp model.SignProfile
if err := database.DB.Where("id = ? AND user_id = ?", pid, userID).First(&sp).Error; err != nil {
continue
}
certData, err := protect.ReadEncrypted(sp.CertPath)
if err != nil {
continue
}
password := ""
if b, e := protect.ReadEncrypted(sp.PassPath); e == nil {
password = string(b)
}
full, perr := protect.ParseIdentitiesFull(certData, password)
if perr != nil {
continue
}
var list []protect.IdentityDetail
for _, i := range idxs {
if i >= 1 && i <= len(full) {
list = append(list, full[i-1])
}
}
res := checkIdentities(list, 0, ban)
for _, r := range res {
key := strconv.FormatUint(uint64(pid), 10) + ":" + strconv.Itoa(r["index"].(int))
out[key] = r
}
}
items := make([]gin.H, 0, len(order))
for _, k := range order {
if r, ok := out[k]; ok {
r["key"] = k
items = append(items, r)
}
}
response.Success(c, gin.H{"items": items, "checked": len(items)})
}
+8 -8
View File
@@ -80,13 +80,13 @@ func handleGetLogs(c *gin.Context) {
}
response.Success(c, gin.H{
"logs": logs,
"total": total,
"page": page,
"page_size": pageSize,
"total_page": (total + int64(pageSize) - 1) / int64(pageSize),
"success_count": successCount,
"failed_count": failedCount,
"operation_count": operationCount,
"logs": logs,
"total": total,
"page": page,
"page_size": pageSize,
"total_page": (total + int64(pageSize) - 1) / int64(pageSize),
"success_count": successCount,
"failed_count": failedCount,
"operation_count": operationCount,
})
}
+1 -1
View File
@@ -1,4 +1,4 @@
package admin
package admin
import (
"fmt"
@@ -283,4 +283,4 @@ func createZipFromDir(srcDir, zipPath string) error {
_, err = io.Copy(writer, file)
return err
})
}
}
+8 -8
View File
@@ -1,4 +1,4 @@
package admin
package admin
import (
"crypto/rand"
@@ -71,7 +71,7 @@ func handleGetProfile(c *gin.Context) {
transactions := getRecentTransactions(userID)
response.Success(c, gin.H{
"user": profile,
"user": profile,
"subscription": subscription,
"transactions": transactions,
})
@@ -115,13 +115,13 @@ func getSubscriptionInfo(user *model.User) gin.H {
}
return gin.H{
"plan": planName,
"status": "active",
"expire_date": expireDate,
"api_quota": apiQuota,
"api_used": user.ApiCallsUsed,
"plan": planName,
"status": "active",
"expire_date": expireDate,
"api_quota": apiQuota,
"api_used": user.ApiCallsUsed,
"storage_quota": storageQuota,
"storage_used": user.StorageUsed,
"storage_used": user.StorageUsed,
}
}
+383
View File
@@ -0,0 +1,383 @@
package admin
// 加壳任务:把验证壳注入用户上传的原始程序(异步,产物可下载)
import (
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/protect"
"verification-platform-backend/pkg/response"
"github.com/gin-gonic/gin"
)
func SetupProtectRoutes(r *gin.RouterGroup) {
g := r.Group("/protect")
{
g.POST("/tasks", HandleCreateProtectTask)
g.GET("/tasks", HandleListProtectTasks)
g.GET("/tasks/:id", HandleGetProtectTask)
g.GET("/tasks/:id/download", HandleDownloadProtectTask)
g.POST("/tasks/:id/publish", HandlePublishProtectTask)
g.DELETE("/tasks/:id", HandleDeleteProtectTask)
}
}
// baseURL 从请求推断站点根地址(面板/应用共用同一域名)
func baseURL(c *gin.Context) string {
scheme := c.GetHeader("X-Forwarded-Proto")
if scheme == "" {
if c.Request.TLS != nil {
scheme = "https"
} else {
scheme = "http"
}
}
host := c.GetHeader("X-Forwarded-Host")
if host == "" {
host = c.Request.Host
}
return fmt.Sprintf("%s://%s", scheme, host)
}
// HandleCreateProtectTask 上传原始程序 → 建任务 → 异步加壳
func HandleCreateProtectTask(c *gin.Context) {
userID := c.GetUint("user_id")
appIDStr := c.PostForm("application_id")
appID, err := strconv.ParseUint(appIDStr, 10, 64)
if err != nil || appID == 0 {
response.ParamError(c, "缺少 application_id")
return
}
var app model.Application
if err := database.DB.Where("id = ? AND user_id = ?", appID, userID).First(&app).Error; err != nil {
response.NotFound(c, "应用不存在或无权操作")
return
}
fh, err := c.FormFile("file")
if err != nil {
response.ParamError(c, "请上传要加壳的程序(form 字段 file)")
return
}
name := filepath.Base(fh.Filename)
ext := strings.ToLower(filepath.Ext(name))
switch ext {
case ".exe", ".dll", ".apk", ".ipa", ".elf", ".bin", ".sys", ".efi", "":
default:
response.ParamError(c, "支持 .exe/.dll/.sys/.apk/.ipa/.elf(Linux 可执行可无扩展名);其他格式还没接入")
return
}
if fh.Size > 200*1024*1024 {
response.ParamError(c, "文件过大(上限 200MB)")
return
}
src, err := fh.Open()
if err != nil {
response.InternalError(c, "读取上传文件失败")
return
}
data, err := io.ReadAll(src)
src.Close()
if err != nil {
response.InternalError(c, "读取上传文件失败")
return
}
// 可选:指定重签证书(必须是自己的、平台与文件类型匹配的资产)。
// 校验放在建任务之前,并且把证书直接交给 CreateAndRunSigned —— 原来是
// 先 CreateAndRun(内部已 go execute)再 UPDATE,协程可能先读到 NULL,
// 证书被静默忽略:任务成功、产物却没重签。
var signProfileID *uint
certIdentity := 0
var warnings []string
if v := c.PostForm("sign_profile_id"); v != "" {
pid, _ := strconv.ParseUint(v, 10, 64)
if pid == 0 {
response.ParamError(c, "sign_profile_id 非法")
return
}
var sp model.SignProfile
if err := database.DB.Where("id = ? AND user_id = ?", pid, userID).First(&sp).Error; err != nil {
response.ParamError(c, "签名证书不存在或无权使用")
return
}
if sp.Status != "" && sp.Status != "active" {
response.ParamError(c, "该证书已停用,不能用于重签")
return
}
// 过期证书允许使用:私服/内网分发场景下「有签名」比「签名被链信任」更重要,
// 但要在响应里明确告诉调用方,别让人以为签了一张受信任的证书。
if sp.NotAfter != nil && sp.NotAfter.Before(time.Now()) {
warnings = append(warnings, "所选证书已于 "+sp.NotAfter.Format("2006-01-02")+
" 过期:仍会写入签名,但 Windows 会因证书过期判定签名不受信任")
}
// 应用证书 / 驱动证书要分清:EKU 里没有 Code Signing 的不能签 exe,
// 没有 Kernel Mode Code Signing 的不能签 .sys。选错了现场签出来是废的,
// 所以在建任务前就挡。
isDriver := protect.IsDriverPE(data, fh.Filename)
// 用途只提示、不拦:实测普通代码签名证书也能把签名写进 .sys,
// 真正决定 Windows 认不认的是「有没有交叉签名证书 + 系统版本 + 安全启动 +
// 是否微软签名门户签过」,不是 EKU 一票否决。
if usage, usubj, uerr := protect.ProfileIdentityUsage(uint(pid), certIdentity); uerr == nil {
if isDriver && !usage.Driver {
warnings = append(warnings, "所选证书没有内核驱动签名用途(EKU:"+usage.Label+
"):签名能写进去,但目标机可能不认;建议配交叉签名证书,并注意 Win10 1607+ 的内核驱动政策("+usubj+")")
}
if !isDriver && !usage.App {
warnings = append(warnings, "所选证书只有内核驱动签名用途(EKU:"+usage.Label+
"),签应用文件可能不被系统信任("+usubj+")")
}
if isDriver && sp.CrossPath == "" {
warnings = append(warnings, "这张证书没有配交叉签名证书:驱动签名建议上传对应的 *-CrossCert(.cer),否则签名链到不了微软的驱动信任根")
}
}
// 平台必须和文件类型对得上:PE 要 windows 证书,IPA 要 iOS 证书;
// APK/ELF 不吃签名证书,传了直接拒,免得以为签过了。
det := protect.DetectFile(data, fh.Filename)
want := ""
switch det.Kind {
case protect.KindPE:
want = "windows"
case protect.KindIPA:
want = "ios"
case protect.KindAPK, protect.KindELF:
response.ParamError(c, "该类型文件不支持用证书重签(APK 用服务端 keystore,ELF 无签名机制)")
return
}
if want != "" && sp.Platform != want {
response.ParamError(c, "证书平台不匹配:这个文件需要 "+want+" 证书,选中的是 "+sp.Platform)
return
}
// 一个证书文件里可能装几十套身份,用户可以用 cert_identity 指定第几套;
// 不指定就用第一套(和签名工具默认行为一致)。
if v := c.PostForm("cert_identity"); v != "" {
n, _ := strconv.Atoi(v)
if n < 0 || n > sp.KeyCount && sp.KeyCount > 0 {
response.ParamError(c, "cert_identity 超出范围:该证书文件里只有 "+
strconv.Itoa(sp.KeyCount)+" 套身份")
return
}
certIdentity = n
}
id := uint(pid)
signProfileID = &id
// 吊销 / 拉黑把关:私钥泄露被抓到会进 CA 的吊销名单,泄露后仍被信任根
// 认下的证书会进微软 Disallowed 名单。这两种签出来的产物会被 Windows
// 直接判定不可信,拦在建任务之前比事后排查省事。查不到(端点下线)
// 只提示、不拦——老证书的 OCSP 端点经常已经停服。
rev, ban, subj, gerr := protect.CheckProfileIdentity(id, certIdentity, localBanMap())
if gerr == nil {
if ban.Status == protect.RevokeRevoked {
c.JSON(400, gin.H{"code": 400,
"message": "该证书已被拉黑,不能用于签名",
"hint": ban.Detail + "(" + subj + ")"})
return
}
if rev.Status == protect.RevokeRevoked {
c.JSON(400, gin.H{"code": 400,
"message": "该证书已被 CA 吊销,不能用于签名",
"hint": rev.Detail + "(原因:" + rev.Reason + ";证书:" + subj + ")"})
return
}
if rev.Status == protect.RevokeUnknown {
warnings = append(warnings, "吊销状态查不到:"+rev.Detail)
}
if ban.Status == protect.RevokeNotChecked {
warnings = append(warnings, "微软拉黑名单未获取到,无法判断是否被官方作废")
}
}
}
// 内核驱动没有用户态壳可加,必须带证书走「仅签名」
if signProfileID == nil && protect.IsDriverPE(data, fh.Filename) {
c.JSON(400, gin.H{"code": 400,
"message": "内核驱动只能签名,不能加验证壳",
"hint": "请在「重签证书」里选一张支持驱动签名用途的证书(.sys 加壳后会加载失败)"})
return
}
// 验证界面皮肤:不填 = classic(原 Direct2D 壳)
theme := protect.NormalizeTheme(c.PostForm("shell_theme"))
if theme == "" {
response.ParamError(c, "未知的验证界面皮肤,可选:"+strings.Join(protect.ShellThemeOrder, " / "))
return
}
if theme != "classic" {
warnings = append(warnings, "验证界面使用 DuiLib 皮肤「"+protect.ShellThemes[theme]+"」")
}
programVer := strings.TrimSpace(c.PostForm("program_version"))
if len(programVer) > 32 {
response.Error(c, 400, "程序版本号过长(最多 32 个字符)")
return
}
if programVer != "" && !validVersionString(programVer) {
response.Error(c, 400, "程序版本号只能包含字母、数字、点、下划线和横线,例如 1.2.3")
return
}
task, err := protect.CreateAndRunThemedVer(&app, userID, name, data, baseURL(c), signProfileID, certIdentity, theme, programVer)
if err != nil {
response.ParamError(c, err.Error())
return
}
payload := gin.H{
"task_id": task.ID,
"arch": task.Arch,
"status": task.Status,
}
if len(warnings) > 0 {
payload["warning"] = strings.Join(warnings, ";")
}
response.SuccessWithMessage(c, "任务已创建,正在加壳", payload)
}
// HandleListProtectTasks 任务列表
func HandleListProtectTasks(c *gin.Context) {
userID := c.GetUint("user_id")
q := database.DB.Model(&model.ProtectTask{}).Where("user_id = ?", userID)
if v := c.Query("application_id"); v != "" {
q = q.Where("application_id = ?", v)
}
if v := c.Query("status"); v != "" {
q = q.Where("status = ?", v)
}
var total int64
q.Count(&total)
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
perPage, _ := strconv.Atoi(c.DefaultQuery("per_page", "20"))
if page < 1 {
page = 1
}
if perPage < 1 || perPage > 100 {
perPage = 20
}
var tasks []model.ProtectTask
q.Order("id DESC").Limit(perPage).Offset((page - 1) * perPage).Find(&tasks)
response.PageSuccess(c, tasks, total, page, perPage)
}
// HandleGetProtectTask 单任务详情
func HandleGetProtectTask(c *gin.Context) {
userID := c.GetUint("user_id")
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var task model.ProtectTask
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&task).Error; err != nil {
response.NotFound(c, "任务不存在")
return
}
response.Success(c, task)
}
// HandleDownloadProtectTask 下载加壳产物
func HandleDownloadProtectTask(c *gin.Context) {
userID := c.GetUint("user_id")
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var task model.ProtectTask
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&task).Error; err != nil {
response.NotFound(c, "任务不存在")
return
}
if task.Status != "done" || task.OutputPath == "" {
response.Error(c, 400, "任务尚未完成")
return
}
if _, err := os.Stat(task.OutputPath); err != nil {
response.NotFound(c, "产物文件已丢失")
return
}
c.FileAttachment(task.OutputPath, task.OutputName)
}
// HandlePublishProtectTask 把加壳产物落成一条新版本记录
func HandlePublishProtectTask(c *gin.Context) {
userID := c.GetUint("user_id")
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var task model.ProtectTask
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&task).Error; err != nil {
response.NotFound(c, "任务不存在")
return
}
var body struct {
Version string `json:"version"`
UpdateStrategy string `json:"update_strategy"`
UpdateType string `json:"update_type"`
UpdateMethod string `json:"update_method"`
Changelog string `json:"changelog"`
PublishNow bool `json:"publish_now"`
}
if err := c.ShouldBindJSON(&body); err != nil {
response.ParamError(c, "参数格式错误")
return
}
version, err := protect.PublishAsVersion(task.ID, protect.PublishOptions{
Version: body.Version,
UpdateStrategy: body.UpdateStrategy,
UpdateType: body.UpdateType,
UpdateMethod: body.UpdateMethod,
Changelog: body.Changelog,
PublishNow: body.PublishNow,
})
if err != nil {
response.Error(c, 400, err.Error())
return
}
response.SuccessWithMessage(c, "已生成版本", gin.H{
"version_id": version.ID,
"version": version.Version,
"publish_status": version.PublishStatus,
"entry_file": version.EntryFile,
"file_size": version.FileSize,
"file_hash": version.FileHash,
"protected": version.Protected,
})
}
// HandleDeleteProtectTask 删除任务(含源文件与产物)
func HandleDeleteProtectTask(c *gin.Context) {
userID := c.GetUint("user_id")
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var task model.ProtectTask
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&task).Error; err != nil {
response.NotFound(c, "任务不存在")
return
}
if task.Status == "running" {
response.Error(c, 400, "任务正在执行,稍后再删")
return
}
if task.OutputPath != "" {
os.Remove(task.OutputPath)
}
os.RemoveAll(filepath.Join(protect.Default().Dir, strconv.FormatUint(uint64(task.ID), 10)))
database.DB.Delete(&model.ProtectTask{}, task.ID)
response.SuccessWithMessage(c, "已删除", nil)
}
// validVersionString 版本号白名单:只允许字母、数字、点、下划线、横线
func validVersionString(v string) bool {
for _, r := range v {
switch {
case r >= '0' && r <= '9', r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r == '.', r == '_', r == '-':
default:
return false
}
}
return true
}
@@ -0,0 +1,31 @@
package admin
import (
"testing"
"github.com/gin-gonic/gin"
)
// 确认加壳任务路由已挂到 /api/v1/dev 下(防止注册漏掉)
func TestProtectRoutesRegistered(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
g := r.Group("/api/v1/dev")
SetupProtectRoutes(g)
want := map[string]bool{
"/api/v1/dev/protect/tasks": false,
"/api/v1/dev/protect/tasks/:id": false,
"/api/v1/dev/protect/tasks/:id/download": false,
}
for _, ri := range r.Routes() {
if _, ok := want[ri.Path]; ok {
want[ri.Path] = true
}
}
for p, ok := range want {
if !ok {
t.Fatalf("路由未注册: %s", p)
}
}
}
@@ -0,0 +1,471 @@
package admin
// 签名证书资产:上传 .pfx/.p12(+ iOS 的 .mobileprovision),加密入库,
// 供加壳产物重签时取用;任何响应都不回证书内容与口令。
import (
"fmt"
"io"
"mime/multipart"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/protect"
"verification-platform-backend/pkg/response"
"github.com/gin-gonic/gin"
)
func SetupSignProfileRoutes(r *gin.RouterGroup) {
g := r.Group("/sign-profiles")
{
g.POST("", HandleCreateSignProfile)
g.GET("", HandleListSignProfiles)
// 扁平列表与批量检测要放在 /:id 之前注册,否则会被 /:id 匹配走
g.GET("/identities-flat", HandleFlatIdentities)
g.POST("/identities-check", HandleCheckIdentities)
g.GET("/:id", HandleGetSignProfile)
g.GET("/:id/identities", HandleListIdentities)
g.POST("/:id/export", HandleExportIdentities)
g.GET("/blacklist", HandleListBlacklist)
g.POST("/blacklist", HandleAddBlacklist)
g.DELETE("/blacklist/:id", HandleDeleteBlacklist)
g.DELETE("/:id", HandleDeleteSignProfile)
}
}
// HandleCreateSignProfile 上传证书(multipart)
// 字段:platform(windows|ios)、name、cert(文件, .pfx/.p12)、password、profile(iOS 的 .mobileprovision)
// createProfile 建一条证书记录并把加密后的文件落盘。
// 拆包(一个 pfx 多套身份)时每套都会调一次,所以抽出来。
func createProfile(userID uint, platform, name, certFormat string, certData []byte, password string,
subject string, notAfter *time.Time, certCount, keyCount int, profileData []byte, crossData []byte) (model.SignProfile, error) {
sp := model.SignProfile{
UserID: userID,
Platform: platform,
Name: name,
CertFormat: certFormat,
Subject: subject,
NotAfter: notAfter,
CertCount: certCount,
KeyCount: keyCount,
Status: "active",
}
if err := database.DB.Create(&sp).Error; err != nil {
return sp, err
}
dir := protect.ProfileDir(sp.ID)
sp.CertPath = filepath.Join(dir, "cert.enc")
sp.PassPath = filepath.Join(dir, "pass.enc")
fail := func(err error) (model.SignProfile, error) {
os.RemoveAll(dir)
database.DB.Delete(&sp)
return sp, err
}
if err := protect.WriteEncrypted(sp.CertPath, certData); err != nil {
return fail(err)
}
if password != "" {
if err := protect.WriteEncrypted(sp.PassPath, []byte(password)); err != nil {
return fail(err)
}
}
if len(crossData) > 0 {
sp.CrossPath = filepath.Join(dir, "cross.enc")
if err := protect.WriteEncrypted(sp.CrossPath, crossData); err != nil {
return fail(err)
}
}
if len(profileData) > 0 {
sp.ProfilePath = filepath.Join(dir, "profile.enc")
if err := protect.WriteEncrypted(sp.ProfilePath, profileData); err != nil {
return fail(err)
}
}
if err := database.DB.Save(&sp).Error; err != nil {
return fail(err)
}
return sp, nil
}
func HandleCreateSignProfile(c *gin.Context) {
userID := c.GetUint("user_id")
platform, err := protect.NormalizePlatform(c.PostForm("platform"))
if err != nil {
response.ParamError(c, err.Error())
return
}
// 名称不让用户填:显示名就用证书本身的 CN,避免「自己起的标签」和
// 「实际签名者」两套名字对不上。解析完证书后再回填(见下面 cnName)。
name := strings.TrimSpace(c.PostForm("name"))
password := c.PostForm("password")
fh, err := c.FormFile("cert")
if err != nil {
response.ParamError(c, "请上传证书文件(form 字段 cert,.pfx/.p12)")
return
}
ext := strings.ToLower(filepath.Ext(fh.Filename))
if ext != ".pfx" && ext != ".p12" {
response.ParamError(c, "证书格式只支持 .pfx / .p12")
return
}
if fh.Size > 4*1024*1024 {
response.ParamError(c, "证书文件过大")
return
}
certData, err := readUploaded(fh)
if err != nil {
response.InternalError(c, "读取证书失败")
return
}
// 可选:交叉签名证书(微软发布的 *-CrossCert,如 MSCV-VSClass3.cer)。
// 内核驱动签名必须带它,签名链才能连到微软的驱动信任根。
var crossData []byte
if cfh, cerr := c.FormFile("cross"); cerr == nil && cfh.Size > 0 {
if cfh.Size > 256*1024 {
response.ParamError(c, "交叉签名证书文件过大")
return
}
crossData, err = readUploaded(cfh)
if err != nil {
response.InternalError(c, "读取交叉签名证书失败")
return
}
}
var profileData []byte
if platform == protect.PlatformIOS {
pfh, err := c.FormFile("profile")
if err != nil {
response.ParamError(c, "iOS 需要同时上传描述文件(form 字段 profile,.mobileprovision)")
return
}
profileData, err = readUploaded(pfh)
if err != nil {
response.InternalError(c, "读取描述文件失败")
return
}
}
// 解析 pfx 内容:证书数、私钥数、真正能签名的证书及到期时间。
// 生产镜像是 Alpine,没有 openssl CLI,全部纯 Go 解 PKCS#12。
pfx, perr := protect.ParsePFX(certData, password)
if perr != nil {
// PFXError 自带人话原因与下一步建议,直接展示;其它错误才兜底
if pe, ok := perr.(*protect.PFXError); ok {
body := gin.H{"code": 400, "message": pe.Reason}
if pe.Hint != "" {
body["hint"] = pe.Hint
}
c.JSON(400, body)
return
}
response.ParamError(c, "证书解析失败:"+perr.Error())
return
}
if pfx.KeyCount == 0 {
c.JSON(400, gin.H{"code": 400, "message": "这个文件里只有证书、没有私钥,签不了名",
"hint": "请导出带私钥的 .pfx/.p12"})
return
}
certFormat := strings.TrimPrefix(ext, ".")
// 显示名 = 证书 CN。用户填的名字只当备注,不用它当主显示名。
if cn := cnFromSubject(pfx.Signing.Subject); cn != "" {
name = cn
} else if name == "" {
name = "未命名证书"
}
// 一个证书文件里可能装几十套「私钥+证书」(驱动签名打包这类文件很常见)。
// 这里**不拆成多条记录**——79 套就建 79 条记录没法用;而是只建一条,
// 记下有几套身份,加壳时用 cert_identity 指定用哪一套,签名那一刻才拆。
made, cerr := createProfile(userID, platform, name, certFormat, certData, password,
pfx.Signing.Subject, &pfx.Signing.NotAfter, pfx.CertCount, pfx.KeyCount, profileData, crossData)
if cerr != nil {
response.InternalError(c, "保存证书失败:"+cerr.Error())
return
}
msg := "证书已加密保存"
if pfx.KeyCount > 1 {
msg = fmt.Sprintf("证书已保存:文件里含 %d 套可签名身份,云端加密时可任选其中一套", pfx.KeyCount)
}
response.SuccessWithMessage(c, msg, gin.H{
"id": made.ID,
"name": made.Name,
"subject": made.Subject,
"not_after": made.NotAfter,
"cert_count": pfx.CertCount,
"key_count": pfx.KeyCount,
"identities": pfx.Identities,
"note": pfx.Note,
"fingerprint": protect.Fingerprint(certData),
"has_cross": made.CrossPath != "",
})
}
// HandleListIdentities 列出一个证书文件里的所有可签名身份(一个文件可能装几十套)
func HandleListIdentities(c *gin.Context) {
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
response.ParamError(c, "证书 ID 不合法")
return
}
var sp model.SignProfile
if err := database.DB.Where("id = ? AND user_id = ?", id, c.GetUint("user_id")).First(&sp).Error; err != nil {
response.NotFound(c, "证书不存在")
return
}
certData, err := protect.ReadEncrypted(sp.CertPath)
if err != nil {
response.InternalError(c, "读取证书失败")
return
}
password := ""
if b, err := protect.ReadEncrypted(sp.PassPath); err == nil {
password = string(b)
}
// 身份列表。带 check 参数时顺带查吊销与拉黑:
// ?check=7 只查第 7 套
// ?check=range&from=1&to=20 批量查一段(前端分批调用,避免一次请求拖太久)
check := c.Query("check")
if check != "" {
full, ferr := protect.ParseIdentitiesFull(certData, password)
if ferr != nil {
response.InternalError(c, "解析证书失败:"+ferr.Error())
return
}
ban := localBanMap()
if check == "range" {
from, _ := strconv.Atoi(c.DefaultQuery("from", "1"))
to, _ := strconv.Atoi(c.DefaultQuery("to", strconv.Itoa(len(full))))
if from < 1 {
from = 1
}
if to > len(full) {
to = len(full)
}
if to-from+1 > 20 {
to = from + 19 // 单次最多 20 套,剩下的前端接着要
}
if from > to {
response.ParamError(c, "范围不合法")
return
}
items := checkIdentities(full[from-1:to], from, ban)
response.Success(c, gin.H{"total": len(full), "from": from, "to": to, "items": items,
"done": to >= len(full)})
return
}
idx, _ := strconv.Atoi(check)
if idx < 1 || idx > len(full) {
response.ParamError(c, "证书里只有 "+strconv.Itoa(len(full))+" 套身份")
return
}
items := checkIdentities(full[idx-1:idx], idx, ban)
response.Success(c, gin.H{
"total": len(full),
"index": idx,
"subject": full[idx-1].Subject,
"revoke": items[0]["revoke"],
"ban": items[0]["ban"],
"items": items,
})
return
}
info, perr := protect.ParsePFX(certData, password)
if perr != nil {
response.InternalError(c, "解析证书失败:"+perr.Error())
return
}
response.Success(c, gin.H{
"total": len(info.Identities),
"identities": info.Identities,
})
}
// shortCN 从 "CN=xxx,O=yyy" 里抽出 CN,用于给拆出来的记录起名字
func shortCN(subject string) string {
for _, part := range strings.Split(subject, ",") {
part = strings.TrimSpace(part)
if strings.HasPrefix(part, "CN=") {
return strings.TrimPrefix(part, "CN=")
}
}
if subject == "" {
return "证书"
}
return subject
}
// HandleListSignProfiles 列表(不含任何敏感字段)
func HandleListSignProfiles(c *gin.Context) {
userID := c.GetUint("user_id")
q := database.DB.Model(&model.SignProfile{}).Where("user_id = ?", userID)
if p := c.Query("platform"); p != "" {
q = q.Where("platform = ?", p)
}
var items []model.SignProfile
q.Order("id DESC").Find(&items)
out := make([]gin.H, 0, len(items))
for _, sp := range items {
out = append(out, gin.H{
"id": sp.ID, "platform": sp.Platform, "name": sp.Name,
"cert_format": sp.CertFormat, "subject": sp.Subject, "not_after": sp.NotAfter,
"cert_count": sp.CertCount, "key_count": sp.KeyCount,
"status": sp.Status, "has_profile": sp.ProfilePath != "",
"last_used_at": sp.LastUsedAt, "created_at": sp.CreatedAt,
})
}
response.Success(c, gin.H{"items": out, "total": len(out)})
}
// HandleGetSignProfile 详情(元数据)
func HandleGetSignProfile(c *gin.Context) {
userID := c.GetUint("user_id")
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var sp model.SignProfile
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&sp).Error; err != nil {
response.NotFound(c, "证书不存在")
return
}
response.Success(c, gin.H{
"cert_count": sp.CertCount,
"key_count": sp.KeyCount,
"id": sp.ID, "platform": sp.Platform, "name": sp.Name,
"cert_format": sp.CertFormat, "subject": sp.Subject, "not_after": sp.NotAfter,
"status": sp.Status, "has_profile": sp.ProfilePath != "",
"created_at": sp.CreatedAt, "updated_at": sp.UpdatedAt,
})
}
// HandleDeleteSignProfile 删除(含磁盘密文)
func HandleDeleteSignProfile(c *gin.Context) {
userID := c.GetUint("user_id")
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
var sp model.SignProfile
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&sp).Error; err != nil {
response.NotFound(c, "证书不存在")
return
}
os.RemoveAll(protect.ProfileDir(sp.ID))
database.DB.Delete(&model.SignProfile{}, sp.ID)
response.SuccessWithMessage(c, "已删除", nil)
}
func readUploaded(fh *multipart.FileHeader) ([]byte, error) {
f, err := fh.Open()
if err != nil {
return nil, err
}
defer f.Close()
return io.ReadAll(io.LimitReader(f, 16<<20))
}
// localBanMap 平台黑名单:指纹 → 拉黑原因
func localBanMap() map[string]string {
out := map[string]string{}
var rows []model.CertBlacklist
if err := database.DB.Find(&rows).Error; err != nil {
return out
}
for _, r := range rows {
key := r.Fingerprint
if r.Reason != "" {
key += "|" + r.Reason
}
out[strings.ToLower(r.Fingerprint)] = r.Reason
}
return out
}
// HandleListBlacklist 拉黑名单列表
func HandleListBlacklist(c *gin.Context) {
var rows []model.CertBlacklist
database.DB.Order("id desc").Find(&rows)
response.Success(c, gin.H{"items": rows, "total": len(rows)})
}
// HandleAddBlacklist 拉黑一张证书(按 SHA256 指纹)
func HandleAddBlacklist(c *gin.Context) {
var req struct {
Fingerprint string `json:"fingerprint" binding:"required"`
Subject string `json:"subject"`
Reason string `json:"reason"`
Note string `json:"note"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.ParamError(c, "缺少证书指纹")
return
}
fp := strings.ToLower(strings.ReplaceAll(req.Fingerprint, ":", ""))
if len(fp) < 32 {
response.ParamError(c, "证书指纹格式不对(需要 SHA256,64 位十六进制)")
return
}
row := model.CertBlacklist{
Fingerprint: fp,
Subject: req.Subject,
Reason: req.Reason,
Note: req.Note,
CreatedBy: c.GetUint("user_id"),
}
if err := database.DB.Create(&row).Error; err != nil {
response.InternalError(c, "拉黑失败(可能已在名单里)")
return
}
response.SuccessWithMessage(c, "已加入黑名单", gin.H{"id": row.ID})
}
// HandleDeleteBlacklist 解除拉黑
func HandleDeleteBlacklist(c *gin.Context) {
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
if err := database.DB.Delete(&model.CertBlacklist{}, id).Error; err != nil {
response.InternalError(c, "解除失败")
return
}
response.SuccessWithMessage(c, "已从黑名单移除", nil)
}
// checkIdentities 并发检查一批身份的吊销与拉黑状态(并发 6,避免把 CA 端点打爆)
func checkIdentities(list []protect.IdentityDetail, startIndex int, ban map[string]string) []gin.H {
out := make([]gin.H, len(list))
sem := make(chan struct{}, 6)
var wg sync.WaitGroup
for i, d := range list {
wg.Add(1)
go func(i int, d protect.IdentityDetail) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
rev := protect.CheckRevocation(d.Cert, d.Issuer)
b := protect.BanState(d.Cert, ban)
out[i] = gin.H{
"index": d.Index,
"subject": d.Subject,
"not_after": d.NotAfter,
"expired": d.Expired,
"usage": d.Usage,
"revoke": rev,
"ban": b,
}
}(i, d)
}
wg.Wait()
return out
}
@@ -64,15 +64,15 @@ type SystemSettingsResponse struct {
BackupRetention int `json:"backup_retention"`
BackupStorageType string `json:"backup_storage_type"`
EnableTicketSystem bool `json:"enable_ticket_system"`
EnableTicketSystem bool `json:"enable_ticket_system"`
DefaultTheme string `json:"default_theme"`
EnableMultiLang bool `json:"enable_multi_lang"`
EnableMultiLang bool `json:"enable_multi_lang"`
EnableNotification bool `json:"enable_notification"`
AdminNotifyEmail string `json:"admin_notify_email"`
NotifyOnLogin bool `json:"notify_on_login"`
NotifyOnRecharge bool `json:"notify_on_recharge"`
NotifyOnTicket bool `json:"notify_on_ticket"`
EnableNotification bool `json:"enable_notification"`
AdminNotifyEmail string `json:"admin_notify_email"`
NotifyOnLogin bool `json:"notify_on_login"`
NotifyOnRecharge bool `json:"notify_on_recharge"`
NotifyOnTicket bool `json:"notify_on_ticket"`
}
type PaymentSettingsResponse struct {
@@ -180,13 +180,13 @@ func handleGetSystemSettings(c *gin.Context) {
}
type CleanupSettingsResponse struct {
EnableAutoCleanup bool `json:"enable_auto_cleanup"`
CleanupIntervalHours int `json:"cleanup_interval_hours"`
CaptchaRetentionDays int `json:"captcha_retention_days"`
VerifyCodeRetentionDays int `json:"verify_code_retention_days"`
ApiUsageRetentionDays int `json:"api_usage_retention_days"`
WebhookLogRetentionDays int `json:"webhook_log_retention_days"`
DeviceSessionRetentionDays int `json:"device_session_retention_days"`
EnableAutoCleanup bool `json:"enable_auto_cleanup"`
CleanupIntervalHours int `json:"cleanup_interval_hours"`
CaptchaRetentionDays int `json:"captcha_retention_days"`
VerifyCodeRetentionDays int `json:"verify_code_retention_days"`
ApiUsageRetentionDays int `json:"api_usage_retention_days"`
WebhookLogRetentionDays int `json:"webhook_log_retention_days"`
DeviceSessionRetentionDays int `json:"device_session_retention_days"`
}
func handleGetCleanupSettings(c *gin.Context) {
@@ -195,12 +195,12 @@ func handleGetCleanupSettings(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": 200,
"data": CleanupSettingsResponse{
EnableAutoCleanup: cfg.EnableAutoCleanup,
CleanupIntervalHours: cfg.CleanupIntervalHours,
CaptchaRetentionDays: cfg.CaptchaRetentionDays,
VerifyCodeRetentionDays: cfg.VerifyCodeRetentionDays,
ApiUsageRetentionDays: cfg.ApiUsageRetentionDays,
WebhookLogRetentionDays: cfg.WebhookLogRetentionDays,
EnableAutoCleanup: cfg.EnableAutoCleanup,
CleanupIntervalHours: cfg.CleanupIntervalHours,
CaptchaRetentionDays: cfg.CaptchaRetentionDays,
VerifyCodeRetentionDays: cfg.VerifyCodeRetentionDays,
ApiUsageRetentionDays: cfg.ApiUsageRetentionDays,
WebhookLogRetentionDays: cfg.WebhookLogRetentionDays,
DeviceSessionRetentionDays: cfg.DeviceSessionRetentionDays,
},
})
+9 -9
View File
@@ -50,7 +50,7 @@ func handleGetTicketStats(c *gin.Context) {
func handleGetTickets(c *gin.Context) {
userID := c.GetUint("user_id")
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
statusFilter := c.Query("status")
@@ -133,14 +133,14 @@ func handleGetTickets(c *gin.Context) {
}
response.Success(c, gin.H{
"tickets": result,
"total": total,
"page": page,
"page_size": pageSize,
"total_page": (total + int64(pageSize) - 1) / int64(pageSize),
"open_count": openCount,
"processing_count": processingCount,
"resolved_count": resolvedCount,
"tickets": result,
"total": total,
"page": page,
"page_size": pageSize,
"total_page": (total + int64(pageSize) - 1) / int64(pageSize),
"open_count": openCount,
"processing_count": processingCount,
"resolved_count": resolvedCount,
})
}
+1 -1
View File
@@ -1,4 +1,4 @@
package admin
package admin
import (
"fmt"
+31
View File
@@ -16,6 +16,7 @@ import (
)
type UserWithStatus struct {
CardKey string `json:"card_key"` // 卡密主体才有:该主体对应的登录卡密
model.AppUser
OnlineStatus string `json:"online_status"`
DeviceCount int `json:"device_count"`
@@ -279,6 +280,36 @@ func handleGetUsers(c *gin.Context) {
}
paginatedUsers := usersWithStatus[offset:end]
// 卡密主体:把它的登录卡密一并带出去,客服才能用「用户名或卡密」区分是谁
{
ids := make([]uint, 0, len(paginatedUsers))
for _, u := range paginatedUsers {
if u.SubjectType == "card" {
ids = append(ids, u.ID)
}
}
if len(ids) > 0 {
type row struct {
SubjectID uint
CardKey string
}
var rows []row
database.DB.Model(&model.Card{}).
Select("subject_id, card_key").
Where("subject_id IN ? AND purpose = ?", ids, "credential").
Scan(&rows)
keyBySubject := make(map[uint]string, len(rows))
for _, r := range rows {
keyBySubject[r.SubjectID] = r.CardKey
}
for i := range paginatedUsers {
if k, ok := keyBySubject[paginatedUsers[i].ID]; ok {
paginatedUsers[i].CardKey = k
}
}
}
}
responseData := gin.H{
"users": paginatedUsers,
"total": totalCount,
+141 -81
View File
@@ -209,24 +209,45 @@ func handleGetAllVersions(c *gin.Context) {
type VersionWithAppName struct {
model.Version
ApplicationName string `json:"application_name"`
Status string `json:"status"`
Status string `json:"status"`
SourceVersion string `json:"source_version"` // 加壳派生来源的版本号,非加壳版本为空
}
// 一次性查出派生来源版本号(加壳生成的版本才有 source_version_id)
sourceIDs := make([]uint, 0, len(versions))
for _, v := range versions {
if v.SourceVersionID != nil && *v.SourceVersionID > 0 {
sourceIDs = append(sourceIDs, *v.SourceVersionID)
}
}
sourceVersionMap := make(map[uint]string)
if len(sourceIDs) > 0 {
var srcs []model.Version
database.DB.Select("id, version").Where("id IN ?", sourceIDs).Find(&srcs)
for _, s := range srcs {
sourceVersionMap[s.ID] = s.Version
}
}
result := make([]VersionWithAppName, len(versions))
for i, v := range versions {
appName := appNameMap[v.ApplicationID]
log.Printf("[DEBUG] Mapping version %d: ApplicationID=%d -> AppName=%s\n", i, v.ApplicationID, appName)
// 使用数据库中的 publish_status 作为状态
status := v.PublishStatus
if status == "" {
status = "draft"
}
srcVer := ""
if v.SourceVersionID != nil {
srcVer = sourceVersionMap[*v.SourceVersionID]
}
result[i] = VersionWithAppName{
Version: v,
ApplicationName: appName,
Status: status,
Status: status,
SourceVersion: srcVer,
}
}
@@ -262,54 +283,70 @@ func handleGetVersionByID(c *gin.Context) {
}
response.Success(c, gin.H{
"id": version.ID,
"application_id": version.ApplicationID,
"application_name": appNameMap[version.ApplicationID],
"version": version.Version,
"description": version.Description,
"file_path": version.FilePath,
"file_size": version.FileSize,
"file_hash": version.FileHash,
"update_strategy": version.UpdateStrategy,
"update_type": version.UpdateType,
"update_method": version.UpdateMethod,
"custom_download_url": version.CustomDownloadURL,
"changelog": version.Changelog,
"status": version.PublishStatus,
"publish_status": version.PublishStatus,
"superseded_by": version.SupersededBy,
"published_at": version.PublishedAt,
"deprecated_at": version.DeprecatedAt,
"base_version_id": version.BaseVersionID,
"entry_file": version.EntryFile,
"entry_files": version.EntryFiles,
"desktop_shortcut_files": version.DesktopShortcutFiles,
"full_package_path": version.FullPackagePath,
"full_package_size": version.FullPackageSize,
"full_package_hash": version.FullPackageHash,
"files": version.Files,
"created_at": version.CreatedAt,
"updated_at": version.UpdatedAt,
"id": version.ID,
"application_id": version.ApplicationID,
"application_name": appNameMap[version.ApplicationID],
"version": version.Version,
"description": version.Description,
"file_path": version.FilePath,
"file_size": version.FileSize,
"file_hash": version.FileHash,
"update_strategy": version.UpdateStrategy,
"update_type": version.UpdateType,
"update_method": version.UpdateMethod,
"custom_download_url": version.CustomDownloadURL,
"changelog": version.Changelog,
"status": version.PublishStatus,
"publish_status": version.PublishStatus,
"superseded_by": version.SupersededBy,
"published_at": version.PublishedAt,
"deprecated_at": version.DeprecatedAt,
"base_version_id": version.BaseVersionID,
"protected": version.Protected,
"source_version_id": version.SourceVersionID,
"protect_task_id": version.ProtectTaskID,
"source_version": sourceVersionLabel(version.SourceVersionID),
"entry_file": version.EntryFile,
"entry_files": version.EntryFiles,
"desktop_shortcut_files": version.DesktopShortcutFiles,
"full_package_path": version.FullPackagePath,
"full_package_size": version.FullPackageSize,
"full_package_hash": version.FullPackageHash,
"files": version.Files,
"created_at": version.CreatedAt,
"updated_at": version.UpdatedAt,
})
}
// sourceVersionLabel 取派生来源版本的版本号(没有则空串)
func sourceVersionLabel(id *uint) string {
if id == nil || *id == 0 {
return ""
}
var v model.Version
if err := database.DB.Select("id, version").First(&v, *id).Error; err != nil {
return ""
}
return v.Version
}
type CreateVersionRequest struct {
ApplicationID uint `json:"application_id"`
Version string `json:"version"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
EntryFile string `json:"entry_file"`
EntryFiles string `json:"entry_files"`
DesktopShortcutFiles string `json:"desktop_shortcut_files"`
UpdateStrategy string `json:"update_strategy"`
UpdateType string `json:"update_type"`
UpdateMethod string `json:"update_method"`
CustomDownloadURL string `json:"custom_download_url"`
Description string `json:"description"`
Changelog string `json:"changelog"`
BaseVersionID *uint `json:"base_version_id"`
Files []VersionFileInput `json:"files"`
ApplicationID uint `json:"application_id"`
Version string `json:"version"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
EntryFile string `json:"entry_file"`
EntryFiles string `json:"entry_files"`
DesktopShortcutFiles string `json:"desktop_shortcut_files"`
UpdateStrategy string `json:"update_strategy"`
UpdateType string `json:"update_type"`
UpdateMethod string `json:"update_method"`
CustomDownloadURL string `json:"custom_download_url"`
Description string `json:"description"`
Changelog string `json:"changelog"`
BaseVersionID *uint `json:"base_version_id"`
Files []VersionFileInput `json:"files"`
}
type VersionFileInput struct {
@@ -348,21 +385,21 @@ func handleCreateVersionGlobal(c *gin.Context) {
}
version := model.Version{
ApplicationID: req.ApplicationID,
Version: req.Version,
FilePath: req.FilePath,
FileSize: req.FileSize,
FileHash: req.FileHash,
EntryFile: req.EntryFile,
EntryFiles: req.EntryFiles,
DesktopShortcutFiles: req.DesktopShortcutFiles,
UpdateStrategy: req.UpdateStrategy,
UpdateType: req.UpdateType,
UpdateMethod: req.UpdateMethod,
CustomDownloadURL: req.CustomDownloadURL,
Description: req.Description,
Changelog: req.Changelog,
PublishStatus: "draft",
ApplicationID: req.ApplicationID,
Version: req.Version,
FilePath: req.FilePath,
FileSize: req.FileSize,
FileHash: req.FileHash,
EntryFile: req.EntryFile,
EntryFiles: req.EntryFiles,
DesktopShortcutFiles: req.DesktopShortcutFiles,
UpdateStrategy: req.UpdateStrategy,
UpdateType: req.UpdateType,
UpdateMethod: req.UpdateMethod,
CustomDownloadURL: req.CustomDownloadURL,
Description: req.Description,
Changelog: req.Changelog,
PublishStatus: "draft",
}
if version.UpdateStrategy == "" {
@@ -499,21 +536,21 @@ func handleCreateVersionGlobal(c *gin.Context) {
}
type UpdateVersionRequest struct {
Version string `json:"version"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
EntryFile string `json:"entry_file"`
EntryFiles string `json:"entry_files"`
DesktopShortcutFiles string `json:"desktop_shortcut_files"`
UpdateStrategy string `json:"update_strategy"`
UpdateType string `json:"update_type"`
UpdateMethod string `json:"update_method"`
CustomDownloadURL string `json:"custom_download_url"`
Description string `json:"description"`
Changelog string `json:"changelog"`
BaseVersionID *uint `json:"base_version_id"`
Files []VersionFileInput `json:"files"`
Version string `json:"version"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
EntryFile string `json:"entry_file"`
EntryFiles string `json:"entry_files"`
DesktopShortcutFiles string `json:"desktop_shortcut_files"`
UpdateStrategy string `json:"update_strategy"`
UpdateType string `json:"update_type"`
UpdateMethod string `json:"update_method"`
CustomDownloadURL string `json:"custom_download_url"`
Description string `json:"description"`
Changelog string `json:"changelog"`
BaseVersionID *uint `json:"base_version_id"`
Files []VersionFileInput `json:"files"`
}
func handleUpdateVersionGlobal(c *gin.Context) {
@@ -788,6 +825,21 @@ func handleUpdateVersionGlobal(c *gin.Context) {
Details: fmt.Sprintf("更新版本: %s (应用ID: %d)", version.Version, version.ApplicationID),
})
// 只换了包、版本号没动:服务端按「版本记录 ID」判定更新,客户端不会被通知
finalVersion := version.Version
if req.Version != "" {
finalVersion = req.Version
}
if req.FilePath != "" && normalizeVersionStr(finalVersion) == normalizeVersionStr(version.Version) {
log.Printf("[WARN] 版本 %s 替换了文件但版本号未变,客户端不会收到更新通知", finalVersion)
response.Success(c, gin.H{
"warning": "文件已替换,但版本号未变:客户端按版本号判定是否更新,不会收到通知。" +
"请递增版本号,或让客户端在 check-update 时带上 manifest_hash。",
"version": finalVersion,
})
return
}
response.Success(c, nil)
}
@@ -869,10 +921,10 @@ func handleBatchDeleteVersions(c *gin.Context) {
}
type UploadVersionZipResponse struct {
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
Files []VersionFileInfo `json:"files"`
FilePath string `json:"file_path"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
Files []VersionFileInfo `json:"files"`
}
type VersionFileInfo struct {
@@ -1284,3 +1336,11 @@ func handleRollbackVersion(c *gin.Context) {
"publish_status": version.PublishStatus,
})
}
// normalizeVersionStr 版本号归一:去空白、去 v/V 前缀
func normalizeVersionStr(v string) string {
v = strings.TrimSpace(v)
v = strings.TrimPrefix(v, "v")
v = strings.TrimPrefix(v, "V")
return v
}
+27 -27
View File
@@ -81,7 +81,7 @@ func handleGetStats(c *gin.Context) {
database.DB.First(&agent, userID)
response.Success(c, gin.H{
"totalApps": totalApps,
"totalApps": totalApps,
"totalCards": totalCards,
"totalUsers": totalUsers,
"totalRevenue": totalRevenue,
@@ -306,7 +306,7 @@ func handleGetCards(c *gin.Context) {
"unused_count": unusedCount,
"used_count": usedCount,
"expired_count": expiredCount,
"banned_count": bannedCount,
"banned_count": bannedCount,
})
}
@@ -499,19 +499,19 @@ func handleGetUsers(c *gin.Context) {
}
item := gin.H{
"id": u.ID,
"username": u.Username,
"email": u.Email,
"status": u.Status,
"balance": u.Balance,
"expiry_at": u.ExpiryAt,
"last_login_at": u.LastLoginAt,
"id": u.ID,
"username": u.Username,
"email": u.Email,
"status": u.Status,
"balance": u.Balance,
"expiry_at": u.ExpiryAt,
"last_login_at": u.LastLoginAt,
"last_heartbeat_at": u.LastHeartbeatAt,
"device_count": deviceCount,
"online_status": onlineStatus,
"application_id": u.ApplicationID,
"is_trial_user": u.IsTrialUser,
"created_at": u.CreatedAt,
"device_count": deviceCount,
"online_status": onlineStatus,
"application_id": u.ApplicationID,
"is_trial_user": u.IsTrialUser,
"created_at": u.CreatedAt,
}
if u.Application.ID > 0 {
item["application"] = gin.H{
@@ -868,18 +868,18 @@ func handleGetCloudVariables(c *gin.Context) {
appName = appMap[*v.AppID]
}
result = append(result, gin.H{
"id": v.ID,
"key": v.Key,
"app_id": v.AppID,
"application_name": appName,
"default_value": v.DefaultValue,
"var_type": v.VarType,
"max_records": v.MaxRecords,
"scope": v.Scope,
"write_permission": v.WritePermission,
"status": v.Status,
"description": v.Description,
"created_at": v.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
"id": v.ID,
"key": v.Key,
"app_id": v.AppID,
"application_name": appName,
"default_value": v.DefaultValue,
"var_type": v.VarType,
"max_records": v.MaxRecords,
"scope": v.Scope,
"write_permission": v.WritePermission,
"status": v.Status,
"description": v.Description,
"created_at": v.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
})
}
@@ -1581,7 +1581,7 @@ func handleGetSessions(c *gin.Context) {
result := make([]SessionWithDetails, 0, len(sessions))
for _, session := range sessions {
var device model.UserDevice
if err := database.DB.First(&device, session.DeviceID).Error; err != nil {
if err := database.DB.First(&device, session.UserDeviceID).Error; err != nil {
continue
}
+1 -1
View File
@@ -185,7 +185,7 @@ func handleAppHeartbeat(c *gin.Context) {
if sessionErr != nil {
session = model.DeviceSession{
DeviceID: device.ID,
UserDeviceID: device.ID,
UserID: user.ID,
ApplicationID: app.ID,
InstanceID: instanceID,
+362 -51
View File
@@ -12,6 +12,7 @@ import (
"verification-platform-backend/internal/service"
"verification-platform-backend/pkg/jwt"
"verification-platform-backend/pkg/response"
"gorm.io/gorm"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
@@ -65,6 +66,8 @@ func SetupAuthUserRoutes(r *gin.RouterGroup) {
r.POST("/login", handleAppLogin)
r.POST("/send-email-code", handleAppSendEmailCode)
r.POST("/reset-password", handleAppResetPassword)
r.POST("/card-bind", handleAppCardBind)
r.POST("/card-set-password", handleAppCardSetPassword)
}
func handleAppSendEmailCode(c *gin.Context) {
@@ -104,6 +107,12 @@ func handleAppSendEmailCode(c *gin.Context) {
response.Error(c, 400, "该应用未启用密码重置功能")
return
}
} else if req.Purpose == "bind_email" {
// 卡密主体给自己绑邮箱:只在这类应用开启「允许卡密用户设密码」时给发码
if !app.CardLoginAllowPassword && app.LoginMode != "card" && app.LoginMode != "both" {
response.Error(c, 400, "该应用未开启卡密绑定邮箱")
return
}
}
var smtpConfig model.AppSMTPConfig
@@ -199,16 +208,16 @@ func handleAppRegister(c *gin.Context) {
}
var req struct {
Username string `json:"username"`
Email string `json:"email"`
EmailCode string `json:"email_code"`
Phone string `json:"phone"`
SmsCode string `json:"sms_code"`
Password string `json:"password"`
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
DeviceType string `json:"device_type"`
InstanceID string `json:"instance_id"`
Username string `json:"username"`
Email string `json:"email"`
EmailCode string `json:"email_code"`
Phone string `json:"phone"`
SmsCode string `json:"sms_code"`
Password string `json:"password"`
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
DeviceType string `json:"device_type"`
InstanceID string `json:"instance_id"`
}
if err := c.ShouldBindJSON(&req); err != nil {
log.Printf("[DEBUG] Invalid request parameters: %v", err)
@@ -294,10 +303,15 @@ func handleAppRegister(c *gin.Context) {
return
}
hashedPwd, hashErr := service.HashAppUserPassword(req.Password)
if hashErr != nil {
response.Error(c, 500, "注册失败:口令处理出错")
return
}
user = model.AppUser{
Username: req.Username,
Email: req.Email,
Password: req.Password,
Password: hashedPwd,
DeviceID: req.DeviceID,
Avatar: "",
Status: "active",
@@ -365,7 +379,7 @@ func handleAppRegister(c *gin.Context) {
if sessionErr != nil {
session = model.DeviceSession{
DeviceID: device.ID,
UserDeviceID: device.ID,
UserID: user.ID,
ApplicationID: appModel.ID,
InstanceID: instanceID,
@@ -412,6 +426,8 @@ func handleAppLogin(c *gin.Context) {
var req struct {
Username string `json:"username"`
Password string `json:"password"`
CardKey string `json:"card_key"`
LoginType string `json:"login_type"` // account(默认) / card / auto
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
DeviceType string `json:"device_type"`
@@ -422,27 +438,75 @@ func handleAppLogin(c *gin.Context) {
response.Error(c, 400, "参数错误")
return
}
log.Printf("[DEBUG] Login request for username: %s", req.Username)
if req.DeviceID == "" {
response.Error(c, 400, "设备ID不能为空")
return
}
var user model.AppUser
if err := database.DB.Where("username = ? AND application_id = ?", req.Username, appModel.ID).First(&user).Error; err != nil {
log.Printf("[DEBUG] User not found: %v", err)
service.LogVerification(c, &appModel.ID, nil, "login_failed", "登录失败: 用户不存在 - "+req.Username, req.DeviceID, fmt.Errorf("用户不存在"))
response.Error(c, 404, "用户不存在")
return
// 凭证类型判定:auto = 密码留空就按卡密走(界面只有一个「账号或卡密」框时用)
if req.LoginType == "" {
req.LoginType = "account"
}
if req.LoginType == "auto" {
if req.Password == "" && req.CardKey == "" && req.Username != "" {
req.CardKey = req.Username
}
if req.CardKey != "" && req.Password == "" {
req.LoginType = "card"
} else {
req.LoginType = "account"
}
}
if user.Password != req.Password {
log.Printf("[DEBUG] Password mismatch for user: %s", req.Username)
service.LogVerification(c, &appModel.ID, &user.ID, "login_failed", "登录失败: 密码错误 - "+req.Username, req.DeviceID, fmt.Errorf("密码错误"))
response.Error(c, 400, "密码错误")
return
var user model.AppUser
cardAuth := false
if req.LoginType == "card" {
// 卡密是主体的一把钥匙:首登时把卡密激活成一个主体,之后与账号完全同一条链路
cardKey := strings.TrimSpace(req.CardKey)
subject, err := resolveCardSubject(appModel, cardKey)
if err != nil {
// 卡存在就把它属于哪个卡型一并记进日志,后台才能按卡型看谁被刷
var ctID *uint
var probe model.Card
if database.DB.Select("card_type_id").
Where("card_key = ? AND application_id = ?", cardKey, appModel.ID).
First(&probe).Error == nil {
id := probe.CardTypeID
ctID = &id
}
service.LogVerificationCard(c, &appModel.ID, nil, "login_failed",
"登录失败: 卡密"+err.Error()+" - "+cardKey, req.DeviceID, err, ctID)
response.Error(c, 401, "卡密无效或已失效")
return
}
user = *subject
cardAuth = true
req.Username = user.Username
log.Printf("[DEBUG] Card login: card=%s subject=%d", req.CardKey, user.ID)
} else {
log.Printf("[DEBUG] Login request for username: %s", req.Username)
loginQuery := database.DB.Where("application_id = ?", appModel.ID)
if strings.Contains(req.Username, "@") {
loginQuery = loginQuery.Where("email = ?", req.Username) // 绑了邮箱的主体可以用邮箱登录
} else {
loginQuery = loginQuery.Where("username = ?", req.Username)
}
if err := loginQuery.First(&user).Error; err != nil {
log.Printf("[DEBUG] User not found: %v", err)
service.LogVerification(c, &appModel.ID, nil, "login_failed", "登录失败: 用户不存在 - "+req.Username, req.DeviceID, fmt.Errorf("用户不存在"))
response.Error(c, 404, "用户不存在")
return
}
if !service.VerifyAppUserPassword(&user, req.Password) {
log.Printf("[DEBUG] Password mismatch for user: %s", req.Username)
service.LogVerification(c, &appModel.ID, &user.ID, "login_failed", "登录失败: 密码错误 - "+req.Username, req.DeviceID, fmt.Errorf("密码错误"))
response.Error(c, 400, "密码错误")
return
}
}
_ = cardAuth // 凭证类型已体现在 req.LoginType 上,后续审计日志按它区分
if blocked, reason := checkRiskControl(c, appModel.ID, req.DeviceID, req.Username); blocked {
log.Printf("[DEBUG] Login blocked by risk control: %s", reason)
@@ -500,7 +564,7 @@ func handleAppLogin(c *gin.Context) {
now := time.Now()
deviceType := getDeviceType(c, req.DeviceType)
deviceName := req.DeviceName
if deviceName == "" {
deviceName = req.DeviceID
@@ -520,10 +584,10 @@ func handleAppLogin(c *gin.Context) {
if appModel.MaxDevices > 0 && ipCount >= int64(appModel.MaxDevices) {
log.Printf("[DEBUG] IP limit exceeded for user %d: %d/%d", user.ID, ipCount, appModel.MaxDevices)
var userIPs []model.UserIP
database.DB.Where("user_id = ? AND application_id = ?", user.ID, appModel.ID).Order("created_at DESC").Find(&userIPs)
ipList := make([]gin.H, 0)
for _, ip := range userIPs {
ipList = append(ipList, gin.H{
@@ -533,12 +597,12 @@ func handleAppLogin(c *gin.Context) {
"created_at": ip.CreatedAt,
})
}
response.ErrorWithData(c, 403, "IP绑定数量已达上限,请解绑后再试", gin.H{
"error_code": "IP_LIMIT_EXCEEDED",
"max_ips": appModel.MaxDevices,
"ip_count": ipCount,
"ips": ipList,
"error_code": "IP_LIMIT_EXCEEDED",
"max_ips": appModel.MaxDevices,
"ip_count": ipCount,
"ips": ipList,
})
service.LogVerification(c, &appModel.ID, &user.ID, "login_failed", "登录失败: IP绑定数量已达上限 - "+req.Username, req.DeviceID, fmt.Errorf("IP绑定数量已达上限"))
return
@@ -557,7 +621,7 @@ func handleAppLogin(c *gin.Context) {
}
}
}
var device model.UserDevice
deviceErr := database.DB.Where("user_id = ? AND application_id = ? AND device_id = ?", user.ID, appModel.ID, req.DeviceID).First(&device).Error
@@ -570,25 +634,25 @@ func handleAppLogin(c *gin.Context) {
if deviceCount >= int64(appModel.MaxDevices) {
log.Printf("[DEBUG] Device limit exceeded for user %d: %d/%d", user.ID, deviceCount, appModel.MaxDevices)
var devices []model.UserDevice
database.DB.Where("user_id = ? AND application_id = ?", user.ID, appModel.ID).Order("created_at DESC").Find(&devices)
deviceList := make([]gin.H, 0)
for _, d := range devices {
var onlineSessions []model.DeviceSession
database.DB.Where("device_id = ? AND last_heartbeat > ?", d.ID, timeoutThreshold).Find(&onlineSessions)
deviceList = append(deviceList, gin.H{
"id": d.ID,
"device_id": d.DeviceID,
"device_name": d.DeviceName,
"device_type": d.DeviceType,
"online_count": len(onlineSessions),
"created_at": d.CreatedAt,
"id": d.ID,
"device_id": d.DeviceID,
"device_name": d.DeviceName,
"device_type": d.DeviceType,
"online_count": len(onlineSessions),
"created_at": d.CreatedAt,
})
}
response.ErrorWithData(c, 403, "设备绑定数量已达上限,请解绑后再试", gin.H{
"error_code": "DEVICE_LIMIT_EXCEEDED",
"max_devices": appModel.MaxDevices,
@@ -599,7 +663,7 @@ func handleAppLogin(c *gin.Context) {
return
}
}
device = model.UserDevice{
UserID: user.ID,
ApplicationID: appModel.ID,
@@ -629,10 +693,10 @@ func handleAppLogin(c *gin.Context) {
if sessionCount >= int64(appModel.MaxInstances) {
log.Printf("[DEBUG] Multi-instance limit exceeded for user %d device %s: %d/%d", user.ID, req.DeviceID, sessionCount, appModel.MaxInstances)
var sessions []model.DeviceSession
database.DB.Where("device_id = ? AND instance_id != ?", device.ID, instanceID).Order("last_heartbeat DESC").Find(&sessions)
sessionList := make([]gin.H, 0)
for _, s := range sessions {
isOnline := s.LastHeartbeat != nil && s.LastHeartbeat.After(timeoutThreshold)
@@ -644,7 +708,7 @@ func handleAppLogin(c *gin.Context) {
"created_at": s.CreatedAt,
})
}
response.ErrorWithData(c, 403, "多开数量已达上限", gin.H{
"error_code": "MULTI_INSTANCE_LIMIT_EXCEEDED",
"max_instances": appModel.MaxInstances,
@@ -659,7 +723,7 @@ func handleAppLogin(c *gin.Context) {
var session model.DeviceSession
if err := database.DB.Where("device_id = ? AND instance_id = ?", device.ID, instanceID).First(&session).Error; err != nil {
session = model.DeviceSession{
DeviceID: device.ID,
UserDeviceID: device.ID,
UserID: user.ID,
ApplicationID: appModel.ID,
InstanceID: instanceID,
@@ -789,6 +853,253 @@ func checkFreePeriod(app *model.Application) bool {
return false
}
// resolveCardSubject 把卡密解析成主体:首次登录当场激活(建主体 + 回填卡 + 按卡型发额度),
// 之后每次登录只是查回同一个主体。一卡一主体,卡作废不影响主体数据。
func resolveCardSubject(app *model.Application, cardKey string) (*model.AppUser, error) {
if cardKey == "" {
return nil, fmt.Errorf("卡密不能为空")
}
var card model.Card
if err := database.DB.Preload("CardType").
Where("card_key = ? AND application_id = ? AND purpose = ?", cardKey, app.ID, "credential").
First(&card).Error; err != nil {
return nil, fmt.Errorf("卡密不存在")
}
if card.Status == "void" {
return nil, fmt.Errorf("卡密已作废")
}
if card.ExpireAt != nil && card.ExpireAt.Before(time.Now()) {
return nil, fmt.Errorf("卡密已过期")
}
// 已激活过:直接回到原主体
if card.SubjectID != nil {
var subject model.AppUser
if err := database.DB.Where("id = ? AND application_id = ?", *card.SubjectID, app.ID).First(&subject).Error; err != nil {
return nil, fmt.Errorf("卡密对应的主体不存在")
}
if subject.Status != "active" {
return nil, fmt.Errorf("主体已被停用")
}
return &subject, nil
}
if card.Status != "unused" {
return nil, fmt.Errorf("卡密状态不可用")
}
// 首次激活:主体 + 额度 + 卡归属,一个事务
tx := database.DB.Begin()
if tx.Error != nil {
return nil, fmt.Errorf("系统繁忙")
}
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
now := time.Now()
subject := model.AppUser{
Username: fmt.Sprintf("card-%d", card.ID),
DisplayName: card.CardKey,
SubjectType: "card",
ApplicationID: app.ID,
Status: "active",
LastLoginAt: &now,
}
// 主体不需要可猜的口令:给一个随机解锁不了的散列(卡密就是它的钥匙)
if h, err := service.HashAppUserPassword(fmt.Sprintf("card-only-%d-%d", card.ID, now.UnixNano())); err == nil {
subject.Password = h
}
// 用户名撞车(理论上 card-ID 不会)就换个后缀,避免唯一索引炸掉整笔登录
for i := 0; i < 5; i++ {
if err := tx.Create(&subject).Error; err == nil {
break
}
subject.Username = fmt.Sprintf("card-%d-%d", card.ID, i+2)
if i == 4 {
tx.Rollback()
return nil, fmt.Errorf("激活卡密失败")
}
}
// 按卡型发额度:余额型加余额,订阅型加时长
if card.CardType.ID != 0 {
if card.CardType.RechargeType == "subscription" {
var add time.Duration
switch card.CardType.ValueUnit {
case "day":
add = time.Duration(card.CardType.Value*24) * time.Hour
case "month":
add = time.Duration(card.CardType.Value*24*30) * time.Hour
case "year":
add = time.Duration(card.CardType.Value*24*365) * time.Hour
default:
add = time.Duration(card.CardType.Value) * time.Second
}
base := now
if subject.ExpiryAt != nil && subject.ExpiryAt.After(now) {
base = *subject.ExpiryAt
}
exp := base.Add(add)
subject.ExpiryAt = &exp
tx.Model(&subject).Update("expiry_at", exp)
} else {
tx.Model(&subject).Update("balance", gorm.Expr("balance + ?", card.CardType.Value))
}
}
if err := tx.Model(&model.Card{}).Where("id = ?", card.ID).Updates(map[string]interface{}{
"subject_id": subject.ID,
"status": "used",
"used_at": &now,
}).Error; err != nil {
tx.Rollback()
return nil, fmt.Errorf("激活卡密失败")
}
if err := tx.Commit().Error; err != nil {
return nil, fmt.Errorf("激活卡密失败")
}
database.DB.First(&subject, subject.ID)
log.Printf("[CARD] 卡密首次激活: card=%s subject=%d/%s", card.CardKey, subject.ID, subject.Username)
return &subject, nil
}
// handleAppCardBind 卡密主体自助绑定邮箱并设置登录密码:
// 卡密是钥匙,邮箱+密码是备用钥匙;主体、余额、到期、设备全部不变。
func handleAppCardBind(c *gin.Context) {
appKey := c.Param("appKey")
var app model.Application
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
response.Error(c, 404, "应用不存在")
return
}
if !app.CardLoginAllowPassword && app.LoginMode != "card" && app.LoginMode != "both" {
response.Error(c, 400, "该应用未开启卡密绑定邮箱")
return
}
var req struct {
CardKey string `json:"card_key" binding:"required"`
Email string `json:"email" binding:"required,email"`
Code string `json:"code" binding:"required"`
Password string `json:"password" binding:"required,min=6"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, 400, "参数错误(密码至少 6 位)")
return
}
var code model.EmailVerifyCode
if err := database.DB.Where(
"application_id = ? AND email = ? AND code = ? AND purpose = ? AND used = ?",
app.ID, req.Email, req.Code, "bind_email", false,
).First(&code).Error; err != nil {
response.Error(c, 400, "验证码无效或已过期")
return
}
if code.ExpiresAt.Before(time.Now()) {
response.Error(c, 400, "验证码已过期")
return
}
subject, err := resolveCardSubject(&app, strings.TrimSpace(req.CardKey))
if err != nil {
response.Error(c, 401, "卡密无效或已失效")
return
}
// 邮箱已被同应用的其他主体占用时不允许(否则找回会串号)
var dup int64
database.DB.Model(&model.AppUser{}).
Where("application_id = ? AND email = ? AND id <> ?", app.ID, req.Email, subject.ID).
Count(&dup)
if dup > 0 {
response.Error(c, 400, "该邮箱已绑定其他用户")
return
}
hash, herr := service.HashAppUserPassword(req.Password)
if herr != nil {
response.Error(c, 500, "密码加密失败")
return
}
tx := database.DB.Begin()
if err := tx.Model(&model.AppUser{}).Where("id = ?", subject.ID).Updates(map[string]interface{}{
"email": req.Email,
"password": hash,
}).Error; err != nil {
tx.Rollback()
response.Error(c, 500, "绑定失败")
return
}
if err := tx.Model(&model.EmailVerifyCode{}).Where("id = ?", code.ID).Update("used", true).Error; err != nil {
tx.Rollback()
response.Error(c, 500, "绑定失败")
return
}
tx.Commit()
service.LogVerification(c, &app.ID, &subject.ID, "card_bind_email",
fmt.Sprintf("卡密主体绑定邮箱并设置密码: %s", req.Email), "", nil)
response.Success(c, gin.H{
"message": "绑定成功,以后可以用邮箱 + 密码登录,也可以继续用卡密登录",
"username": subject.Username,
})
}
// handleAppCardSetPassword 卡密主体直接用卡密改(设)登录密码,不需要旧密码也不需要验证码。
// 卡密本身就是这主体的钥匙,能出示卡密就等于证明身份。
func handleAppCardSetPassword(c *gin.Context) {
appKey := c.Param("appKey")
var app model.Application
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
response.Error(c, 404, "应用不存在")
return
}
if !app.CardLoginAllowPassword {
response.Error(c, 400, "该应用未开启卡密用户设置密码")
return
}
var req struct {
CardKey string `json:"card_key" binding:"required"`
Password string `json:"password" binding:"required,min=6"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, 400, "参数错误(密码至少 6 位)")
return
}
subject, _, err := resolveCardOwner(&app, strings.TrimSpace(req.CardKey))
if err != nil {
response.Error(c, 401, "卡密无效或已失效")
return
}
hash, herr := service.HashAppUserPassword(req.Password)
if herr != nil {
response.Error(c, 500, "密码加密失败")
return
}
if err := database.DB.Model(&model.AppUser{}).Where("id = ?", subject.ID).
Update("password", hash).Error; err != nil {
response.Error(c, 500, "设置密码失败")
return
}
service.LogVerification(c, &app.ID, &subject.ID, "card_set_password",
"卡密用户用卡密重设登录密码", "", nil)
response.Success(c, gin.H{"message": "密码已更新,可以用「邮箱/账号 + 新密码」登录"})
}
func checkRiskControl(c *gin.Context, appID uint, deviceID string, username string) (bool, string) {
clientIP := c.ClientIP()
@@ -899,9 +1210,9 @@ func handleAppResetPassword(c *gin.Context) {
}
var req struct {
Email string `json:"email" binding:"required,email"`
Code string `json:"code" binding:"required"`
Password string `json:"password" binding:"required,min=6"`
Email string `json:"email" binding:"required,email"`
Code string `json:"code" binding:"required"`
Password string `json:"password" binding:"required,min=6"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, 400, "参数错误")
+142 -11
View File
@@ -2,6 +2,7 @@ package app
import (
"fmt"
"strings"
"time"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
@@ -21,6 +22,8 @@ func SetupDeviceRoutes(r *gin.RouterGroup) {
func SetupDevicePublicRoutes(r *gin.RouterGroup) {
r.POST("/unbind-device-with-auth", handleAppUnbindDeviceWithAuth)
r.POST("/card-devices", handleAppCardDevices)
r.POST("/card-unbind", handleAppCardUnbind)
r.POST("/change-password", handleAppChangePassword)
}
@@ -58,7 +61,7 @@ func handleAppUnbindDeviceWithAuth(c *gin.Context) {
return
}
if user.Password != req.Password {
if !service.VerifyAppUserPassword(&user, req.Password) {
response.Error(c, 401, "密码错误")
return
}
@@ -125,13 +128,13 @@ func handleAppGetDevices(c *gin.Context) {
Count(&onlineSessionCount)
result = append(result, gin.H{
"id": device.ID,
"device_id": device.DeviceID,
"device_name": device.DeviceName,
"device_type": device.DeviceType,
"status": device.Status,
"online_sessions": onlineSessionCount,
"created_at": device.CreatedAt,
"id": device.ID,
"device_id": device.DeviceID,
"device_name": device.DeviceName,
"device_type": device.DeviceType,
"status": device.Status,
"online_sessions": onlineSessionCount,
"created_at": device.CreatedAt,
})
}
@@ -277,7 +280,7 @@ func handleAppGetInstances(c *gin.Context) {
var device model.UserDevice
for _, d := range devices {
if d.ID == session.DeviceID {
if d.ID == session.UserDeviceID {
device = d
break
}
@@ -373,12 +376,17 @@ func handleAppChangePassword(c *gin.Context) {
return
}
if user.Password != req.OldPassword {
if !service.VerifyAppUserPassword(&user, req.OldPassword) {
response.Error(c, 400, "原密码错误")
return
}
user.Password = req.NewPassword
newHash, hashErr := service.HashAppUserPassword(req.NewPassword)
if hashErr != nil {
response.Error(c, 500, "密码修改失败")
return
}
user.Password = newHash
if err := database.DB.Save(&user).Error; err != nil {
response.Error(c, 500, "密码修改失败")
return
@@ -388,3 +396,126 @@ func handleAppChangePassword(c *gin.Context) {
"message": "密码修改成功",
})
}
// resolveCardOwner 用卡密定位主体(卡密本身就是钥匙,能拿出来就等于持有它)
func resolveCardOwner(app *model.Application, cardKey string) (*model.AppUser, *model.Card, error) {
var card model.Card
if err := database.DB.Where("card_key = ? AND application_id = ? AND purpose = ?", cardKey, app.ID, "credential").
First(&card).Error; err != nil {
return nil, nil, fmt.Errorf("卡密不存在")
}
if card.Status == "void" {
return nil, nil, fmt.Errorf("卡密已作废")
}
if card.SubjectID == nil {
return nil, &card, fmt.Errorf("卡密尚未激活,先登录一次即可激活")
}
var subject model.AppUser
if err := database.DB.Where("id = ? AND application_id = ?", *card.SubjectID, app.ID).First(&subject).Error; err != nil {
return nil, &card, fmt.Errorf("卡密对应的主体不存在")
}
return &subject, &card, nil
}
// handleAppCardDevices 卡密用户自助查看已绑设备(不需要先登录,卡密就是身份)
func handleAppCardDevices(c *gin.Context) {
appKey := c.Param("appKey")
var app model.Application
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
response.Error(c, 404, "应用不存在")
return
}
var req struct {
CardKey string `json:"card_key" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, 400, "请提供卡密")
return
}
subject, _, err := resolveCardOwner(&app, strings.TrimSpace(req.CardKey))
if err != nil {
response.Error(c, 401, err.Error())
return
}
var devices []model.UserDevice
database.DB.Where("user_id = ? AND application_id = ?", subject.ID, app.ID).
Order("created_at DESC").Find(&devices)
timeout := app.HeartbeatTimeout
if timeout == 0 {
timeout = 300
}
threshold := time.Now().Add(-time.Duration(timeout) * time.Second)
list := make([]gin.H, 0, len(devices))
for _, d := range devices {
var online int64
database.DB.Model(&model.DeviceSession{}).
Where("device_id = ? AND last_heartbeat > ?", d.ID, threshold).Count(&online)
list = append(list, gin.H{
"device_id": d.DeviceID,
"device_name": d.DeviceName,
"device_type": d.DeviceType,
"created_at": d.CreatedAt,
"online_count": online,
})
}
response.Success(c, gin.H{
"max_devices": app.MaxDevices,
"device_count": len(list),
"devices": list,
"expiry_at": subject.ExpiryAt,
"balance": subject.Balance,
})
}
// handleAppCardUnbind 卡密用户自助解绑其中一台设备
func handleAppCardUnbind(c *gin.Context) {
appKey := c.Param("appKey")
var app model.Application
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
response.Error(c, 404, "应用不存在")
return
}
var req struct {
CardKey string `json:"card_key" binding:"required"`
DeviceID string `json:"device_id" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, 400, "请提供卡密与设备ID")
return
}
subject, _, err := resolveCardOwner(&app, strings.TrimSpace(req.CardKey))
if err != nil {
response.Error(c, 401, err.Error())
return
}
var device model.UserDevice
if err := database.DB.Where("user_id = ? AND application_id = ? AND device_id = ?",
subject.ID, app.ID, req.DeviceID).First(&device).Error; err != nil {
response.Error(c, 404, "设备不存在或已解绑")
return
}
database.DB.Where("device_id = ?", device.ID).Delete(&model.DeviceSession{})
if err := database.DB.Delete(&device).Error; err != nil {
response.Error(c, 500, "解绑失败")
return
}
if subject.DeviceID == req.DeviceID {
database.DB.Model(&model.AppUser{}).Where("id = ?", subject.ID).Update("device_id", "")
}
service.LogVerification(c, &app.ID, &subject.ID, "card_unbind_device",
fmt.Sprintf("卡密自助解绑设备: %s", req.DeviceID), req.DeviceID, nil)
response.Success(c, gin.H{"message": "解绑成功"})
}
+49 -49
View File
@@ -121,40 +121,40 @@ func handleExecuteDynamicCode(c *gin.Context) {
vm := goja.New()
appData := map[string]interface{}{
"id": app.ID,
"name": app.Name,
"description": app.Description,
"app_key": app.AppKey,
"status": app.Status,
"billing_type": app.BillingType,
"deduction_mode": app.DeductionMode,
"deduction_type": app.DeductionType,
"deduction_interval": app.DeductionInterval,
"deduction_unit": app.DeductionUnit,
"deduction_amount": app.DeductionAmount,
"enable_trial": app.EnableTrial,
"trial_balance": app.TrialBalance,
"trial_days": app.TrialDays,
"enable_free_period": app.EnableFreePeriod,
"free_period_type": app.FreePeriodType,
"free_period_start": app.FreePeriodStart,
"free_period_end": app.FreePeriodEnd,
"free_period_weekdays": app.FreePeriodWeekdays,
"id": app.ID,
"name": app.Name,
"description": app.Description,
"app_key": app.AppKey,
"status": app.Status,
"billing_type": app.BillingType,
"deduction_mode": app.DeductionMode,
"deduction_type": app.DeductionType,
"deduction_interval": app.DeductionInterval,
"deduction_unit": app.DeductionUnit,
"deduction_amount": app.DeductionAmount,
"enable_trial": app.EnableTrial,
"trial_balance": app.TrialBalance,
"trial_days": app.TrialDays,
"enable_free_period": app.EnableFreePeriod,
"free_period_type": app.FreePeriodType,
"free_period_start": app.FreePeriodStart,
"free_period_end": app.FreePeriodEnd,
"free_period_weekdays": app.FreePeriodWeekdays,
"free_period_start_time": app.FreePeriodStartTime,
"free_period_end_time": app.FreePeriodEndTime,
"max_devices": app.MaxDevices,
"bind_type": app.BindType,
"multi_open_mode": app.MultiOpenMode,
"max_instances": app.MaxInstances,
"login_policy": app.LoginPolicy,
"max_attempts": app.MaxAttempts,
"lock_duration": app.LockDuration,
"heartbeat_interval": app.HeartbeatInterval,
"heartbeat_timeout": app.HeartbeatTimeout,
"change_limit": app.ChangeLimit,
"change_interval": app.ChangeInterval,
"change_exceed_action": app.ChangeExceedAction,
"change_deduct_amount": app.ChangeDeductAmount,
"free_period_end_time": app.FreePeriodEndTime,
"max_devices": app.MaxDevices,
"bind_type": app.BindType,
"multi_open_mode": app.MultiOpenMode,
"max_instances": app.MaxInstances,
"login_policy": app.LoginPolicy,
"max_attempts": app.MaxAttempts,
"lock_duration": app.LockDuration,
"heartbeat_interval": app.HeartbeatInterval,
"heartbeat_timeout": app.HeartbeatTimeout,
"change_limit": app.ChangeLimit,
"change_interval": app.ChangeInterval,
"change_exceed_action": app.ChangeExceedAction,
"change_deduct_amount": app.ChangeDeductAmount,
}
if err := vm.Set("app", appData); err != nil {
response.Error(c, 500, "应用数据设置失败")
@@ -216,12 +216,12 @@ func handleExecuteDynamicCode(c *gin.Context) {
database.DB.Where("user_id = ? AND application_id = ?", user.ID, app.ID).Find(&userDevices)
for _, d := range userDevices {
devices = append(devices, map[string]interface{}{
"id": d.ID,
"device_id": d.DeviceID,
"device_name": d.DeviceName,
"device_type": d.DeviceType,
"status": d.Status,
"created_at": d.CreatedAt,
"id": d.ID,
"device_id": d.DeviceID,
"device_name": d.DeviceName,
"device_type": d.DeviceType,
"status": d.Status,
"created_at": d.CreatedAt,
})
}
@@ -266,12 +266,12 @@ func handleExecuteDynamicCode(c *gin.Context) {
database.DB.Where("user_id = ? AND application_id = ?", targetUser.ID, app.ID).Find(&targetUserDevices)
for _, d := range targetUserDevices {
targetDevices = append(targetDevices, map[string]interface{}{
"id": d.ID,
"device_id": d.DeviceID,
"device_name": d.DeviceName,
"device_type": d.DeviceType,
"status": d.Status,
"created_at": d.CreatedAt,
"id": d.ID,
"device_id": d.DeviceID,
"device_name": d.DeviceName,
"device_type": d.DeviceType,
"status": d.Status,
"created_at": d.CreatedAt,
})
}
@@ -669,10 +669,10 @@ func handleAddRecord(appID uint, userID *uint, actionMap map[string]interface{})
func getRecords(appID uint, userID *uint, variableKey string, page, pageSize int) map[string]interface{} {
result := map[string]interface{}{
"success": false,
"records": []interface{}{},
"total": 0,
"page": page,
"success": false,
"records": []interface{}{},
"total": 0,
"page": page,
"pageSize": pageSize,
}
+40 -12
View File
@@ -242,12 +242,28 @@ func handleAppGetInfo(c *gin.Context) {
"trial_balance": app.TrialBalance,
"heartbeat_interval": app.HeartbeatInterval,
"heartbeat_timeout": app.HeartbeatTimeout,
// —— 客户端界面开关:壳按这些字段决定显示哪些 tab / 哪些步骤 ——
"allow_register": app.AllowRegister,
"enable_login_verify": app.EnableLoginVerify,
"enable_register_verify": app.EnableRegisterVerify,
"verify_method": app.VerifyMethod,
"enable_password_reset": app.EnablePasswordReset,
"password_reset_method": app.PasswordResetMethod,
"enable_free_period": app.EnableFreePeriod,
"trial_days": app.TrialDays,
"bind_type": app.BindType,
"login_mode": app.LoginMode,
"card_login_bind_device": app.CardLoginBindDevice,
"card_login_allow_password": app.CardLoginAllowPassword,
})
}
func handleAppCheckUpdate(c *gin.Context) {
appKey := c.Param("appKey")
clientVersion := c.Query("version")
// 可选:客户端把自己本地的清单指纹报上来。
// 报了就能发现"版本号没变但文件被重新上传过"的情况;不报则退回按版本记录 ID 判定。
clientManifestHash := strings.TrimSpace(c.Query("manifest_hash"))
var app model.Application
if err := database.DB.Where("app_key = ?", appKey).First(&app).Error; err != nil {
@@ -364,18 +380,30 @@ func handleAppCheckUpdate(c *gin.Context) {
if latestVersion.ID > clientVersionRecord.ID {
updateStrategy = latestVersion.UpdateStrategy // optional 或 forced
} else {
// 已经是最新版本
response.Success(c, gin.H{
"has_update": false,
"current_version": clientVersion,
"latest_version": clientVersionRecord.Version,
"download_url": "",
"update_notes": "",
"update_strategy": "",
"update_method": "",
"files": []interface{}{},
})
return
// 版本记录 ID 相同,但客户端报了清单指纹且与服务器不一致
// → 说明该版本号下的文件被重新上传过,仍然下发更新
_, latestManifestHash, _, _ := buildVersionManifest(latestVersion)
contentChanged := clientManifestHash != "" && latestManifestHash != "" &&
clientManifestHash != latestManifestHash
if !contentChanged {
// 已经是最新版本
response.Success(c, gin.H{
"has_update": false,
"current_version": clientVersion,
"latest_version": clientVersionRecord.Version,
"latest_version_id": latestVersion.ID,
"manifest_hash": latestManifestHash,
"reason": "version_record_id_unchanged",
"download_url": "",
"update_notes": "",
"update_strategy": "",
"update_method": "",
"files": []interface{}{},
})
return
}
// 文件内容变了:按最新版本下发
updateStrategy = latestVersion.UpdateStrategy
}
}
+18 -4
View File
@@ -54,17 +54,30 @@ func handleAppRecharge(c *gin.Context) {
fmt.Printf("[DEBUG] 卡密信息: ID=%d, CardKey=%s, Status=%s, CardTypeID=%d\n", card.ID, card.CardKey, card.Status, card.CardTypeID)
fmt.Printf("[DEBUG] 卡类信息: ID=%d, Name=%s, Value=%f, Price=%f\n", card.CardType.ID, card.CardType.Name, card.CardType.Value, card.CardType.Price)
// 登录卡是钥匙不是额度:拿它来充值直接拒绝,避免用途混淆
if card.Purpose == "credential" {
service.LogVerification(c, &app.ID, nil, "recharge_failed", fmt.Sprintf("充值失败: 这是登录卡密 - %s", req.CardKey), "", fmt.Errorf("登录卡密不能用于充值"))
response.Error(c, 400, "这是登录卡密,只能用于登录,不能充值")
return
}
if card.Status != "unused" {
service.LogVerification(c, &app.ID, nil, "recharge_failed", fmt.Sprintf("充值失败: 卡密已使用 - %s", req.CardKey), "", fmt.Errorf("卡密已使用"))
response.Error(c, 400, "卡密已使用")
return
}
// 目标是主体:可以填用户名,也可以直接填卡密(卡给卡充值就走这条)
var user model.AppUser
if err := database.DB.Where("username = ? AND application_id = ?", req.Username, app.ID).First(&user).Error; err != nil {
service.LogVerification(c, &app.ID, nil, "recharge_failed", fmt.Sprintf("充值失败: 用户不存在 - %s", req.Username), "", fmt.Errorf("用户不存在"))
response.Error(c, 404, "用户不存在")
return
var targetCard model.Card
hit := database.DB.Where("card_key = ? AND application_id = ? AND subject_id IS NOT NULL", req.Username, app.ID).
First(&targetCard).Error == nil
if !hit || database.DB.First(&user, *targetCard.SubjectID).Error != nil {
service.LogVerification(c, &app.ID, nil, "recharge_failed", fmt.Sprintf("充值失败: 用户不存在 - %s", req.Username), "", fmt.Errorf("用户不存在"))
response.Error(c, 404, "用户不存在(可以直接填用户名或卡密)")
return
}
}
if user.Balance == -1 {
@@ -79,6 +92,7 @@ func handleAppRecharge(c *gin.Context) {
card.Status = "used"
card.AppUserID = &user.ID
card.AppliedToSubjectID = &user.ID
now := time.Now()
card.UsedAt = &now
@@ -203,7 +217,7 @@ func handleAppTrial(c *gin.Context) {
}
response.SuccessWithMessage(c, "试用成功", gin.H{
"message": "试用成功",
"message": "试用成功",
"trial_balance": app.TrialBalance,
})
}
+5 -5
View File
@@ -116,11 +116,11 @@ func handleAppGetUserInfo(c *gin.Context) {
}
result := gin.H{
"user_id": user.ID,
"username": user.Username,
"email": user.Email,
"avatar": user.Avatar,
"status": user.Status,
"user_id": user.ID,
"username": user.Username,
"email": user.Email,
"avatar": user.Avatar,
"status": user.Status,
}
if user.Balance == -1 {
+11 -11
View File
@@ -819,18 +819,18 @@ func handleGetAppInfo(c *gin.Context) {
}
response.Success(c, gin.H{
"id": app.ID,
"name": app.Name,
"description": app.Description,
"billing_type": app.BillingType,
"encrypt_type": app.EncryptType,
"bind_type": app.BindType,
"max_devices": app.MaxDevices,
"id": app.ID,
"name": app.Name,
"description": app.Description,
"billing_type": app.BillingType,
"encrypt_type": app.EncryptType,
"bind_type": app.BindType,
"max_devices": app.MaxDevices,
"multi_open_mode": app.MultiOpenMode,
"enable_trial": app.EnableTrial,
"trial_balance": app.TrialBalance,
"status": app.Status,
"created_at": app.CreatedAt,
"enable_trial": app.EnableTrial,
"trial_balance": app.TrialBalance,
"status": app.Status,
"created_at": app.CreatedAt,
})
}
+2 -2
View File
@@ -798,8 +798,8 @@ func handleGetPublicStats(c *gin.Context) {
database.DB.Model(&model.Card{}).Where("status = ?", "used").Count(&totalVerifications)
response.Success(c, gin.H{
"totalApps": totalApps,
"totalUsers": totalUsers,
"totalApps": totalApps,
"totalUsers": totalUsers,
"totalVerifications": totalVerifications,
})
}
+15 -15
View File
@@ -120,21 +120,21 @@ func handleTestDatabase(c *gin.Context) {
}
type SetupRequest struct {
DbType string `json:"db_type"`
DbHost string `json:"db_host"`
DbPort string `json:"db_port"`
DbName string `json:"db_name"`
DbUsername string `json:"db_username"`
DbPassword string `json:"db_password"`
JwtSecret string `json:"jwt_secret"`
AdminUser string `json:"admin_user"`
AdminPass string `json:"admin_pass"`
AdminEmail string `json:"admin_email"`
UseRedis bool `json:"use_redis"`
RedisHost string `json:"redis_host"`
RedisPort string `json:"redis_port"`
RedisPass string `json:"redis_password"`
RedisDb int `json:"redis_db"`
DbType string `json:"db_type"`
DbHost string `json:"db_host"`
DbPort string `json:"db_port"`
DbName string `json:"db_name"`
DbUsername string `json:"db_username"`
DbPassword string `json:"db_password"`
JwtSecret string `json:"jwt_secret"`
AdminUser string `json:"admin_user"`
AdminPass string `json:"admin_pass"`
AdminEmail string `json:"admin_email"`
UseRedis bool `json:"use_redis"`
RedisHost string `json:"redis_host"`
RedisPort string `json:"redis_port"`
RedisPass string `json:"redis_password"`
RedisDb int `json:"redis_db"`
}
func handleSetup(c *gin.Context) {
+5 -5
View File
@@ -70,7 +70,7 @@ func simulateCheckUpdate(appKey, clientVersion string) (gin.H, error) {
// 安装器模式:客户端没报版本号,直接给最新全量包
if strings.TrimSpace(clientVersion) == "" {
lv := &published[0]
res := packageResult(lv, clientVersion)
res := packageResult(lv, a.AppKey, clientVersion)
res["mode"] = "installer_mode(未上报版本号 → 直接下发最新包)"
res["has_update"] = true
mergeH(base, res)
@@ -95,7 +95,7 @@ func simulateCheckUpdate(appKey, clientVersion string) (gin.H, error) {
// 客户端版本号在服务器里匹配不到 → 整包兜底(新代码行为)
if cur == nil {
lv := &published[0]
res := packageResult(lv, clientVersion)
res := packageResult(lv, a.AppKey, clientVersion)
res["mode"] = "unknown_client_version(客户端版本号在服务器不存在 → 下发最新整包)"
res["has_update"] = true
mergeH(base, res)
@@ -141,7 +141,7 @@ func simulateCheckUpdate(appKey, clientVersion string) (gin.H, error) {
return nil, fmt.Errorf("读取最新版本失败: %w", err)
}
res := packageResult(&lvFull, clientVersion)
res := packageResult(&lvFull, a.AppKey, clientVersion)
res["has_update"] = true
res["update_strategy"] = strategy
res["mode"] = "update"
@@ -154,7 +154,7 @@ func simulateCheckUpdate(appKey, clientVersion string) (gin.H, error) {
}
// packageResult 按 handler 的优先级给出下载地址、hash、清单信息
func packageResult(v *model.Version, clientVersion string) gin.H {
func packageResult(v *model.Version, appKey, clientVersion string) gin.H {
downloadURL := v.FullPackagePath
downloadSize := v.FullPackageSize
downloadHash := v.FullPackageHash
@@ -194,7 +194,7 @@ func packageResult(v *model.Version, clientVersion string) gin.H {
"patch_size": v.FileSize,
"patch_hash": v.FileHash,
"is_patch_delivery": isPatch,
"manifest_url": fmt.Sprintf("/api/v1/app/%s/versions/manifest?version_id=%d", v.Application.AppKey, v.ID),
"manifest_url": fmt.Sprintf("/api/v1/app/%s/versions/manifest?version_id=%d", appKey, v.ID),
"manifest_hash": manifestHash,
"manifest_complete": complete,
"manifest_content_read": stored,
+230 -3
View File
@@ -3,16 +3,21 @@ package mcp
import (
"context"
"crypto/subtle"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"verification-platform-backend/internal/config"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"verification-platform-backend/internal/protect"
"verification-platform-backend/internal/router/app"
"verification-platform-backend/internal/service"
"verification-platform-backend/internal/utils/contentstore"
"github.com/gin-gonic/gin"
sdk "github.com/mark3labs/mcp-go/mcp"
@@ -187,8 +192,8 @@ func registerReadTools(s *mcpserver.MCPServer) {
"desktop_shortcut_files": v.DesktopShortcutFiles,
"description": v.Description, "changelog": v.Changelog,
"manifest_hash": manifestHash, "manifest_complete": complete, "content_stored": stored,
"files": files,
"created_at": v.CreatedAt, "updated_at": v.UpdatedAt,
"files": files,
"created_at": v.CreatedAt, "updated_at": v.UpdatedAt,
})
})
@@ -374,10 +379,65 @@ func registerReadTools(s *mcpserver.MCPServer) {
}
return sdk.NewToolResultJSON(gin.H{"total": len(items), "logs": items})
})
// ---------- 加壳任务(只读) ----------
s.AddTool(sdk.NewTool("verify_list_protect_tasks",
sdk.WithDescription("列出加壳任务(给程序注入验证壳的任务)。可按应用与状态过滤,按 id 倒序。"),
sdk.WithNumber("app_id", sdk.Description("应用 ID,省略则全部")),
sdk.WithString("status", sdk.Description("pending/running/done/failed")),
sdk.WithNumber("limit", sdk.Description("返回条数,默认 20,最大 100")),
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
limit := int(req.GetFloat("limit", 20))
if limit < 1 || limit > 100 {
limit = 20
}
q := database.DB.Model(&model.ProtectTask{})
if appID := req.GetInt("app_id", 0); appID > 0 {
q = q.Where("application_id = ?", appID)
}
if st := req.GetString("status", ""); st != "" {
q = q.Where("status = ?", st)
}
var tasks []model.ProtectTask
if err := q.Order("id DESC").Limit(limit).Find(&tasks).Error; err != nil {
return sdk.NewToolResultErrorFromErr("查询加壳任务失败", err), nil
}
items := make([]gin.H, 0, len(tasks))
for _, t := range tasks {
items = append(items, gin.H{
"id": t.ID, "application_id": t.ApplicationID, "source_name": t.SourceName,
"source_size": t.SourceSize, "arch": t.Arch, "status": t.Status,
"message": t.Message, "output_name": t.OutputName, "output_size": t.OutputSize,
"crc_vfy": t.CrcVfy, "crc_file": t.CrcFile,
"created_at": t.CreatedAt, "finished_at": t.FinishedAt,
})
}
return sdk.NewToolResultJSON(gin.H{"total": len(items), "tasks": items})
})
s.AddTool(sdk.NewTool("verify_get_protect_task",
sdk.WithDescription("查看单个加壳任务详情:状态、错误信息、产物文件名/大小、双层 CRC。"),
sdk.WithNumber("task_id", sdk.Required(), sdk.Description("任务 ID")),
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
id := req.GetInt("task_id", 0)
if id <= 0 {
return sdk.NewToolResultError("task_id 必须为正整数"), nil
}
var t model.ProtectTask
if err := database.DB.First(&t, id).Error; err != nil {
return sdk.NewToolResultError("任务不存在"), nil
}
return sdk.NewToolResultJSON(gin.H{
"id": t.ID, "application_id": t.ApplicationID, "source_name": t.SourceName,
"source_size": t.SourceSize, "arch": t.Arch, "status": t.Status,
"message": t.Message, "output_name": t.OutputName, "output_size": t.OutputSize,
"output_path": t.OutputPath, "crc_vfy": t.CrcVfy, "crc_file": t.CrcFile,
"created_at": t.CreatedAt, "started_at": t.StartedAt, "finished_at": t.FinishedAt,
})
})
}
func registerWriteTools(s *mcpserver.MCPServer) {
// ---------- 发布版本 ----------
s.AddTool(sdk.NewTool("verify_publish_version",
sdk.WithDescription("发布版本。规则与面板一致:仅 draft/deprecated 可发布;forced 策略会把更早的 published 版本置为 superseded。dry_run=true 只返回将要发生的变化。"),
sdk.WithDestructiveHintAnnotation(true),
@@ -486,6 +546,173 @@ func registerWriteTools(s *mcpserver.MCPServer) {
"publish_status": v.PublishStatus, "restored_version_ids": restored,
})
})
// ---------- 给版本加壳 ----------
s.AddTool(sdk.NewTool("verify_protect_version",
sdk.WithDescription("给版本的入口程序注入验证壳:Windows PE 改入口+内存加载壳 DLL+双层 CRC32;Android APK 改 AndroidManifest 的 application 并注入壳类后重签。同步执行,返回产物大小/说明。dry_run=true 只报告将用哪个文件。"),
sdk.WithDestructiveHintAnnotation(true),
sdk.WithNumber("version_id", sdk.Required(), sdk.Description("版本记录 ID")),
sdk.WithBoolean("dry_run", sdk.Description("只报告不改动,默认 true")),
sdk.WithString("base_url", sdk.Description("产物验证接口的站点根地址,如 https://v.viaeon.com;省略则读配置 protect.base_url")),
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
vid := req.GetInt("version_id", 0)
if vid <= 0 {
return sdk.NewToolResultError("version_id 必须为正整数"), nil
}
var v model.Version
if err := database.DB.First(&v, vid).Error; err != nil {
return sdk.NewToolResultError("版本不存在"), nil
}
var app model.Application
if err := database.DB.First(&app, v.ApplicationID).Error; err != nil {
return sdk.NewToolResultError("应用不存在"), nil
}
var files []model.VersionFile
database.DB.Where("version_id = ?", v.ID).Find(&files)
chosen, err := pickEntryExe(&v, files)
if err != nil {
return sdk.NewToolResultErrorFromErr("找不到可加壳的入口 exe", err), nil
}
srcPath := contentstore.ContentFilePath(chosen.FileHash)
if err := protect.WaitSource(srcPath); err != nil {
contentstore.ExtractOnDemand(v.FilePath)
if err := protect.WaitSource(srcPath); err != nil {
return sdk.NewToolResultError("入口文件还没解包到服务器本地,请稍后重试: " + err.Error()), nil
}
}
data, err := os.ReadFile(srcPath)
if err != nil {
return sdk.NewToolResultErrorFromErr("读取入口文件失败", err), nil
}
det := protect.DetectFile(data, chosen.FileName)
if det.Kind == protect.KindUnknown {
return sdk.NewToolResultError("入口文件格式无法识别"), nil
}
if err := protect.Injectable(det.Kind); err != nil {
return sdk.NewToolResultError(err.Error()), nil
}
arch := det.Arch
if req.GetBool("dry_run", true) {
return sdk.NewToolResultJSON(gin.H{
"dry_run": true, "version_id": v.ID, "version": v.Version,
"app_key": app.AppKey, "app_name": app.Name,
"entry_file": chosen.FileName, "source_size": len(data), "arch": arch,
})
}
base := req.GetString("base_url", "")
if base == "" {
base = config.GetString("protect.base_url")
}
if base == "" {
return sdk.NewToolResultError("缺少 base_url:请传参或配置 protect.base_url(产物靠它找到验证接口)"), nil
}
task, info, err := protect.CreateAndRunSyncWithVersion(&app, app.UserID, chosen.FileName, data, base, v.ID)
if err != nil {
return sdk.NewToolResultErrorFromErr("加壳失败", err), nil
}
return sdk.NewToolResultJSON(gin.H{
"dry_run": false, "task_id": task.ID, "version_id": v.ID, "version": v.Version,
"entry_file": chosen.FileName, "arch": info.Arch,
"source_size": info.OriginalSource, "output_size": info.OutSize,
"entry_old": fmt.Sprintf("0x%x", info.EntryOld), "entry_new": fmt.Sprintf("0x%x", info.EntryNew),
"crc_vfy": fmt.Sprintf("%08x", info.CrcVfy), "crc_file": fmt.Sprintf("%08x", info.CrcFile),
"note": info.Note,
"download": fmt.Sprintf("/api/v1/dev/protect/tasks/%d/download", task.ID),
"next": "调 verify_publish_protected_version 把产物落成新版本",
})
})
// ---------- 把加壳产物落成版本 ----------
s.AddTool(sdk.NewTool("verify_publish_protected_version",
sdk.WithDescription("把已完成的加壳任务产物写成一条新的版本记录(客户端按版本记录 ID 递增判定更新,原地改已发布版本的入口文件推不下去)。其余资源文件沿用来源版本;版本号留空则末段自动 +1。dry_run=true 只报告将创建的版本。"),
sdk.WithDestructiveHintAnnotation(true),
sdk.WithNumber("task_id", sdk.Required(), sdk.Description("加壳任务 ID")),
sdk.WithString("version", sdk.Description("新版本号,留空自动进位")),
sdk.WithString("update_strategy", sdk.Description("optional / forced,默认 optional")),
sdk.WithString("update_type", sdk.Description("full / delta,默认 full")),
sdk.WithString("changelog", sdk.Description("更新说明")),
sdk.WithBoolean("publish_now", sdk.Description("创建后立即发布,默认 false(存为草稿)")),
sdk.WithBoolean("dry_run", sdk.Description("只报告不改动,默认 true")),
), func(ctx context.Context, req sdk.CallToolRequest) (*sdk.CallToolResult, error) {
tid := req.GetInt("task_id", 0)
if tid <= 0 {
return sdk.NewToolResultError("task_id 必须为正整数"), nil
}
var task model.ProtectTask
if err := database.DB.First(&task, tid).Error; err != nil {
return sdk.NewToolResultError("加壳任务不存在"), nil
}
if task.Status != "done" {
return sdk.NewToolResultError("任务未完成,当前状态: " + task.Status), nil
}
opts := protect.PublishOptions{
Version: req.GetString("version", ""),
UpdateStrategy: req.GetString("update_strategy", "optional"),
UpdateType: req.GetString("update_type", "full"),
Changelog: req.GetString("changelog", ""),
PublishNow: req.GetBool("publish_now", false),
}
if req.GetBool("dry_run", true) {
var srcInfo gin.H
if task.VersionID > 0 {
var src model.Version
if database.DB.First(&src, task.VersionID).Error == nil {
srcInfo = gin.H{"source_version_id": src.ID, "source_version": src.Version, "source_publish_status": src.PublishStatus}
}
}
planned := opts.Version
if planned == "" && task.VersionID > 0 {
var src model.Version
if database.DB.First(&src, task.VersionID).Error == nil {
planned = protect.BumpVersion(src.Version) + "(自动进位,若已占用会继续往上找)"
}
}
return sdk.NewToolResultJSON(gin.H{
"dry_run": true, "task_id": task.ID, "application_id": task.ApplicationID,
"source_name": task.SourceName, "output_name": task.OutputName,
"output_size": task.OutputSize, "arch": task.Arch,
"planned_version": planned, "update_strategy": opts.UpdateStrategy,
"publish_now": opts.PublishNow, "source": srcInfo,
})
}
v, err := protect.PublishAsVersion(task.ID, opts)
if err != nil {
return sdk.NewToolResultErrorFromErr("生成版本失败", err), nil
}
return sdk.NewToolResultJSON(gin.H{
"dry_run": false, "version_id": v.ID, "version": v.Version,
"publish_status": v.PublishStatus, "entry_file": v.EntryFile,
"file_size": v.FileSize, "file_hash": v.FileHash,
"protected": v.Protected, "source_version_id": v.SourceVersionID,
"update_strategy": v.UpdateStrategy,
})
})
}
// pickEntryExe 从版本文件里挑出入口 exe:优先 version.entry_file 同名项,退化到第一个 .exe
func pickEntryExe(v *model.Version, files []model.VersionFile) (*model.VersionFile, error) {
want := strings.ToLower(filepath.Base(v.EntryFile))
if want != "" && want != "." {
for i := range files {
if strings.ToLower(filepath.Base(files[i].FileName)) == want {
return &files[i], nil
}
}
}
for i := range files {
if strings.HasSuffix(strings.ToLower(files[i].FileName), ".exe") {
return &files[i], nil
}
}
return nil, fmt.Errorf("版本 %s 里没有 .exe(共 %d 个文件)", v.Version, len(files))
}
// auditLog 把 MCP 写操作记进 verify 自己的 logs 表(user_id 留空表示系统/MCP 操作)
+1 -1
View File
@@ -4,9 +4,9 @@ import (
"time"
"verification-platform-backend/internal/middleware"
"verification-platform-backend/internal/router/admin"
"verification-platform-backend/internal/router/agent"
"verification-platform-backend/internal/router/app"
"verification-platform-backend/internal/router/admin"
"verification-platform-backend/internal/router/extension"
"verification-platform-backend/internal/router/frontend"
"verification-platform-backend/internal/router/install"
+12 -12
View File
@@ -10,22 +10,22 @@ import (
)
type CleanupConfig struct {
EnableAutoCleanup bool
CleanupIntervalHours int
CaptchaRetentionDays int
VerifyCodeRetentionDays int
ApiUsageRetentionDays int
WebhookLogRetentionDays int
EnableAutoCleanup bool
CleanupIntervalHours int
CaptchaRetentionDays int
VerifyCodeRetentionDays int
ApiUsageRetentionDays int
WebhookLogRetentionDays int
DeviceSessionRetentionDays int
}
var defaultConfig = CleanupConfig{
EnableAutoCleanup: false,
CleanupIntervalHours: 24,
CaptchaRetentionDays: 1,
VerifyCodeRetentionDays: 7,
ApiUsageRetentionDays: 30,
WebhookLogRetentionDays: 30,
EnableAutoCleanup: false,
CleanupIntervalHours: 24,
CaptchaRetentionDays: 1,
VerifyCodeRetentionDays: 7,
ApiUsageRetentionDays: 30,
WebhookLogRetentionDays: 30,
DeviceSessionRetentionDays: 7,
}
@@ -0,0 +1,55 @@
package service
import (
"crypto/subtle"
"log"
"strings"
"verification-platform-backend/internal/database"
"verification-platform-backend/internal/model"
"golang.org/x/crypto/bcrypt"
)
// IsBcryptHash 判断库里的口令字段是不是 bcrypt 哈希
func IsBcryptHash(s string) bool {
return strings.HasPrefix(s, "$2a$") || strings.HasPrefix(s, "$2b$") || strings.HasPrefix(s, "$2y$")
}
// HashAppUserPassword 终端用户新口令入库前的统一哈希
func HashAppUserPassword(plain string) (string, error) {
h, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)
return string(h), err
}
// VerifyAppUserPassword 校验终端用户口令,兼容历史明文
//
// 历史原因 app_users.password 里混着明文和 bcrypt(注册写明文、重置写哈希)。
// 这里两条都认:bcrypt 直接比对;明文用定长比较,命中后顺手升级成 bcrypt。
// 升级用 WHERE password = 旧值 做条件更新,避免并发把别人刚写的哈希覆盖回去。
// 升级写库失败不影响本次登录结果——放行,等下次再升。
func VerifyAppUserPassword(user *model.AppUser, plain string) bool {
if user == nil || user.Password == "" {
return false
}
if IsBcryptHash(user.Password) {
return bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(plain)) == nil
}
if subtle.ConstantTimeCompare([]byte(user.Password), []byte(plain)) != 1 {
return false
}
h, err := HashAppUserPassword(plain)
if err != nil {
log.Printf("[appuser] 口令升级失败 user=%d: %v", user.ID, err)
return true
}
res := database.DB.Model(&model.AppUser{}).
Where("id = ? AND password = ?", user.ID, user.Password).
Update("password", h)
if res.Error != nil {
log.Printf("[appuser] 口令升级写库失败 user=%d: %v", user.ID, res.Error)
return true
}
user.Password = h
return true
}
@@ -0,0 +1,71 @@
package service
import (
"testing"
"verification-platform-backend/internal/model"
"golang.org/x/crypto/bcrypt"
)
func TestHashAndVerifyAppUserPassword(t *testing.T) {
h, err := HashAppUserPassword("123456")
if err != nil {
t.Fatalf("哈希失败: %v", err)
}
if !IsBcryptHash(h) {
t.Fatalf("哈希前缀不识别: %s", h[:7])
}
u := &model.AppUser{Password: h}
if !VerifyAppUserPassword(u, "123456") {
t.Fatal("正确口令未通过")
}
if VerifyAppUserPassword(u, "1234567") {
t.Fatal("错误口令通过了")
}
if VerifyAppUserPassword(nil, "123456") {
t.Fatal("nil 用户通过了")
}
if VerifyAppUserPassword(&model.AppUser{}, "x") {
t.Fatal("空口令用户通过了")
}
}
// 历史明文必须仍然认账(这里只测比对分支:口令不符时不触发写库)
func TestVerifyLegacyPlaintextMismatch(t *testing.T) {
u := &model.AppUser{Password: "plain-old"}
if VerifyAppUserPassword(u, "wrong") {
t.Fatal("明文错误口令通过了")
}
if IsBcryptHash("plain-old") {
t.Fatal("明文被误判成 bcrypt")
}
}
func TestIsBcryptHash(t *testing.T) {
cases := map[string]bool{
"$2a$10$abc": true,
"$2b$12$xyz": true,
"$2y$05$q": true,
"123456": false,
"": false,
"$2a": false,
}
for in, want := range cases {
if got := IsBcryptHash(in); got != want {
t.Fatalf("IsBcryptHash(%q)=%v 期望 %v", in, got, want)
}
}
}
func TestBcryptRoundTripCost(t *testing.T) {
// 成本不能被误改成 4 以下
h, err := bcrypt.GenerateFromPassword([]byte("x"), bcrypt.DefaultCost)
if err != nil {
t.Fatal(err)
}
c, err := bcrypt.Cost(h)
if err != nil || c != bcrypt.DefaultCost {
t.Fatalf("成本 %v 期望 %v (err=%v)", c, bcrypt.DefaultCost, err)
}
}
+7 -7
View File
@@ -56,13 +56,13 @@ func (s *AuthService) Login(username, password, agentPath string) (map[string]in
// 返回用户信息和令牌
return map[string]interface{}{
"user": map[string]interface{}{
"id": user.ID,
"username": user.Username,
"email": user.Email,
"avatar": user.Avatar,
"role": user.Role,
"status": user.Status,
"parent_agent_id": user.ParentAgentID,
"id": user.ID,
"username": user.Username,
"email": user.Email,
"avatar": user.Avatar,
"role": user.Role,
"status": user.Status,
"parent_agent_id": user.ParentAgentID,
"can_view_cloud_data": user.CanViewCloudData,
},
"token": token,
+23
View File
@@ -165,6 +165,29 @@ func LogOperationWithApp(c *gin.Context, applicationID *uint, action, resource s
return logService.LogOperationWithApp(c, applicationID, action, resource, resourceID, details, err)
}
// LogVerificationCard 同 LogVerification,额外记下卡型(卡密登录失败用)
func LogVerificationCard(c *gin.Context, applicationID *uint, appUserID *uint, action, details string, deviceID string, err error, cardTypeID *uint) error {
l := &model.Log{
ApplicationID: applicationID,
AppUserID: appUserID,
LogType: "verification",
Action: action,
Details: details,
DeviceID: deviceID,
CardTypeID: cardTypeID,
Status: "success",
}
if err != nil {
l.Status = "failed"
l.ErrorMessage = err.Error()
}
if c != nil {
l.IPAddress = c.ClientIP()
l.UserAgent = c.Request.UserAgent()
}
return database.DB.Create(l).Error
}
func LogVerification(c *gin.Context, applicationID *uint, appUserID *uint, action, details string, DeviceFingerprint string, err error) error {
return logService.LogVerification(c, applicationID, appUserID, action, details, DeviceFingerprint, err)
}
+77 -77
View File
@@ -66,46 +66,46 @@ func GetApplicationDisabledStatus(appID uint) bool {
}
type ApplicationWithStatus struct {
ID uint `json:"id"`
UserID uint `json:"user_id"`
Name string `json:"name"`
Description string `json:"description"`
AppKey string `json:"app_key"`
IconURL string `json:"icon_url"`
Status string `json:"status"`
BillingType string `json:"billing_type"`
LoginPolicy string `json:"login_policy"`
MaxDevices int `json:"max_devices"`
MultiOpenMode string `json:"multi_open_mode"`
EnableTrial bool `json:"enable_trial"`
TrialDays int `json:"trial_days"`
EnableFreePeriod bool `json:"enable_free_period"`
FreePeriodType string `json:"free_period_type"`
FreePeriodStart string `json:"free_period_start"`
FreePeriodEnd string `json:"free_period_end"`
FreePeriodWeekdays string `json:"free_period_weekdays"`
FreePeriodStartTime string `json:"free_period_start_time"`
FreePeriodEndTime string `json:"free_period_end_time"`
HeartbeatInterval int `json:"heartbeat_interval"`
HeartbeatTimeout int `json:"heartbeat_timeout"`
MaxAttempts int `json:"max_attempts"`
LockDuration int `json:"lock_duration"`
DeductionMode string `json:"deduction_mode"`
DeductionType string `json:"deduction_type"`
DeductionInterval int `json:"deduction_interval"`
DeductionUnit string `json:"deduction_unit"`
DeductionAmount float64 `json:"deduction_amount"`
AllowRegister bool `json:"allow_register"`
EnableLoginVerify bool `json:"enable_login_verify"`
EnableRegisterVerify bool `json:"enable_register_verify"`
VerifyMethod string `json:"verify_method"`
EnablePasswordReset bool `json:"enable_password_reset"`
PasswordResetMethod string `json:"password_reset_method"`
PasswordResetEmailID *uint `json:"password_reset_email_id"`
PasswordResetSmsID *uint `json:"password_reset_sms_id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
DisabledByPackage bool `json:"disabled_by_package"`
ID uint `json:"id"`
UserID uint `json:"user_id"`
Name string `json:"name"`
Description string `json:"description"`
AppKey string `json:"app_key"`
IconURL string `json:"icon_url"`
Status string `json:"status"`
BillingType string `json:"billing_type"`
LoginPolicy string `json:"login_policy"`
MaxDevices int `json:"max_devices"`
MultiOpenMode string `json:"multi_open_mode"`
EnableTrial bool `json:"enable_trial"`
TrialDays int `json:"trial_days"`
EnableFreePeriod bool `json:"enable_free_period"`
FreePeriodType string `json:"free_period_type"`
FreePeriodStart string `json:"free_period_start"`
FreePeriodEnd string `json:"free_period_end"`
FreePeriodWeekdays string `json:"free_period_weekdays"`
FreePeriodStartTime string `json:"free_period_start_time"`
FreePeriodEndTime string `json:"free_period_end_time"`
HeartbeatInterval int `json:"heartbeat_interval"`
HeartbeatTimeout int `json:"heartbeat_timeout"`
MaxAttempts int `json:"max_attempts"`
LockDuration int `json:"lock_duration"`
DeductionMode string `json:"deduction_mode"`
DeductionType string `json:"deduction_type"`
DeductionInterval int `json:"deduction_interval"`
DeductionUnit string `json:"deduction_unit"`
DeductionAmount float64 `json:"deduction_amount"`
AllowRegister bool `json:"allow_register"`
EnableLoginVerify bool `json:"enable_login_verify"`
EnableRegisterVerify bool `json:"enable_register_verify"`
VerifyMethod string `json:"verify_method"`
EnablePasswordReset bool `json:"enable_password_reset"`
PasswordResetMethod string `json:"password_reset_method"`
PasswordResetEmailID *uint `json:"password_reset_email_id"`
PasswordResetSmsID *uint `json:"password_reset_sms_id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
DisabledByPackage bool `json:"disabled_by_package"`
}
func GetApplicationsWithDisabledStatus(userID uint) ([]ApplicationWithStatus, error) {
@@ -122,45 +122,45 @@ func GetApplicationsWithDisabledStatus(userID uint) ([]ApplicationWithStatus, er
result := make([]ApplicationWithStatus, len(apps))
for i, app := range apps {
result[i] = ApplicationWithStatus{
ID: app.ID,
UserID: app.UserID,
Name: app.Name,
Description: app.Description,
AppKey: app.AppKey,
IconURL: app.IconURL,
Status: app.Status,
BillingType: app.BillingType,
LoginPolicy: app.LoginPolicy,
MaxDevices: app.MaxDevices,
MultiOpenMode: app.MultiOpenMode,
EnableTrial: app.EnableTrial,
TrialDays: app.TrialDays,
EnableFreePeriod: app.EnableFreePeriod,
FreePeriodType: app.FreePeriodType,
FreePeriodStart: app.FreePeriodStart,
FreePeriodEnd: app.FreePeriodEnd,
FreePeriodWeekdays: app.FreePeriodWeekdays,
FreePeriodStartTime: app.FreePeriodStartTime,
FreePeriodEndTime: app.FreePeriodEndTime,
HeartbeatInterval: app.HeartbeatInterval,
HeartbeatTimeout: app.HeartbeatTimeout,
MaxAttempts: app.MaxAttempts,
LockDuration: app.LockDuration,
DeductionMode: app.DeductionMode,
DeductionType: app.DeductionType,
DeductionInterval: app.DeductionInterval,
DeductionUnit: app.DeductionUnit,
DeductionAmount: app.DeductionAmount,
AllowRegister: app.AllowRegister,
EnableLoginVerify: app.EnableLoginVerify,
ID: app.ID,
UserID: app.UserID,
Name: app.Name,
Description: app.Description,
AppKey: app.AppKey,
IconURL: app.IconURL,
Status: app.Status,
BillingType: app.BillingType,
LoginPolicy: app.LoginPolicy,
MaxDevices: app.MaxDevices,
MultiOpenMode: app.MultiOpenMode,
EnableTrial: app.EnableTrial,
TrialDays: app.TrialDays,
EnableFreePeriod: app.EnableFreePeriod,
FreePeriodType: app.FreePeriodType,
FreePeriodStart: app.FreePeriodStart,
FreePeriodEnd: app.FreePeriodEnd,
FreePeriodWeekdays: app.FreePeriodWeekdays,
FreePeriodStartTime: app.FreePeriodStartTime,
FreePeriodEndTime: app.FreePeriodEndTime,
HeartbeatInterval: app.HeartbeatInterval,
HeartbeatTimeout: app.HeartbeatTimeout,
MaxAttempts: app.MaxAttempts,
LockDuration: app.LockDuration,
DeductionMode: app.DeductionMode,
DeductionType: app.DeductionType,
DeductionInterval: app.DeductionInterval,
DeductionUnit: app.DeductionUnit,
DeductionAmount: app.DeductionAmount,
AllowRegister: app.AllowRegister,
EnableLoginVerify: app.EnableLoginVerify,
EnableRegisterVerify: app.EnableRegisterVerify,
VerifyMethod: app.VerifyMethod,
EnablePasswordReset: app.EnablePasswordReset,
PasswordResetMethod: app.PasswordResetMethod,
VerifyMethod: app.VerifyMethod,
EnablePasswordReset: app.EnablePasswordReset,
PasswordResetMethod: app.PasswordResetMethod,
PasswordResetEmailID: app.PasswordResetEmailID,
PasswordResetSmsID: app.PasswordResetSmsID,
CreatedAt: app.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
UpdatedAt: app.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
PasswordResetSmsID: app.PasswordResetSmsID,
CreatedAt: app.CreatedAt.Format("2006-01-02T15:04:05Z07:00"),
UpdatedAt: app.UpdatedAt.Format("2006-01-02T15:04:05Z07:00"),
}
}
@@ -0,0 +1,10 @@
# Treat all files in this repo as binary, with no git magic updating
# line endings. Windows users contributing to Go will need to use a
# modern version of git and editors capable of LF line endings.
#
# We'll prevent accidental CRLF line endings from entering the repo
# via the git-review gofmt checks.
#
# See golang.org/issue/9281
* -text
+2
View File
@@ -0,0 +1,2 @@
# Add no patterns to .hgignore except for files generated by the build.
last-change
+28
View File
@@ -0,0 +1,28 @@
Copyright (c) 2015, 2018, 2019 Opsmate, Inc. All rights reserved.
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+31
View File
@@ -0,0 +1,31 @@
# package pkcs12
[![Documentation](https://pkg.go.dev/badge/software.sslmate.com/src/go-pkcs12)](https://pkg.go.dev/software.sslmate.com/src/go-pkcs12)
import "software.sslmate.com/src/go-pkcs12"
Package pkcs12 implements some of PKCS#12 (also known as P12 or PFX).
It is intended for decoding DER-encoded P12/PFX files for use with the `crypto/tls`
package, and for encoding P12/PFX files for use by legacy applications which
do not support newer formats. Since PKCS#12 uses weak encryption
primitives, it SHOULD NOT be used for new applications.
Note that only DER-encoded PKCS#12 files are supported, even though PKCS#12
allows BER encoding. This is because encoding/asn1 only supports DER.
This package is forked from `golang.org/x/crypto/pkcs12`, which is frozen.
The implementation is distilled from https://tools.ietf.org/html/rfc7292
and referenced documents.
## Import Path
Note that although the source code and issue tracker for this package are hosted
on GitHub, the import path is:
software.sslmate.com/src/go-pkcs12
Please be sure to use this path when you `go get` and `import` this package.
## Report Issues / Send Patches
Open an issue or PR at https://github.com/SSLMate/go-pkcs12
+63
View File
@@ -0,0 +1,63 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pkcs12
import (
"errors"
"unicode/utf16"
)
// bmpStringZeroTerminated returns s encoded in UCS-2 with a zero terminator.
func bmpStringZeroTerminated(s string) ([]byte, error) {
// References:
// https://tools.ietf.org/html/rfc7292#appendix-B.1
// The above RFC provides the info that BMPStrings are NULL terminated.
ret, err := bmpString(s)
if err != nil {
return nil, err
}
return append(ret, 0, 0), nil
}
// bmpString returns s encoded in UCS-2
func bmpString(s string) ([]byte, error) {
// References:
// https://tools.ietf.org/html/rfc7292#appendix-B.1
// https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane
// - non-BMP characters are encoded in UTF 16 by using a surrogate pair of 16-bit codes
// EncodeRune returns 0xfffd if the rune does not need special encoding
ret := make([]byte, 0, 2*len(s)+2)
for _, r := range s {
if t, _ := utf16.EncodeRune(r); t != 0xfffd {
return nil, errors.New("pkcs12: string contains characters that cannot be encoded in UCS-2")
}
ret = append(ret, byte(r/256), byte(r%256))
}
return ret, nil
}
func decodeBMPString(bmpString []byte) (string, error) {
if len(bmpString)%2 != 0 {
return "", errors.New("pkcs12: odd-length BMP string")
}
// strip terminator if present
if l := len(bmpString); l >= 2 && bmpString[l-1] == 0 && bmpString[l-2] == 0 {
bmpString = bmpString[:l-2]
}
s := make([]uint16, 0, len(bmpString)/2)
for len(bmpString) > 0 {
s = append(s, uint16(bmpString[0])<<8+uint16(bmpString[1]))
bmpString = bmpString[2:]
}
return string(utf16.Decode(s)), nil
}
+321
View File
@@ -0,0 +1,321 @@
// Copyright 2015, 2018, 2019 Opsmate, Inc. All rights reserved.
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pkcs12
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/des"
"crypto/sha1"
"crypto/sha256"
"crypto/x509/pkix"
"encoding/asn1"
"errors"
"hash"
"io"
"golang.org/x/crypto/pbkdf2"
"software.sslmate.com/src/go-pkcs12/internal/rc2"
)
var (
oidPBEWithSHAAnd3KeyTripleDESCBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 3})
oidPBEWithSHAAnd128BitRC2CBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 5})
oidPBEWithSHAAnd40BitRC2CBC = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 12, 1, 6})
oidPBES2 = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 5, 13})
oidPBKDF2 = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 1, 5, 12})
oidHmacWithSHA1 = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 2, 7})
oidHmacWithSHA256 = asn1.ObjectIdentifier([]int{1, 2, 840, 113549, 2, 9})
oidAES128CBC = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 1, 2})
oidAES192CBC = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 1, 22})
oidAES256CBC = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 1, 42})
)
// pbeCipher is an abstraction of a PKCS#12 cipher.
type pbeCipher interface {
// create returns a cipher.Block given a key.
create(key []byte) (cipher.Block, error)
// deriveKey returns a key derived from the given password and salt.
deriveKey(salt, password []byte, iterations int) []byte
// deriveKey returns an IV derived from the given password and salt.
deriveIV(salt, password []byte, iterations int) []byte
}
type shaWithTripleDESCBC struct{}
func (shaWithTripleDESCBC) create(key []byte) (cipher.Block, error) {
return des.NewTripleDESCipher(key)
}
func (shaWithTripleDESCBC) deriveKey(salt, password []byte, iterations int) []byte {
return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 24)
}
func (shaWithTripleDESCBC) deriveIV(salt, password []byte, iterations int) []byte {
return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8)
}
type shaWith128BitRC2CBC struct{}
func (shaWith128BitRC2CBC) create(key []byte) (cipher.Block, error) {
return rc2.New(key, len(key)*8)
}
func (shaWith128BitRC2CBC) deriveKey(salt, password []byte, iterations int) []byte {
return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 16)
}
func (shaWith128BitRC2CBC) deriveIV(salt, password []byte, iterations int) []byte {
return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8)
}
type shaWith40BitRC2CBC struct{}
func (shaWith40BitRC2CBC) create(key []byte) (cipher.Block, error) {
return rc2.New(key, len(key)*8)
}
func (shaWith40BitRC2CBC) deriveKey(salt, password []byte, iterations int) []byte {
return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 1, 5)
}
func (shaWith40BitRC2CBC) deriveIV(salt, password []byte, iterations int) []byte {
return pbkdf(sha1Sum, 20, 64, salt, password, iterations, 2, 8)
}
type pbeParams struct {
Salt []byte
Iterations int
}
func pbeCipherFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.Block, []byte, error) {
var cipherType pbeCipher
switch {
case algorithm.Algorithm.Equal(oidPBEWithSHAAnd3KeyTripleDESCBC):
cipherType = shaWithTripleDESCBC{}
case algorithm.Algorithm.Equal(oidPBEWithSHAAnd128BitRC2CBC):
cipherType = shaWith128BitRC2CBC{}
case algorithm.Algorithm.Equal(oidPBEWithSHAAnd40BitRC2CBC):
cipherType = shaWith40BitRC2CBC{}
case algorithm.Algorithm.Equal(oidPBES2):
// rfc7292#appendix-B.1 (the original PKCS#12 PBE) requires passwords formatted as BMPStrings.
// However, rfc8018#section-3 recommends that the password for PBES2 follow ASCII or UTF-8.
// This is also what Windows expects.
// Therefore, we convert the password to UTF-8.
originalPassword, err := decodeBMPString(password)
if err != nil {
return nil, nil, err
}
utf8Password := []byte(originalPassword)
return pbes2CipherFor(algorithm, utf8Password)
default:
return nil, nil, NotImplementedError("algorithm " + algorithm.Algorithm.String() + " is not supported")
}
var params pbeParams
if err := unmarshal(algorithm.Parameters.FullBytes, &params); err != nil {
return nil, nil, err
}
key := cipherType.deriveKey(params.Salt, password, params.Iterations)
iv := cipherType.deriveIV(params.Salt, password, params.Iterations)
block, err := cipherType.create(key)
if err != nil {
return nil, nil, err
}
return block, iv, nil
}
func pbDecrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.BlockMode, int, error) {
block, iv, err := pbeCipherFor(algorithm, password)
if err != nil {
return nil, 0, err
}
return cipher.NewCBCDecrypter(block, iv), block.BlockSize(), nil
}
func pbDecrypt(info decryptable, password []byte) (decrypted []byte, err error) {
cbc, blockSize, err := pbDecrypterFor(info.Algorithm(), password)
if err != nil {
return nil, err
}
encrypted := info.Data()
if len(encrypted) == 0 {
return nil, errors.New("pkcs12: empty encrypted data")
}
if len(encrypted)%blockSize != 0 {
return nil, errors.New("pkcs12: input is not a multiple of the block size")
}
decrypted = make([]byte, len(encrypted))
cbc.CryptBlocks(decrypted, encrypted)
psLen := int(decrypted[len(decrypted)-1])
if psLen == 0 || psLen > blockSize {
return nil, ErrDecryption
}
if len(decrypted) < psLen {
return nil, ErrDecryption
}
ps := decrypted[len(decrypted)-psLen:]
decrypted = decrypted[:len(decrypted)-psLen]
if bytes.Compare(ps, bytes.Repeat([]byte{byte(psLen)}, psLen)) != 0 {
return nil, ErrDecryption
}
return
}
// PBES2-params ::= SEQUENCE {
// keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
// encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}
// }
type pbes2Params struct {
Kdf pkix.AlgorithmIdentifier
EncryptionScheme pkix.AlgorithmIdentifier
}
// PBKDF2-params ::= SEQUENCE {
// salt CHOICE {
// specified OCTET STRING,
// otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}
// },
// iterationCount INTEGER (1..MAX),
// keyLength INTEGER (1..MAX) OPTIONAL,
// prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT
// algid-hmacWithSHA1
// }
type pbkdf2Params struct {
Salt asn1.RawValue
Iterations int
KeyLength int `asn1:"optional"`
Prf pkix.AlgorithmIdentifier `asn1:"optional"`
}
func pbes2CipherFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.Block, []byte, error) {
var params pbes2Params
if err := unmarshal(algorithm.Parameters.FullBytes, &params); err != nil {
return nil, nil, err
}
if !params.Kdf.Algorithm.Equal(oidPBKDF2) {
return nil, nil, NotImplementedError("kdf algorithm " + params.Kdf.Algorithm.String() + " is not supported")
}
var kdfParams pbkdf2Params
if err := unmarshal(params.Kdf.Parameters.FullBytes, &kdfParams); err != nil {
return nil, nil, err
}
if kdfParams.Salt.Tag != asn1.TagOctetString {
return nil, nil, errors.New("pkcs12: only octet string salts are supported for pbkdf2")
}
var prf func() hash.Hash
switch {
case kdfParams.Prf.Algorithm.Equal(oidHmacWithSHA256):
prf = sha256.New
case kdfParams.Prf.Algorithm.Equal(oidHmacWithSHA1):
prf = sha1.New
case kdfParams.Prf.Algorithm.Equal(asn1.ObjectIdentifier([]int{})):
prf = sha1.New
default:
return nil, nil, NotImplementedError("pbes2 prf " + kdfParams.Prf.Algorithm.String() + " is not supported")
}
var keyLen int
switch {
case params.EncryptionScheme.Algorithm.Equal(oidAES256CBC):
keyLen = 32
case params.EncryptionScheme.Algorithm.Equal(oidAES192CBC):
keyLen = 24
case params.EncryptionScheme.Algorithm.Equal(oidAES128CBC):
keyLen = 16
default:
return nil, nil, NotImplementedError("pbes2 algorithm " + params.EncryptionScheme.Algorithm.String() + " is not supported")
}
key := pbkdf2.Key(password, kdfParams.Salt.Bytes, kdfParams.Iterations, keyLen, prf)
iv := params.EncryptionScheme.Parameters.Bytes
block, err := aes.NewCipher(key)
if err != nil {
return nil, nil, err
}
return block, iv, nil
}
// decryptable abstracts an object that contains ciphertext.
type decryptable interface {
Algorithm() pkix.AlgorithmIdentifier
Data() []byte
}
func pbEncrypterFor(algorithm pkix.AlgorithmIdentifier, password []byte) (cipher.BlockMode, int, error) {
block, iv, err := pbeCipherFor(algorithm, password)
if err != nil {
return nil, 0, err
}
return cipher.NewCBCEncrypter(block, iv), block.BlockSize(), nil
}
func pbEncrypt(info encryptable, decrypted []byte, password []byte) error {
cbc, blockSize, err := pbEncrypterFor(info.Algorithm(), password)
if err != nil {
return err
}
psLen := blockSize - len(decrypted)%blockSize
encrypted := make([]byte, len(decrypted)+psLen)
copy(encrypted[:len(decrypted)], decrypted)
copy(encrypted[len(decrypted):], bytes.Repeat([]byte{byte(psLen)}, psLen))
cbc.CryptBlocks(encrypted, encrypted)
info.SetData(encrypted)
return nil
}
// encryptable abstracts a object that contains ciphertext.
type encryptable interface {
Algorithm() pkix.AlgorithmIdentifier
SetData([]byte)
}
func makePBES2Parameters(rand io.Reader, salt []byte, iterations int) ([]byte, error) {
var err error
randomIV := make([]byte, 16)
if _, err := rand.Read(randomIV); err != nil {
return nil, err
}
var kdfparams pbkdf2Params
if kdfparams.Salt.FullBytes, err = asn1.Marshal(salt); err != nil {
return nil, err
}
kdfparams.Iterations = iterations
kdfparams.Prf.Algorithm = oidHmacWithSHA256
var params pbes2Params
params.Kdf.Algorithm = oidPBKDF2
if params.Kdf.Parameters.FullBytes, err = asn1.Marshal(kdfparams); err != nil {
return nil, err
}
params.EncryptionScheme.Algorithm = oidAES256CBC
if params.EncryptionScheme.Parameters.FullBytes, err = asn1.Marshal(randomIV); err != nil {
return nil, err
}
return asn1.Marshal(params)
}
+23
View File
@@ -0,0 +1,23 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pkcs12
import "errors"
var (
// ErrDecryption represents a failure to decrypt the input.
ErrDecryption = errors.New("pkcs12: decryption error, incorrect padding")
// ErrIncorrectPassword is returned when an incorrect password is detected.
// Usually, P12/PFX data is signed to be able to verify the password.
ErrIncorrectPassword = errors.New("pkcs12: decryption password incorrect")
)
// NotImplementedError indicates that the input is not currently supported.
type NotImplementedError string
func (e NotImplementedError) Error() string {
return "pkcs12: " + string(e)
}
+5
View File
@@ -0,0 +1,5 @@
module software.sslmate.com/src/go-pkcs12
go 1.19
require golang.org/x/crypto v0.11.0
+20
View File
@@ -0,0 +1,20 @@
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g=
golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 h1:tkVvjkPTB7pnW3jnid7kNyAMPVWllTNOf/qKDze4p9o=
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA=
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -0,0 +1,27 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rc2
import (
"testing"
)
func BenchmarkEncrypt(b *testing.B) {
r, _ := New([]byte{0, 0, 0, 0, 0, 0, 0, 0}, 64)
b.ResetTimer()
var src [8]byte
for i := 0; i < b.N; i++ {
r.Encrypt(src[:], src[:])
}
}
func BenchmarkDecrypt(b *testing.B) {
r, _ := New([]byte{0, 0, 0, 0, 0, 0, 0, 0}, 64)
b.ResetTimer()
var src [8]byte
for i := 0; i < b.N; i++ {
r.Decrypt(src[:], src[:])
}
}
+271
View File
@@ -0,0 +1,271 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package rc2 implements the RC2 cipher
/*
https://www.ietf.org/rfc/rfc2268.txt
http://people.csail.mit.edu/rivest/pubs/KRRR98.pdf
This code is licensed under the MIT license.
*/
package rc2
import (
"crypto/cipher"
"encoding/binary"
)
// The rc2 block size in bytes
const BlockSize = 8
type rc2Cipher struct {
k [64]uint16
}
// New returns a new rc2 cipher with the given key and effective key length t1
func New(key []byte, t1 int) (cipher.Block, error) {
// TODO(dgryski): error checking for key length
return &rc2Cipher{
k: expandKey(key, t1),
}, nil
}
func (*rc2Cipher) BlockSize() int { return BlockSize }
var piTable = [256]byte{
0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,
0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,
0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,
0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,
0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,
0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,
0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,
0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,
0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,
0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,
0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,
0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,
0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,
0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,
0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,
0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad,
}
func expandKey(key []byte, t1 int) [64]uint16 {
l := make([]byte, 128)
copy(l, key)
var t = len(key)
var t8 = (t1 + 7) / 8
var tm = byte(255 % uint(1<<(8+uint(t1)-8*uint(t8))))
for i := len(key); i < 128; i++ {
l[i] = piTable[l[i-1]+l[uint8(i-t)]]
}
l[128-t8] = piTable[l[128-t8]&tm]
for i := 127 - t8; i >= 0; i-- {
l[i] = piTable[l[i+1]^l[i+t8]]
}
var k [64]uint16
for i := range k {
k[i] = uint16(l[2*i]) + uint16(l[2*i+1])*256
}
return k
}
func rotl16(x uint16, b uint) uint16 {
return (x >> (16 - b)) | (x << b)
}
func (c *rc2Cipher) Encrypt(dst, src []byte) {
r0 := binary.LittleEndian.Uint16(src[0:])
r1 := binary.LittleEndian.Uint16(src[2:])
r2 := binary.LittleEndian.Uint16(src[4:])
r3 := binary.LittleEndian.Uint16(src[6:])
var j int
for j <= 16 {
// mix r0
r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1)
r0 = rotl16(r0, 1)
j++
// mix r1
r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2)
r1 = rotl16(r1, 2)
j++
// mix r2
r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3)
r2 = rotl16(r2, 3)
j++
// mix r3
r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0)
r3 = rotl16(r3, 5)
j++
}
r0 = r0 + c.k[r3&63]
r1 = r1 + c.k[r0&63]
r2 = r2 + c.k[r1&63]
r3 = r3 + c.k[r2&63]
for j <= 40 {
// mix r0
r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1)
r0 = rotl16(r0, 1)
j++
// mix r1
r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2)
r1 = rotl16(r1, 2)
j++
// mix r2
r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3)
r2 = rotl16(r2, 3)
j++
// mix r3
r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0)
r3 = rotl16(r3, 5)
j++
}
r0 = r0 + c.k[r3&63]
r1 = r1 + c.k[r0&63]
r2 = r2 + c.k[r1&63]
r3 = r3 + c.k[r2&63]
for j <= 60 {
// mix r0
r0 = r0 + c.k[j] + (r3 & r2) + ((^r3) & r1)
r0 = rotl16(r0, 1)
j++
// mix r1
r1 = r1 + c.k[j] + (r0 & r3) + ((^r0) & r2)
r1 = rotl16(r1, 2)
j++
// mix r2
r2 = r2 + c.k[j] + (r1 & r0) + ((^r1) & r3)
r2 = rotl16(r2, 3)
j++
// mix r3
r3 = r3 + c.k[j] + (r2 & r1) + ((^r2) & r0)
r3 = rotl16(r3, 5)
j++
}
binary.LittleEndian.PutUint16(dst[0:], r0)
binary.LittleEndian.PutUint16(dst[2:], r1)
binary.LittleEndian.PutUint16(dst[4:], r2)
binary.LittleEndian.PutUint16(dst[6:], r3)
}
func (c *rc2Cipher) Decrypt(dst, src []byte) {
r0 := binary.LittleEndian.Uint16(src[0:])
r1 := binary.LittleEndian.Uint16(src[2:])
r2 := binary.LittleEndian.Uint16(src[4:])
r3 := binary.LittleEndian.Uint16(src[6:])
j := 63
for j >= 44 {
// unmix r3
r3 = rotl16(r3, 16-5)
r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0)
j--
// unmix r2
r2 = rotl16(r2, 16-3)
r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3)
j--
// unmix r1
r1 = rotl16(r1, 16-2)
r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2)
j--
// unmix r0
r0 = rotl16(r0, 16-1)
r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1)
j--
}
r3 = r3 - c.k[r2&63]
r2 = r2 - c.k[r1&63]
r1 = r1 - c.k[r0&63]
r0 = r0 - c.k[r3&63]
for j >= 20 {
// unmix r3
r3 = rotl16(r3, 16-5)
r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0)
j--
// unmix r2
r2 = rotl16(r2, 16-3)
r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3)
j--
// unmix r1
r1 = rotl16(r1, 16-2)
r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2)
j--
// unmix r0
r0 = rotl16(r0, 16-1)
r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1)
j--
}
r3 = r3 - c.k[r2&63]
r2 = r2 - c.k[r1&63]
r1 = r1 - c.k[r0&63]
r0 = r0 - c.k[r3&63]
for j >= 0 {
// unmix r3
r3 = rotl16(r3, 16-5)
r3 = r3 - c.k[j] - (r2 & r1) - ((^r2) & r0)
j--
// unmix r2
r2 = rotl16(r2, 16-3)
r2 = r2 - c.k[j] - (r1 & r0) - ((^r1) & r3)
j--
// unmix r1
r1 = rotl16(r1, 16-2)
r1 = r1 - c.k[j] - (r0 & r3) - ((^r0) & r2)
j--
// unmix r0
r0 = rotl16(r0, 16-1)
r0 = r0 - c.k[j] - (r3 & r2) - ((^r3) & r1)
j--
}
binary.LittleEndian.PutUint16(dst[0:], r0)
binary.LittleEndian.PutUint16(dst[2:], r1)
binary.LittleEndian.PutUint16(dst[4:], r2)
binary.LittleEndian.PutUint16(dst[6:], r3)
}
+92
View File
@@ -0,0 +1,92 @@
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package rc2
import (
"bytes"
"encoding/hex"
"testing"
)
func TestEncryptDecrypt(t *testing.T) {
// TODO(dgryski): add the rest of the test vectors from the RFC
var tests = []struct {
key string
plain string
cipher string
t1 int
}{
{
"0000000000000000",
"0000000000000000",
"ebb773f993278eff",
63,
},
{
"ffffffffffffffff",
"ffffffffffffffff",
"278b27e42e2f0d49",
64,
},
{
"3000000000000000",
"1000000000000001",
"30649edf9be7d2c2",
64,
},
{
"88",
"0000000000000000",
"61a8a244adacccf0",
64,
},
{
"88bca90e90875a",
"0000000000000000",
"6ccf4308974c267f",
64,
},
{
"88bca90e90875a7f0f79c384627bafb2",
"0000000000000000",
"1a807d272bbe5db1",
64,
},
{
"88bca90e90875a7f0f79c384627bafb2",
"0000000000000000",
"2269552ab0f85ca6",
128,
},
{
"88bca90e90875a7f0f79c384627bafb216f80a6f85920584c42fceb0be255daf1e",
"0000000000000000",
"5b78d3a43dfff1f1",
129,
},
}
for _, tt := range tests {
k, _ := hex.DecodeString(tt.key)
p, _ := hex.DecodeString(tt.plain)
c, _ := hex.DecodeString(tt.cipher)
b, _ := New(k, tt.t1)
var dst [8]byte
b.Encrypt(dst[:], p)
if !bytes.Equal(dst[:], c) {
t.Errorf("encrypt failed: got % 2x wanted % 2x\n", dst, c)
}
b.Decrypt(dst[:], c)
if !bytes.Equal(dst[:], p) {
t.Errorf("decrypt failed: got % 2x wanted % 2x\n", dst, p)
}
}
}
+71
View File
@@ -0,0 +1,71 @@
// Copyright 2015, 2018, 2019 Opsmate, Inc. All rights reserved.
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pkcs12
import (
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"crypto/x509/pkix"
"encoding/asn1"
"hash"
)
type macData struct {
Mac digestInfo
MacSalt []byte
Iterations int `asn1:"optional,default:1"`
}
// from PKCS#7:
type digestInfo struct {
Algorithm pkix.AlgorithmIdentifier
Digest []byte
}
var (
oidSHA1 = asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26})
oidSHA256 = asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 1})
)
func doMac(macData *macData, message, password []byte) ([]byte, error) {
var hFn func() hash.Hash
var key []byte
switch {
case macData.Mac.Algorithm.Algorithm.Equal(oidSHA1):
hFn = sha1.New
key = pbkdf(sha1Sum, 20, 64, macData.MacSalt, password, macData.Iterations, 3, 20)
case macData.Mac.Algorithm.Algorithm.Equal(oidSHA256):
hFn = sha256.New
key = pbkdf(sha256Sum, 32, 64, macData.MacSalt, password, macData.Iterations, 3, 32)
default:
return nil, NotImplementedError("unknown digest algorithm: " + macData.Mac.Algorithm.Algorithm.String())
}
mac := hmac.New(hFn, key)
mac.Write(message)
return mac.Sum(nil), nil
}
func verifyMac(macData *macData, message, password []byte) error {
expectedMAC, err := doMac(macData, message, password)
if err != nil {
return err
}
if !hmac.Equal(macData.Mac.Digest, expectedMAC) {
return ErrIncorrectPassword
}
return nil
}
func computeMac(macData *macData, message, password []byte) error {
digest, err := doMac(macData, message, password)
if err != nil {
return err
}
macData.Mac.Digest = digest
return nil
}

Some files were not shown because too many files have changed in this diff Show More