Compare commits
88
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb88a940c0 | ||
|
|
b45c11ef9f | ||
|
|
1175adec62 | ||
|
|
97a046ab00 | ||
|
|
74355c1dd2 | ||
|
|
a446a1ba37 | ||
|
|
f997035972 | ||
|
|
ead706ea52 | ||
|
|
bf381d8034 | ||
|
|
f283b4eae0 | ||
|
|
78d4a7c3aa | ||
|
|
fb3f549acc | ||
|
|
336c41a90f | ||
|
|
5d9c2ca0c9 | ||
|
|
944c3f31b3 | ||
|
|
5b193181d1 | ||
|
|
b7461cee27 | ||
|
|
02bb727f33 | ||
|
|
9b7cc01c3a | ||
|
|
c21326eea8 | ||
|
|
98ca1a6190 | ||
|
|
7d1ad7a417 | ||
|
|
6067e9517e | ||
|
|
ccdf5bd19b | ||
|
|
a98c9a36ac | ||
|
|
40c930cdbb | ||
|
|
7515565660 | ||
|
|
24e3f7b811 | ||
|
|
77e59f021c | ||
|
|
3f0962708c | ||
|
|
acbe3c5820 | ||
|
|
9e9a4b0674 | ||
|
|
f51a41db24 | ||
|
|
ae81ffbda1 | ||
|
|
85216901cc | ||
|
|
e60c209e59 | ||
|
|
105e5d381e | ||
|
|
21e9e6ed6e | ||
|
|
6016886f48 | ||
|
|
1e9e847762 | ||
|
|
cddb757e08 | ||
|
|
4c347a9623 | ||
|
|
fd1e6b213d | ||
|
|
52a3fddb32 | ||
|
|
ea3ef37a31 | ||
|
|
8a3ecc6594 | ||
|
|
3eb4ee653f | ||
|
|
9f4255f731 | ||
|
|
356e0b37f3 | ||
|
|
00edf61910 | ||
|
|
1e7867c67d | ||
|
|
72c8b615b3 | ||
|
|
01059ecd18 | ||
|
|
81f6bdbc50 | ||
|
|
dbfee003ca | ||
|
|
2575473f6c | ||
|
|
871c68e3b6 | ||
|
|
3e5195584f | ||
|
|
613486dde2 | ||
|
|
e026dc1364 | ||
|
|
b42a40434f | ||
|
|
8134874c64 | ||
|
|
a1cc236e74 | ||
|
|
02f7fd0feb | ||
|
|
850ab691b7 | ||
|
|
0fce2c8aef | ||
|
|
d942da1639 | ||
|
|
bd04ac88dd | ||
|
|
b275de31a7 | ||
|
|
f6a4c7d40a | ||
|
|
6340ba9e38 | ||
|
|
96d72f3611 | ||
|
|
8acf72dd6e | ||
|
|
1d4ad9bf54 | ||
|
|
621b783960 | ||
|
|
10347aa330 | ||
|
|
2e3b2e3875 | ||
|
|
64a0a5ed49 | ||
|
|
80bc105d95 | ||
|
|
5169bf249e | ||
|
|
7f19742c21 | ||
|
|
18ea287d3d | ||
|
|
72a7bdb3d6 | ||
|
|
8f7caad687 | ||
|
|
9d0c50e7f2 | ||
|
|
7840872f91 | ||
|
|
0eac13578e | ||
|
|
1a69b61e75 |
@@ -52,3 +52,6 @@ temp/
|
||||
|
||||
# Trae
|
||||
.trae/
|
||||
|
||||
# 壳源码的本地构建产物
|
||||
shell/**/out/
|
||||
|
||||
+40
-1
@@ -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"]
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// vfyfix — 修正壳节(.load,旧产物 .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 = ".load"
|
||||
legacySecName = ".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) || strings.HasPrefix(s.Name, legacySecName) {
|
||||
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 壳节 %s 文件偏移=0x%x 原始大小=%d flags=0x%x(bit1=%d)\n", path, sec.Name, 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)
|
||||
}
|
||||
@@ -4,6 +4,8 @@ app:
|
||||
port: "8080"
|
||||
jwt_secret: "your-secret-key-change-in-production"
|
||||
jwt_expire_hours: "24"
|
||||
# 加壳时写进壳 cfg 的站点根地址;留空则按请求头推断(反代需要传 X-Forwarded-Host)
|
||||
public_url: ""
|
||||
|
||||
database:
|
||||
host: "localhost"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -9,12 +9,10 @@ package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"verification-platform-backend/internal/config"
|
||||
"verification-platform-backend/internal/model"
|
||||
@@ -159,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{}{
|
||||
@@ -243,6 +220,8 @@ func runMigrations() {
|
||||
&model.VersionFile{},
|
||||
&model.CloudVariableRecord{},
|
||||
&model.ProtectTask{},
|
||||
&model.SignProfile{},
|
||||
&model.CertBlacklist{},
|
||||
}
|
||||
for _, m := range models {
|
||||
var err error
|
||||
@@ -261,6 +240,16 @@ func runMigrations() {
|
||||
// 导致心跳写设备时 Error 1265 Data truncated,设备表永远是空的。
|
||||
fixDeviceIDColumnType()
|
||||
|
||||
// 登录方式开关(login_mode)上线:enforce 为空的历史行补成 warn(只记录不拦截),
|
||||
// 这样升级后行为完全不变,面板也能显示真实状态;管理员确认影响面后再切 strict。
|
||||
if DB.Migrator().HasTable(&model.Application{}) {
|
||||
if err := DB.Model(&model.Application{}).
|
||||
Where("login_mode_enforce IS NULL OR login_mode_enforce = ''").
|
||||
Update("login_mode_enforce", "warn").Error; err != nil {
|
||||
log.Printf("[WARN] 回填 applications.login_mode_enforce 失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 迁移后复核:仍有表不存在时明确打出来,避免后续写库时报 1146 无从排查
|
||||
for _, m := range models {
|
||||
if !DB.Migrator().HasTable(m) {
|
||||
@@ -268,20 +257,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 {
|
||||
@@ -289,46 +292,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 列
|
||||
@@ -430,12 +397,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{
|
||||
@@ -472,7 +439,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,
|
||||
@@ -483,7 +450,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,
|
||||
@@ -494,7 +461,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,
|
||||
@@ -786,25 +753,52 @@ func initTicketData() {
|
||||
}
|
||||
}
|
||||
|
||||
// fixDeviceIDColumnType 把 user_devices.device_id 从数值类型改成字符串类型。
|
||||
// 只在 MySQL 上执行;列类型已经是 varchar 时跳过,可重复执行。
|
||||
func fixDeviceIDColumnType() {
|
||||
if strings.ToLower(config.GetString("database.type")) != "mysql" {
|
||||
// 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
|
||||
}
|
||||
var colType string
|
||||
if err := DB.Raw("SELECT column_type FROM information_schema.columns " +
|
||||
"WHERE table_schema = DATABASE() AND table_name = 'user_devices' AND column_name = 'device_id'").
|
||||
Scan(&colType).Error; err != nil {
|
||||
log.Printf("[MIGRATE] 读取 user_devices.device_id 类型失败: %v", err)
|
||||
renamed, err := renameIndexTo("cert_blacklists", "fingerprint",
|
||||
"uni_cert_blacklists_fingerprint", "fingerprint")
|
||||
if err != nil {
|
||||
log.Printf("[MIGRATE] cert_blacklists 唯一索引改名失败: %v", err)
|
||||
return
|
||||
}
|
||||
if colType == "" || strings.HasPrefix(strings.ToLower(colType), "varchar") || strings.HasPrefix(strings.ToLower(colType), "char") {
|
||||
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)
|
||||
}
|
||||
if err := DB.Exec("ALTER TABLE user_devices MODIFY COLUMN device_id VARCHAR(100) NULL").Error; err != nil {
|
||||
log.Printf("[MIGRATE][ERROR] user_devices.device_id 由 %s 改为 varchar(100) 失败: %v", colType, err)
|
||||
return
|
||||
}
|
||||
log.Printf("[MIGRATE] user_devices.device_id 已由 %s 改为 varchar(100)", colType)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
+263
-198
@@ -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,100 +166,107 @@ 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:both" json:"login_mode"` // account = 账号密码, card = 单卡直登, both = 两种都开
|
||||
// 登录方式开关的生效级别:off = 不校验(旧行为), warn = 只记录不拦截(灰度用), strict = 真正拦截
|
||||
LoginModeEnforce string `gorm:"size:16;default:warn" json:"login_mode_enforce"`
|
||||
// 切换登录方式后的宽限期截止时间:在此之前旧凭证仍然可用(避免一刀切锁死存量用户)
|
||||
LoginModeGraceUntil *time.Time `json:"login_mode_grace_until"`
|
||||
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"`
|
||||
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:"-"`
|
||||
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 版本文件模型
|
||||
@@ -284,6 +294,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"`
|
||||
@@ -303,6 +314,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"`
|
||||
@@ -366,10 +380,10 @@ type Order struct {
|
||||
// Log 日志模型
|
||||
type Log struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
UserID *uint `json:"user_id"`
|
||||
ApplicationID *uint `json:"application_id"`
|
||||
UserID *uint `gorm:"index:idx_logs_user_created,priority:1" json:"user_id"`
|
||||
ApplicationID *uint `gorm:"index:idx_logs_app_created,priority:1" json:"application_id"`
|
||||
AppUserID *uint `json:"app_user_id"`
|
||||
LogType string `gorm:"size:20;default:operation" json:"log_type"` // operation, verification, exception
|
||||
LogType string `gorm:"size:20;default:operation;index:idx_logs_type_status,priority:1" json:"log_type"` // operation, verification, exception
|
||||
Action string `gorm:"size:100" json:"action"`
|
||||
Resource string `gorm:"size:100" json:"resource"`
|
||||
ResourceID *uint `json:"resource_id"`
|
||||
@@ -377,17 +391,18 @@ 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"`
|
||||
Status string `gorm:"size:20;default:success" json:"status"` // success, failed, pending
|
||||
CardTypeID *uint `gorm:"index" json:"card_type_id"` // 卡密登录失败时记下这是哪个卡型的卡,便于按卡型看爆破
|
||||
Status string `gorm:"size:20;default:success;index:idx_logs_type_status,priority:2" 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"`
|
||||
StackTrace string `gorm:"type:text" json:"stack_trace"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
CreatedAt time.Time `gorm:"index:idx_logs_app_created,priority:2;index:idx_logs_user_created,priority:2" json:"created_at"`
|
||||
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 充值记录模型
|
||||
@@ -510,9 +525,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
|
||||
@@ -549,11 +564,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"`
|
||||
}
|
||||
@@ -682,7 +697,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"`
|
||||
@@ -714,23 +729,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"`
|
||||
@@ -756,14 +771,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 {
|
||||
@@ -778,35 +793,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"`
|
||||
}
|
||||
@@ -840,23 +855,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"`
|
||||
}
|
||||
@@ -895,29 +917,59 @@ type PackHistory struct {
|
||||
|
||||
// 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"` // 来源版本(从哪个版本加壳)
|
||||
SourceName string `gorm:"size:255" json:"source_name"`
|
||||
SourceSize int64 `json:"source_size"`
|
||||
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"`
|
||||
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"`
|
||||
@@ -1010,8 +1062,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"`
|
||||
@@ -1034,3 +1086,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"`
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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 }
|
||||
@@ -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 应当被拒绝")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package protect:服务端给 PE 注入验证壳(改入口 + 内嵌壳 DLL + 双层 CRC32)
|
||||
//
|
||||
// 产物结构:原 exe 追加 .vfy 节 = [48B 头][引导 blob][壳 DLL][配置 JSON]
|
||||
// 入口指向 .vfy 内的引导代码;引导代码反射加载 DLL(零落盘)。
|
||||
// 产物结构:原 exe 追加 .load 节 = [48B 头][引导 blob][壳 DLL][配置 JSON]
|
||||
// 入口指向 .load 内的引导代码;引导代码反射加载 DLL(零落盘)。
|
||||
package protect
|
||||
|
||||
import (
|
||||
@@ -15,25 +15,72 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"verification-platform-backend/internal/model"
|
||||
)
|
||||
|
||||
//go:embed assets/blob64.bin assets/blob32.bin assets/shell64.bin assets/shell32.bin
|
||||
//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"
|
||||
secName = ".load"
|
||||
legacySec = ".vfy" // 旧产物用 .vfy,检测时一并识别(新产物一律写 .load)
|
||||
shellVer = 8
|
||||
secAttrib = 0x60000020 // CODE | EXECUTE | READ
|
||||
)
|
||||
|
||||
// Assets 取出指定架构的 blob 与壳 DLL
|
||||
// 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:
|
||||
@@ -50,44 +97,105 @@ func Assets(arch string) (blob, dll []byte, err error) {
|
||||
return blob, dll, nil
|
||||
}
|
||||
|
||||
// DetectArch 判断目标 PE 是 x64 还是 x86
|
||||
func DetectArch(target []byte) (string, error) {
|
||||
// HasVfy 判断 PE 里是不是已经有壳节(.load,或旧产物的 .vfy)。
|
||||
// 二次加壳会在文件里留下两个壳节:旧壳的 cfg 指向老服务器、白占几百 KB,
|
||||
// 目标机跳的却是新节,排查时极易被旧头误导,所以入口直接挡掉。
|
||||
func HasVfy(target []byte) bool {
|
||||
f, err := pe.NewFile(bytes.NewReader(target))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("不是有效 PE: %w", err)
|
||||
return false
|
||||
}
|
||||
switch f.Machine {
|
||||
case pe.IMAGE_FILE_MACHINE_AMD64:
|
||||
return "x64", nil
|
||||
case pe.IMAGE_FILE_MACHINE_I386:
|
||||
return "x86", nil
|
||||
defer f.Close()
|
||||
for _, s := range f.Sections {
|
||||
if strings.HasPrefix(s.Name, secName) || strings.HasPrefix(s.Name, legacySec) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("不支持的架构 machine=0x%x", f.Machine)
|
||||
return false
|
||||
}
|
||||
|
||||
// Patch 把验证壳注入 target,返回产物与两份 CRC
|
||||
// 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) {
|
||||
blob, dll, err := Assets(arch)
|
||||
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)
|
||||
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 uint32
|
||||
EntryNew uint32
|
||||
SecRVA uint32
|
||||
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) ([]byte, Info, error) {
|
||||
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 {
|
||||
@@ -150,7 +258,11 @@ func patchWith(raw, blob, dll, cfg []byte) ([]byte, Info, error) {
|
||||
binary.LittleEndian.PutUint32(hdr[20:], uint32(len(cfg)))
|
||||
binary.LittleEndian.PutUint32(hdr[24:], entryRVA)
|
||||
binary.LittleEndian.PutUint32(hdr[28:], uint32(len(blob)))
|
||||
binary.LittleEndian.PutUint32(hdr[32:], 0) // flags
|
||||
flags := uint32(0)
|
||||
if signed {
|
||||
flags |= 2 // bit1:已签名构建,壳侧跳过整文件 CRC
|
||||
}
|
||||
binary.LittleEndian.PutUint32(hdr[32:], flags)
|
||||
|
||||
var sec bytes.Buffer
|
||||
sec.Write(hdr)
|
||||
@@ -198,13 +310,17 @@ func patchWith(raw, blob, dll, cfg []byte) ([]byte, Info, error) {
|
||||
skipAt := int(newFileOff) + crcOff
|
||||
binary.LittleEndian.PutUint32(out[skipAt:], 0)
|
||||
binary.LittleEndian.PutUint32(out[skipAt+4:], 0)
|
||||
crcF := crcSkip(out[:skipAt], out[skipAt+8:])
|
||||
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 = entryRVA
|
||||
info.EntryNew = newRVA + hdrSize
|
||||
info.SecRVA = newRVA
|
||||
info.EntryOld = uint64(entryRVA)
|
||||
info.EntryNew = uint64(newRVA) + hdrSize
|
||||
info.SecRVA = uint64(newRVA)
|
||||
info.SecSize = uint32(len(sectionData))
|
||||
info.CrcVfy = crcV
|
||||
info.CrcFile = crcF
|
||||
@@ -214,9 +330,24 @@ func patchWith(raw, blob, dll, cfg []byte) ([]byte, Info, error) {
|
||||
|
||||
// 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)
|
||||
cfg := fmt.Sprintf(`{"api":%q,"name":%q,"device_auto":1,"shell_ver":%d}`,
|
||||
api, appName, shellVer)
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -229,22 +360,94 @@ 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)
|
||||
}
|
||||
arch, err := DetectArch(src)
|
||||
if err != nil {
|
||||
return Info{}, 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 + ")"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out, info, err := Patch(src, cfg, arch)
|
||||
if err != nil {
|
||||
if perr != nil {
|
||||
err = perr
|
||||
return info, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
|
||||
@@ -282,7 +485,8 @@ func (r *Runner) OutPath(taskID uint, name string) string {
|
||||
if i := strings.LastIndex(base, "."); i > 0 {
|
||||
base = base[:i] + "_protected" + base[i:]
|
||||
} else {
|
||||
base += "_protected.exe"
|
||||
// 无扩展名(常见于 Linux 可执行)不加 .exe
|
||||
base += "_protected"
|
||||
}
|
||||
return filepath.Join(r.Dir, fmt.Sprintf("%d", taskID), base)
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ type PublishOptions struct {
|
||||
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("加壳任务不存在")
|
||||
return nil, fmt.Errorf("云端加密任务不存在")
|
||||
}
|
||||
if task.Status != "done" || task.OutputPath == "" {
|
||||
return nil, fmt.Errorf("任务尚未完成,无法生成版本")
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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 不该被接受(请用加壳任务类型自动判断)")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package protect
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
@@ -24,18 +25,30 @@ func Default() *Runner {
|
||||
}
|
||||
|
||||
// createTask 建库记录 + 把源文件落盘,返回任务与源文件路径
|
||||
func createTask(app *model.Application, userID uint, srcName string, data []byte) (*model.ProtectTask, string, error) {
|
||||
arch, err := DetectArch(data)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("不是有效的 Windows 程序: %w", err)
|
||||
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("这个文件已经是云端加密后的产物(带 .load/.vfy 节),请上传未加密的原始程序")
|
||||
}
|
||||
// 签名证书必须在建任务时就落库:execute 是 go 协程,事后 UPDATE 有窗口
|
||||
// 被它读到 NULL,导致证书被静默忽略(任务照样成功,只是没重签)。
|
||||
task := &model.ProtectTask{
|
||||
ApplicationID: app.ID,
|
||||
UserID: userID,
|
||||
SourceName: filepath.Base(srcName),
|
||||
SourceSize: int64(len(data)),
|
||||
Arch: arch,
|
||||
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)
|
||||
@@ -56,7 +69,9 @@ func execute(taskID uint, srcPath, srcName string, cfg []byte) (Info, error) {
|
||||
Updates(map[string]interface{}{"status": "running", "started_at": &now})
|
||||
|
||||
outPath := r.OutPath(taskID, srcName)
|
||||
info, err := r.Run(srcPath, outPath, cfg)
|
||||
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()
|
||||
@@ -69,7 +84,7 @@ func execute(taskID uint, srcPath, srcName string, cfg []byte) (Info, error) {
|
||||
fin := time.Now()
|
||||
database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).Updates(map[string]interface{}{
|
||||
"status": "done",
|
||||
"message": fmt.Sprintf("入口 0x%x → 0x%x,.vfy RVA=0x%x", info.EntryOld, info.EntryNew, info.SecRVA),
|
||||
"message": infoMessage(info),
|
||||
"output_name": filepath.Base(outPath),
|
||||
"output_size": int64(info.OutSize),
|
||||
"output_path": outPath,
|
||||
@@ -84,11 +99,39 @@ func execute(taskID uint, srcPath, srcName string, cfg []byte) (Info, error) {
|
||||
|
||||
// CreateAndRun 建任务 → 落盘源文件 → 异步加壳。返回的任务状态为 pending。
|
||||
func CreateAndRun(app *model.Application, userID uint, srcName string, data []byte, baseURL string) (*model.ProtectTask, error) {
|
||||
task, srcPath, err := createTask(app, userID, srcName, data)
|
||||
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
|
||||
}
|
||||
cfg := BuildCfg(app.AppKey, app.Name, baseURL)
|
||||
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
|
||||
}
|
||||
@@ -100,7 +143,20 @@ func CreateAndRunSync(app *model.Application, userID uint, srcName string, data
|
||||
|
||||
// CreateAndRunSyncWithVersion 同步加壳并记录来源版本(versionID 可为 0)
|
||||
func CreateAndRunSyncWithVersion(app *model.Application, userID uint, srcName string, data []byte, baseURL string, versionID uint) (*model.ProtectTask, Info, error) {
|
||||
task, srcPath, err := createTask(app, userID, srcName, data)
|
||||
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
|
||||
}
|
||||
@@ -108,13 +164,25 @@ func CreateAndRunSyncWithVersion(app *model.Application, userID uint, srcName st
|
||||
database.DB.Model(task).Update("version_id", versionID)
|
||||
task.VersionID = versionID
|
||||
}
|
||||
info, err := execute(task.ID, srcPath, srcName, BuildCfg(app.AppKey, app.Name, baseURL))
|
||||
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++ {
|
||||
@@ -125,3 +193,11 @@ func WaitSource(path string) error {
|
||||
}
|
||||
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,壳节 RVA=0x%x", info.EntryOld, info.EntryNew, info.SecRVA)
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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, "参数错误")
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ func SetupApplicationRoutes(r *gin.RouterGroup) {
|
||||
applications.PUT("/:id", handleUpdateApplication)
|
||||
applications.DELETE("/:id", handleDeleteApplication)
|
||||
applications.GET("/:id", handleGetApplication)
|
||||
applications.GET("/:id/login-mode-impact", handleLoginModeImpact)
|
||||
applications.POST("/:id/icon", handleUploadIcon)
|
||||
applications.POST("/:id/upload", handleUploadVersionFile)
|
||||
applications.GET("/:id/versions", handleGetVersions)
|
||||
@@ -89,48 +90,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 +206,51 @@ 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,
|
||||
LoginMode: "both", // 新建应用默认两种登录方式都开,避免上线即把某一类用户挡在门外
|
||||
LoginModeEnforce: "warn", // 默认只记录不拦截,管理员确认影响面后再切 strict
|
||||
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 +300,56 @@ 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"`
|
||||
// 登录方式开关的生效级别与宽限期(前端「登录方式」卡片里的那两项)
|
||||
LoginModeEnforce string `form:"login_mode_enforce" json:"login_mode_enforce"`
|
||||
LoginModeGraceDays *int `form:"login_mode_grace_days" json:"login_mode_grace_days"`
|
||||
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 +384,38 @@ func handleUpdateApplication(c *gin.Context) {
|
||||
if req.BillingType != "" {
|
||||
app.BillingType = req.BillingType
|
||||
}
|
||||
oldLoginMode := app.LoginMode
|
||||
if req.LoginMode != "" {
|
||||
switch req.LoginMode {
|
||||
case "account", "card", "both":
|
||||
app.LoginMode = req.LoginMode
|
||||
}
|
||||
}
|
||||
if req.LoginModeEnforce != "" {
|
||||
switch req.LoginModeEnforce {
|
||||
case "off", "warn", "strict":
|
||||
app.LoginModeEnforce = req.LoginModeEnforce
|
||||
}
|
||||
}
|
||||
// 宽限期:显式传了按传的算(0 = 立即生效,顺带清掉截止时间);
|
||||
// 没传但刚切换了登录方式,自动给 7 天,避免存量用户被一刀切挡在门外。
|
||||
if req.LoginModeGraceDays != nil {
|
||||
if *req.LoginModeGraceDays > 0 {
|
||||
until := time.Now().AddDate(0, 0, *req.LoginModeGraceDays)
|
||||
app.LoginModeGraceUntil = &until
|
||||
} else {
|
||||
app.LoginModeGraceUntil = nil
|
||||
}
|
||||
} else if req.LoginMode != "" && req.LoginMode != oldLoginMode {
|
||||
until := time.Now().AddDate(0, 0, 7)
|
||||
app.LoginModeGraceUntil = &until
|
||||
}
|
||||
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 +991,7 @@ func handleCreateVersion(c *gin.Context) {
|
||||
Version: req.Version,
|
||||
Description: req.Description,
|
||||
FilePath: filePath,
|
||||
PublishStatus: "draft",
|
||||
PublishStatus: "draft",
|
||||
FileSize: fileSize,
|
||||
}
|
||||
|
||||
@@ -997,9 +1038,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 +1086,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 +1147,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 {
|
||||
@@ -1129,3 +1169,62 @@ func handleManualDeduct(c *gin.Context) {
|
||||
"message": "扣费成功",
|
||||
})
|
||||
}
|
||||
|
||||
// handleLoginModeImpact 登录方式切换的影响面。
|
||||
// 面板在把 login_mode 改成 account / card 之前先调这个,看清楚有多少主体会被挡住,
|
||||
// 再决定是「只记录」「开宽限期」还是「先跑迁移动作」。
|
||||
func handleLoginModeImpact(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
|
||||
var app model.Application
|
||||
if err := database.DB.Where("id = ? AND user_id = ?", c.Param("id"), userID).First(&app).Error; err != nil {
|
||||
response.Error(c, 404, "应用不存在")
|
||||
return
|
||||
}
|
||||
|
||||
var total, cardSubjects, cardWithEmail, onlyAccount int64
|
||||
database.DB.Model(&model.AppUser{}).Where("application_id = ?", app.ID).Count(&total)
|
||||
|
||||
// 卡密主体的密码是建主体时写进去的随机散列(卡密才是它的钥匙),所以不能靠 password 是否为空判断。
|
||||
// 这里用「有没有绑邮箱」来区分:绑了邮箱的卡密主体有自助设密码的通道,没绑的只能靠卡密登录。
|
||||
database.DB.Model(&model.AppUser{}).
|
||||
Where("application_id = ? AND subject_type = ?", app.ID, "card").
|
||||
Count(&cardSubjects)
|
||||
database.DB.Model(&model.AppUser{}).
|
||||
Where("application_id = ? AND subject_type = ?", app.ID, "card").
|
||||
Where("email IS NOT NULL AND email <> ''").
|
||||
Count(&cardWithEmail)
|
||||
onlyCard := cardSubjects - cardWithEmail
|
||||
if onlyCard < 0 {
|
||||
onlyCard = 0
|
||||
}
|
||||
|
||||
// 仅账号主体:有账号但没绑任何「登录卡」→ 切到 card 后他们登不进来
|
||||
database.DB.Model(&model.AppUser{}).
|
||||
Where("application_id = ? AND subject_type = ?", app.ID, "account").
|
||||
Where("NOT EXISTS (SELECT 1 FROM cards WHERE cards.subject_id = app_users.id AND cards.purpose = ? AND cards.deleted_at IS NULL)", "credential").
|
||||
Count(&onlyAccount)
|
||||
|
||||
mode := service.AppLoginMode(&app)
|
||||
graceDays := service.LoginModeGraceDaysLeft(&app)
|
||||
blocking := (mode == "account" && onlyCard > 0) || (mode == "card" && onlyAccount > 0)
|
||||
|
||||
// 切换成该模式后会被挡住的人数(给前端直接显示,不用自己算)
|
||||
blockedIfSwitch := onlyCard
|
||||
if mode == "card" {
|
||||
blockedIfSwitch = onlyAccount
|
||||
}
|
||||
|
||||
response.Success(c, gin.H{
|
||||
"login_mode": mode,
|
||||
"login_mode_enforce": service.AppLoginModeEnforce(&app),
|
||||
"login_mode_grace_days": graceDays,
|
||||
"total_subjects": total,
|
||||
"card_subjects": cardSubjects,
|
||||
"card_subjects_with_email": cardWithEmail,
|
||||
"only_card_subjects": onlyCard,
|
||||
"only_account_subjects": onlyAccount,
|
||||
"blocking": blocking,
|
||||
"blocked_if_switch": blockedIfSwitch,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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 ""
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -23,6 +23,7 @@ func SetupRoutes(r *gin.RouterGroup) {
|
||||
SetupAnnouncementRoutes(r)
|
||||
SetupVersionRoutes(r)
|
||||
SetupProtectRoutes(r)
|
||||
SetupSignProfileRoutes(r)
|
||||
SetupProfileRoutes(r)
|
||||
SetupEmailRoutes(r)
|
||||
SetupSystemSettingsRoutes(r)
|
||||
|
||||
@@ -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,4 +1,4 @@
|
||||
package admin
|
||||
package admin
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
@@ -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,4 +1,4 @@
|
||||
package admin
|
||||
package admin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
@@ -2,13 +2,17 @@ package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"verification-platform-backend/internal/database"
|
||||
"verification-platform-backend/internal/model"
|
||||
"verification-platform-backend/internal/service"
|
||||
"verification-platform-backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type FinanceRecordResponse struct {
|
||||
@@ -38,6 +42,7 @@ func SetupFinanceRoutes(r *gin.RouterGroup) {
|
||||
finance.GET("/recharge-records", handleGetRechargeRecords)
|
||||
finance.GET("/consumption-records", handleGetConsumptionRecords)
|
||||
finance.GET("/records", handleGetFinanceRecords)
|
||||
finance.GET("/export", handleExportFinanceRecords)
|
||||
finance.DELETE("/records/:id", handleDeleteFinanceRecord)
|
||||
finance.POST("/records/batch-delete", handleBatchDeleteFinanceRecords)
|
||||
}
|
||||
@@ -89,10 +94,20 @@ func handleGetFinanceStatistics(c *gin.Context) {
|
||||
Select("COALESCE(SUM(amount), 0)").
|
||||
Scan(&totalExpense)
|
||||
|
||||
// 本月流水条数:两个空数据分支都在返回它,正常分支以前漏了
|
||||
monthStart := time.Now().Format("2006-01") + "-01 00:00:00"
|
||||
var monthly int64
|
||||
database.DB.Model(&model.RechargeRecord{}).
|
||||
Where("user_id IN ? AND created_at >= ?", appUserIDs, monthStart).Count(&monthly)
|
||||
var monthlyCons int64
|
||||
database.DB.Model(&model.ConsumptionRecord{}).
|
||||
Where("user_id IN ? AND created_at >= ?", appUserIDs, monthStart).Count(&monthlyCons)
|
||||
|
||||
response.Success(c, gin.H{
|
||||
"total_income": totalIncome,
|
||||
"total_expense": totalExpense,
|
||||
"net_profit": totalIncome - totalExpense,
|
||||
"total_income": totalIncome,
|
||||
"total_expense": totalExpense,
|
||||
"net_profit": totalIncome - totalExpense,
|
||||
"monthly_transactions": monthly + monthlyCons,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -132,8 +147,7 @@ func handleGetRechargeRecords(c *gin.Context) {
|
||||
status := c.Query("status")
|
||||
startDate := c.Query("start_date")
|
||||
endDate := c.Query("end_date")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
page, pageSize := parsePageParams(c)
|
||||
|
||||
if search != "" {
|
||||
query = query.Where("order_no LIKE ? OR card_code LIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
@@ -202,8 +216,7 @@ func handleGetConsumptionRecords(c *gin.Context) {
|
||||
status := c.Query("status")
|
||||
startDate := c.Query("start_date")
|
||||
endDate := c.Query("end_date")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
page, pageSize := parsePageParams(c)
|
||||
|
||||
if search != "" {
|
||||
query = query.Where("order_no LIKE ? OR content LIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
@@ -238,308 +251,401 @@ func handleGetConsumptionRecords(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
func handleGetFinanceRecords(c *gin.Context) {
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
response.Error(c, 401, "未授权")
|
||||
return
|
||||
// 财务查询的公共筛选条件:records(列表)与 export(导出)共用,避免两边口径漂移。
|
||||
type financeFilter struct {
|
||||
appUserIDs []uint
|
||||
recordType string
|
||||
status string
|
||||
search string
|
||||
startDate string
|
||||
endDate string
|
||||
}
|
||||
|
||||
func (f financeFilter) wantRecharge() bool {
|
||||
return f.recordType == "" || f.recordType == "all" || f.recordType == "recharge"
|
||||
}
|
||||
|
||||
func (f financeFilter) wantConsumption() bool {
|
||||
return f.recordType == "" || f.recordType == "all" || f.recordType == "consumption"
|
||||
}
|
||||
|
||||
func (f financeFilter) recharge() *gorm.DB {
|
||||
q := database.DB.Model(&model.RechargeRecord{}).Where("user_id IN ?", f.appUserIDs)
|
||||
if f.search != "" {
|
||||
p := "%" + escapeLike(f.search) + "%"
|
||||
q = q.Where("order_no LIKE ? OR card_code LIKE ?", p, p)
|
||||
}
|
||||
if f.status != "" && f.status != "all" {
|
||||
q = q.Where("status = ?", f.status)
|
||||
}
|
||||
if f.startDate != "" {
|
||||
q = q.Where("created_at >= ?", f.startDate)
|
||||
}
|
||||
if f.endDate != "" {
|
||||
q = q.Where("created_at <= ?", f.endDate+" 23:59:59")
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func (f financeFilter) consumption() *gorm.DB {
|
||||
q := database.DB.Model(&model.ConsumptionRecord{}).Where("user_id IN ?", f.appUserIDs)
|
||||
if f.search != "" {
|
||||
p := "%" + escapeLike(f.search) + "%"
|
||||
q = q.Where("order_no LIKE ? OR content LIKE ?", p, p)
|
||||
}
|
||||
if f.status != "" && f.status != "all" {
|
||||
q = q.Where("status = ?", f.status)
|
||||
}
|
||||
if f.startDate != "" {
|
||||
q = q.Where("created_at >= ?", f.startDate)
|
||||
}
|
||||
if f.endDate != "" {
|
||||
q = q.Where("created_at <= ?", f.endDate+" 23:59:59")
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
// appUserIDsForFinance 取这批应用下的主体 id。
|
||||
//
|
||||
// 关键点:用 Unscoped() 把**已软删的主体**也算进来。
|
||||
// 否则后台删掉一个用户后,他历史上的充值和消费流水在面板里会凭空消失,
|
||||
// 累计收入也跟着变少——财务记录必须不受主体删除影响。
|
||||
func appUserIDsForFinance(appIDs []uint) []uint {
|
||||
var ids []uint
|
||||
if len(appIDs) == 0 {
|
||||
return ids
|
||||
}
|
||||
database.DB.Unscoped().Model(&model.AppUser{}).
|
||||
Where("application_id IN ?", appIDs).Pluck("id", &ids)
|
||||
return ids
|
||||
}
|
||||
|
||||
// preloadAppUserIncludingDeleted 同一个道理:主体已软删也要把名字读出来,方便对账。
|
||||
func preloadAppUserIncludingDeleted(db *gorm.DB) *gorm.DB {
|
||||
return db.Unscoped()
|
||||
}
|
||||
|
||||
// resolveFinanceScope 解析当前账号能看到的主体范围;application_id 只能是自己名下的应用。
|
||||
func resolveFinanceScope(c *gin.Context, appIDs []uint) (financeFilter, int, string) {
|
||||
scopeAppIDs := appIDs
|
||||
if v := c.Query("application_id"); v != "" && v != "all" {
|
||||
id, err := strconv.ParseUint(v, 10, 64)
|
||||
owned := false
|
||||
for _, a := range appIDs {
|
||||
if a == uint(id) {
|
||||
owned = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if err != nil || !owned {
|
||||
return financeFilter{}, 403, "无权查看该应用"
|
||||
}
|
||||
scopeAppIDs = []uint{uint(id)}
|
||||
}
|
||||
return financeFilter{
|
||||
appUserIDs: appUserIDsForFinance(scopeAppIDs),
|
||||
recordType: c.Query("type"),
|
||||
status: c.Query("status"),
|
||||
search: c.Query("search"),
|
||||
startDate: c.Query("start_date"),
|
||||
endDate: c.Query("end_date"),
|
||||
}, 0, ""
|
||||
}
|
||||
|
||||
// 财务汇总:走 SQL 聚合,不受分页影响
|
||||
func financeSummary(f financeFilter) gin.H {
|
||||
var rechargeAmount, consumptionAmount float64
|
||||
var rechargeCount, consumptionCount int64
|
||||
if f.wantRecharge() {
|
||||
f.recharge().Where("status = ?", "success").Select("COALESCE(SUM(amount), 0)").Scan(&rechargeAmount)
|
||||
f.recharge().Count(&rechargeCount)
|
||||
}
|
||||
if f.wantConsumption() {
|
||||
f.consumption().Where("status = ?", "success").Select("COALESCE(SUM(amount), 0)").Scan(&consumptionAmount)
|
||||
f.consumption().Count(&consumptionCount)
|
||||
}
|
||||
return gin.H{
|
||||
"recharge_amount": rechargeAmount,
|
||||
"recharge_count": rechargeCount,
|
||||
"consumption_amount": consumptionAmount,
|
||||
"consumption_count": consumptionCount,
|
||||
"profit": rechargeAmount - consumptionAmount,
|
||||
}
|
||||
}
|
||||
|
||||
// 财务记录:充值表 + 消费表合并成一条时间线。
|
||||
//
|
||||
// 之前的实现有两个硬伤:
|
||||
// 1. 两张表全量 Find 进内存再切片,数据一多就是内存炸弹,total 也只是 len();
|
||||
// 2. 前端不传分页参数 → 只拿回 10 条,而页面上的「充值总额/消费总额/利润」
|
||||
// 又是对这 10 条 reduce 出来的,于是库里 40 条只算 10 条。
|
||||
// 现在分页与汇总都放在 SQL 层:records 是当前页,summary 是全量(同样带筛选条件)。
|
||||
func handleGetFinanceRecords(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
|
||||
var appIDs []uint
|
||||
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
|
||||
|
||||
page, pageSize := parsePageParams(c)
|
||||
empty := func() {
|
||||
response.Success(c, gin.H{
|
||||
"records": []FinanceRecordResponse{},
|
||||
"total": 0,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
"total_page": 0,
|
||||
"summary": gin.H{
|
||||
"recharge_amount": 0,
|
||||
"recharge_count": 0,
|
||||
"consumption_amount": 0,
|
||||
"consumption_count": 0,
|
||||
"profit": 0,
|
||||
},
|
||||
})
|
||||
}
|
||||
if len(appIDs) == 0 {
|
||||
response.Success(c, gin.H{
|
||||
"recharge_records": []FinanceRecordResponse{},
|
||||
"consumption_records": []FinanceRecordResponse{},
|
||||
"total": 0,
|
||||
})
|
||||
empty()
|
||||
return
|
||||
}
|
||||
|
||||
var appUserIDs []uint
|
||||
database.DB.Model(&model.AppUser{}).Where("application_id IN ?", appIDs).Pluck("id", &appUserIDs)
|
||||
|
||||
if len(appUserIDs) == 0 {
|
||||
response.Success(c, gin.H{
|
||||
"recharge_records": []FinanceRecordResponse{},
|
||||
"consumption_records": []FinanceRecordResponse{},
|
||||
"total": 0,
|
||||
})
|
||||
f, code, msg := resolveFinanceScope(c, appIDs)
|
||||
if code != 0 {
|
||||
response.Error(c, code, msg)
|
||||
return
|
||||
}
|
||||
if len(f.appUserIDs) == 0 {
|
||||
empty()
|
||||
return
|
||||
}
|
||||
|
||||
page := c.DefaultQuery("page", "1")
|
||||
pageSize := c.DefaultQuery("page_size", "10")
|
||||
search := c.Query("search")
|
||||
recordType := c.Query("type")
|
||||
status := c.Query("status")
|
||||
startDate := c.Query("start_date")
|
||||
endDate := c.Query("end_date")
|
||||
summary := financeSummary(f)
|
||||
total := summary["recharge_count"].(int64) + summary["consumption_count"].(int64)
|
||||
|
||||
// 合并分页:两张表各取前 offset+pageSize 条,排序后再切当前页
|
||||
offset := (page - 1) * pageSize
|
||||
need := offset + pageSize
|
||||
if need > 1000 {
|
||||
need = 1000 // 深翻页保护:最多让前 1000 条参与合并
|
||||
}
|
||||
|
||||
var rechargeRecords []model.RechargeRecord
|
||||
rechargeQuery := database.DB.Model(&model.RechargeRecord{}).Preload("AppUser").Where("user_id IN ?", appUserIDs)
|
||||
|
||||
if search != "" {
|
||||
rechargeQuery = rechargeQuery.Where("order_no LIKE ? OR card_code LIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if recordType == "recharge" || recordType == "" || recordType == "all" {
|
||||
if status != "" && status != "all" {
|
||||
rechargeQuery = rechargeQuery.Where("status = ?", status)
|
||||
}
|
||||
if startDate != "" {
|
||||
rechargeQuery = rechargeQuery.Where("created_at >= ?", startDate)
|
||||
}
|
||||
if endDate != "" {
|
||||
rechargeQuery = rechargeQuery.Where("created_at <= ?", endDate+" 23:59:59")
|
||||
}
|
||||
if err := rechargeQuery.Order("created_at DESC").Find(&rechargeRecords).Error; err != nil {
|
||||
if f.wantRecharge() {
|
||||
if err := f.recharge().Preload("AppUser", preloadAppUserIncludingDeleted).
|
||||
Order("created_at DESC").Limit(need).Find(&rechargeRecords).Error; err != nil {
|
||||
response.Error(c, 500, "获取充值记录失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var consumptionRecords []model.ConsumptionRecord
|
||||
consumptionQuery := database.DB.Model(&model.ConsumptionRecord{}).Preload("AppUser").Where("user_id IN ?", appUserIDs)
|
||||
|
||||
if search != "" {
|
||||
consumptionQuery = consumptionQuery.Where("order_no LIKE ? OR content LIKE ?", "%"+search+"%", "%"+search+"%")
|
||||
}
|
||||
if recordType == "consumption" || recordType == "" || recordType == "all" {
|
||||
if status != "" && status != "all" {
|
||||
consumptionQuery = consumptionQuery.Where("status = ?", status)
|
||||
}
|
||||
if startDate != "" {
|
||||
consumptionQuery = consumptionQuery.Where("created_at >= ?", startDate)
|
||||
}
|
||||
if endDate != "" {
|
||||
consumptionQuery = consumptionQuery.Where("created_at <= ?", endDate+" 23:59:59")
|
||||
}
|
||||
if err := consumptionQuery.Order("created_at DESC").Find(&consumptionRecords).Error; err != nil {
|
||||
if f.wantConsumption() {
|
||||
if err := f.consumption().Preload("AppUser", preloadAppUserIncludingDeleted).
|
||||
Order("created_at DESC").Limit(need).Find(&consumptionRecords).Error; err != nil {
|
||||
response.Error(c, 500, "获取消费记录失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var allRecords []FinanceRecordResponse
|
||||
for _, r := range rechargeRecords {
|
||||
var user *struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
if r.AppUser != nil && r.AppUser.ID != 0 {
|
||||
user = &struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
}{
|
||||
ID: r.AppUser.ID,
|
||||
Username: r.AppUser.Username,
|
||||
Email: r.AppUser.Email,
|
||||
}
|
||||
}
|
||||
allRecords = append(allRecords, FinanceRecordResponse{
|
||||
ID: r.ID,
|
||||
OrderNo: r.OrderNo,
|
||||
Type: "recharge",
|
||||
UserID: r.UserID,
|
||||
AppID: r.AppUser.ApplicationID,
|
||||
Amount: r.Amount,
|
||||
Detail: r.CardCode,
|
||||
Status: r.Status,
|
||||
PaymentType: r.PaymentType,
|
||||
Remark: r.Remark,
|
||||
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
User: user,
|
||||
})
|
||||
type mergedRow struct {
|
||||
at time.Time
|
||||
resp FinanceRecordResponse
|
||||
}
|
||||
|
||||
for _, r := range consumptionRecords {
|
||||
var user *struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
if r.AppUser != nil && r.AppUser.ID != 0 {
|
||||
user = &struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
}{
|
||||
ID: r.AppUser.ID,
|
||||
Username: r.AppUser.Username,
|
||||
Email: r.AppUser.Email,
|
||||
}
|
||||
}
|
||||
allRecords = append(allRecords, FinanceRecordResponse{
|
||||
ID: r.ID,
|
||||
OrderNo: r.OrderNo,
|
||||
Type: "consumption",
|
||||
UserID: r.UserID,
|
||||
AppID: r.AppUser.ApplicationID,
|
||||
Amount: r.Amount,
|
||||
Detail: r.Content,
|
||||
Status: r.Status,
|
||||
PaymentType: r.PaymentType,
|
||||
Remark: r.Remark,
|
||||
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
User: user,
|
||||
})
|
||||
merged := make([]mergedRow, 0, len(rechargeRecords)+len(consumptionRecords))
|
||||
for i := range rechargeRecords {
|
||||
merged = append(merged, mergedRow{rechargeRecords[i].CreatedAt, rechargeToFinanceResponse(&rechargeRecords[i])})
|
||||
}
|
||||
|
||||
total := len(allRecords)
|
||||
start := 0
|
||||
end := total
|
||||
if p, err := parseInt(page); err == nil && p > 0 {
|
||||
if ps, err := parseInt(pageSize); err == nil && ps > 0 {
|
||||
start = (p - 1) * ps
|
||||
end = start + ps
|
||||
if start > total {
|
||||
start = total
|
||||
}
|
||||
if end > total {
|
||||
end = total
|
||||
}
|
||||
}
|
||||
for i := range consumptionRecords {
|
||||
merged = append(merged, mergedRow{consumptionRecords[i].CreatedAt, consumptionToFinanceResponse(&consumptionRecords[i])})
|
||||
}
|
||||
sort.SliceStable(merged, func(i, j int) bool { return merged[i].at.After(merged[j].at) })
|
||||
|
||||
if start > end {
|
||||
start = end
|
||||
startIdx, endIdx := offset, offset+pageSize
|
||||
if startIdx > len(merged) {
|
||||
startIdx = len(merged)
|
||||
}
|
||||
if endIdx > len(merged) {
|
||||
endIdx = len(merged)
|
||||
}
|
||||
pageRows := make([]FinanceRecordResponse, 0, endIdx-startIdx)
|
||||
for _, r := range merged[startIdx:endIdx] {
|
||||
pageRows = append(pageRows, r.resp)
|
||||
}
|
||||
|
||||
response.Success(c, gin.H{
|
||||
"records": allRecords[start:end],
|
||||
"total": total,
|
||||
"records": pageRows,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
"total_page": (total + int64(pageSize) - 1) / int64(pageSize),
|
||||
"summary": summary,
|
||||
})
|
||||
}
|
||||
|
||||
// 财务流水导出(CSV)。删除接口被封掉之后,需要清理/对账就走这里。
|
||||
func handleExportFinanceRecords(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
|
||||
var appIDs []uint
|
||||
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
|
||||
if len(appIDs) == 0 {
|
||||
response.Error(c, 404, "没有可导出的记录")
|
||||
return
|
||||
}
|
||||
|
||||
f, code, msg := resolveFinanceScope(c, appIDs)
|
||||
if code != 0 {
|
||||
response.Error(c, code, msg)
|
||||
return
|
||||
}
|
||||
if len(f.appUserIDs) == 0 {
|
||||
response.Error(c, 404, "没有可导出的记录")
|
||||
return
|
||||
}
|
||||
|
||||
const exportLimit = 100000
|
||||
var rechargeRecords []model.RechargeRecord
|
||||
if f.wantRecharge() {
|
||||
if err := f.recharge().Preload("AppUser", preloadAppUserIncludingDeleted).
|
||||
Order("created_at DESC").Limit(exportLimit).Find(&rechargeRecords).Error; err != nil {
|
||||
response.Error(c, 500, "导出失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
var consumptionRecords []model.ConsumptionRecord
|
||||
if f.wantConsumption() {
|
||||
if err := f.consumption().Preload("AppUser", preloadAppUserIncludingDeleted).
|
||||
Order("created_at DESC").Limit(exportLimit).Find(&consumptionRecords).Error; err != nil {
|
||||
response.Error(c, 500, "导出失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
type mergedRow struct {
|
||||
at time.Time
|
||||
resp FinanceRecordResponse
|
||||
}
|
||||
merged := make([]mergedRow, 0, len(rechargeRecords)+len(consumptionRecords))
|
||||
for i := range rechargeRecords {
|
||||
merged = append(merged, mergedRow{rechargeRecords[i].CreatedAt, rechargeToFinanceResponse(&rechargeRecords[i])})
|
||||
}
|
||||
for i := range consumptionRecords {
|
||||
merged = append(merged, mergedRow{consumptionRecords[i].CreatedAt, consumptionToFinanceResponse(&consumptionRecords[i])})
|
||||
}
|
||||
sort.SliceStable(merged, func(i, j int) bool { return merged[i].at.After(merged[j].at) })
|
||||
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=finance_%s.csv", time.Now().Format("20060102-150405")))
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("\xEF\xBB\xBF") // BOM,Excel 打开不乱码
|
||||
b.WriteString("类型,订单号,金额,用户,详情,状态,支付方式,备注,应用ID,时间\n")
|
||||
for _, r := range merged {
|
||||
typ := "充值"
|
||||
if r.resp.Type == "consumption" {
|
||||
typ = "消费"
|
||||
}
|
||||
user := ""
|
||||
if r.resp.User != nil {
|
||||
user = r.resp.User.Username
|
||||
}
|
||||
b.WriteString(fmt.Sprintf("%s,%s,%.2f,%s,%s,%s,%s,%s,%d,%s\n",
|
||||
typ, csvField(r.resp.OrderNo), r.resp.Amount, csvField(user), csvField(r.resp.Detail),
|
||||
csvField(r.resp.Status), csvField(r.resp.PaymentType), csvField(r.resp.Remark),
|
||||
r.resp.AppID, r.resp.CreatedAt))
|
||||
}
|
||||
c.String(200, b.String())
|
||||
}
|
||||
|
||||
// csvField 简单转义:含逗号/引号/换行就加引号
|
||||
func csvField(s string) string {
|
||||
if strings.ContainsAny(s, ",\"\n") {
|
||||
return "\"" + strings.ReplaceAll(s, "\"", "\"\"") + "\""
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// 主体信息:AppUser 为空(主体被删/记录user_id悬空)时返回 nil,
|
||||
// 不要像以前那样直接解引用 r.AppUser.ApplicationID —— 那是 nil 指针 panic。
|
||||
func financeUserBrief(u *model.AppUser) *struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
} {
|
||||
if u == nil || u.ID == 0 {
|
||||
return nil
|
||||
}
|
||||
return &struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
}{ID: u.ID, Username: u.Username, Email: u.Email}
|
||||
}
|
||||
|
||||
func rechargeToFinanceResponse(r *model.RechargeRecord) FinanceRecordResponse {
|
||||
appID := uint(0)
|
||||
if r.AppUser != nil {
|
||||
appID = r.AppUser.ApplicationID
|
||||
}
|
||||
return FinanceRecordResponse{
|
||||
ID: r.ID,
|
||||
OrderNo: r.OrderNo,
|
||||
Type: "recharge",
|
||||
UserID: r.UserID,
|
||||
AppID: appID,
|
||||
Amount: r.Amount,
|
||||
Detail: r.CardCode,
|
||||
Status: r.Status,
|
||||
PaymentType: r.PaymentType,
|
||||
Remark: r.Remark,
|
||||
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
User: financeUserBrief(r.AppUser),
|
||||
}
|
||||
}
|
||||
|
||||
func consumptionToFinanceResponse(r *model.ConsumptionRecord) FinanceRecordResponse {
|
||||
appID := r.ApplicationID
|
||||
if r.AppUser != nil && r.AppUser.ApplicationID != 0 {
|
||||
appID = r.AppUser.ApplicationID
|
||||
}
|
||||
return FinanceRecordResponse{
|
||||
ID: r.ID,
|
||||
OrderNo: r.OrderNo,
|
||||
Type: "consumption",
|
||||
UserID: r.UserID,
|
||||
AppID: appID,
|
||||
Amount: r.Amount,
|
||||
Detail: r.Content,
|
||||
Status: r.Status,
|
||||
PaymentType: r.PaymentType,
|
||||
Remark: r.Remark,
|
||||
CreatedAt: r.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
User: financeUserBrief(r.AppUser),
|
||||
}
|
||||
}
|
||||
|
||||
func parseInt(s string) (int, error) {
|
||||
var result int
|
||||
_, err := fmt.Sscanf(s, "%d", &result)
|
||||
return result, err
|
||||
}
|
||||
|
||||
// 财务流水是审计凭证:删掉之后「流水没了、余额还在」,账面和余额永久对不上,
|
||||
// 而且删掉的记录(即使软删)在统计里也消失了,事后没法对账。
|
||||
// 所以这里直接封掉删除,要清理/对账一律走 /finance/export 导出。
|
||||
// 老前端仍会调到这两个接口,返回可读的 403,而不是静默失败。
|
||||
const financeDeleteForbidden = "财务流水是审计凭证,不支持删除;需要清理或对账请使用导出"
|
||||
|
||||
func handleDeleteFinanceRecord(c *gin.Context) {
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
response.Error(c, 401, "未授权")
|
||||
return
|
||||
}
|
||||
|
||||
recordID := c.Param("id")
|
||||
recordType := c.Query("type")
|
||||
|
||||
var appIDs []uint
|
||||
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
|
||||
if len(appIDs) == 0 {
|
||||
response.Error(c, 404, "记录不存在")
|
||||
return
|
||||
}
|
||||
|
||||
var appUserIDs []uint
|
||||
database.DB.Model(&model.AppUser{}).Where("application_id IN ?", appIDs).Pluck("id", &appUserIDs)
|
||||
if len(appUserIDs) == 0 {
|
||||
response.Error(c, 404, "记录不存在")
|
||||
return
|
||||
}
|
||||
|
||||
var deletedType string
|
||||
var deletedAmount float64
|
||||
|
||||
if recordType == "recharge" {
|
||||
var record model.RechargeRecord
|
||||
if err := database.DB.Where("id = ? AND user_id IN ?", recordID, appUserIDs).First(&record).Error; err != nil {
|
||||
response.Error(c, 404, "记录不存在")
|
||||
return
|
||||
}
|
||||
if err := database.DB.Delete(&record).Error; err != nil {
|
||||
response.Error(c, 500, "删除失败")
|
||||
return
|
||||
}
|
||||
deletedType = "充值记录"
|
||||
deletedAmount = record.Amount
|
||||
} else if recordType == "consumption" {
|
||||
var record model.ConsumptionRecord
|
||||
if err := database.DB.Where("id = ? AND user_id IN ?", recordID, appUserIDs).First(&record).Error; err != nil {
|
||||
response.Error(c, 404, "记录不存在")
|
||||
return
|
||||
}
|
||||
if err := database.DB.Delete(&record).Error; err != nil {
|
||||
response.Error(c, 500, "删除失败")
|
||||
return
|
||||
}
|
||||
deletedType = "消费记录"
|
||||
deletedAmount = record.Amount
|
||||
} else {
|
||||
var rechargeRecord model.RechargeRecord
|
||||
var consumptionRecord model.ConsumptionRecord
|
||||
|
||||
if err := database.DB.Where("id = ? AND user_id IN ?", recordID, appUserIDs).First(&rechargeRecord).Error; err == nil {
|
||||
database.DB.Delete(&rechargeRecord)
|
||||
deletedType = "充值记录"
|
||||
deletedAmount = rechargeRecord.Amount
|
||||
service.LogOperation(c, "delete", "finance_record", nil, fmt.Sprintf("删除%s: %.2f", deletedType, deletedAmount), nil)
|
||||
response.Success(c, nil)
|
||||
return
|
||||
}
|
||||
|
||||
if err := database.DB.Where("id = ? AND user_id IN ?", recordID, appUserIDs).First(&consumptionRecord).Error; err == nil {
|
||||
database.DB.Delete(&consumptionRecord)
|
||||
deletedType = "消费记录"
|
||||
deletedAmount = consumptionRecord.Amount
|
||||
service.LogOperation(c, "delete", "finance_record", nil, fmt.Sprintf("删除%s: %.2f", deletedType, deletedAmount), nil)
|
||||
response.Success(c, nil)
|
||||
return
|
||||
}
|
||||
|
||||
response.Error(c, 404, "记录不存在")
|
||||
return
|
||||
}
|
||||
|
||||
service.LogOperation(c, "delete", "finance_record", nil, fmt.Sprintf("删除%s: %.2f", deletedType, deletedAmount), nil)
|
||||
|
||||
response.Success(c, nil)
|
||||
service.LogOperation(c, "delete_blocked", "finance_record", nil,
|
||||
"尝试删除财务记录(已被拒绝): id="+c.Param("id")+" type="+c.Query("type"), nil)
|
||||
response.Error(c, 403, financeDeleteForbidden)
|
||||
}
|
||||
|
||||
func handleBatchDeleteFinanceRecords(c *gin.Context) {
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
response.Error(c, 401, "未授权")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
IDs []uint `json:"ids"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.Error(c, 400, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.IDs) == 0 {
|
||||
response.Error(c, 400, "请选择要删除的记录")
|
||||
return
|
||||
}
|
||||
|
||||
var appIDs []uint
|
||||
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
|
||||
if len(appIDs) == 0 {
|
||||
response.Error(c, 404, "记录不存在")
|
||||
return
|
||||
}
|
||||
|
||||
var appUserIDs []uint
|
||||
database.DB.Model(&model.AppUser{}).Where("application_id IN ?", appIDs).Pluck("id", &appUserIDs)
|
||||
if len(appUserIDs) == 0 {
|
||||
response.Error(c, 404, "记录不存在")
|
||||
return
|
||||
}
|
||||
|
||||
database.DB.Where("id IN ? AND user_id IN ?", req.IDs, appUserIDs).Delete(&model.RechargeRecord{})
|
||||
database.DB.Where("id IN ? AND user_id IN ?", req.IDs, appUserIDs).Delete(&model.ConsumptionRecord{})
|
||||
|
||||
service.LogOperation(c, "batch_delete", "finance_record", nil, fmt.Sprintf("批量删除财务记录: %d条", len(req.IDs)), nil)
|
||||
|
||||
response.Success(c, gin.H{"deleted": len(req.IDs)})
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
service.LogOperation(c, "delete_blocked", "finance_record", nil,
|
||||
fmt.Sprintf("尝试批量删除财务记录(已被拒绝): %d 条", len(req.IDs)), nil)
|
||||
response.Error(c, 403, financeDeleteForbidden)
|
||||
}
|
||||
|
||||
@@ -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)})
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"verification-platform-backend/internal/database"
|
||||
"verification-platform-backend/internal/model"
|
||||
"verification-platform-backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func SetupLogRoutes(r *gin.RouterGroup) {
|
||||
@@ -22,8 +22,7 @@ func handleGetLogs(c *gin.Context) {
|
||||
var appIDs []uint
|
||||
database.DB.Model(&model.Application{}).Where("user_id = ?", userID).Pluck("id", &appIDs)
|
||||
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
page, pageSize := parsePageParams(c)
|
||||
logType := c.Query("type")
|
||||
status := c.Query("status")
|
||||
applicationID := c.Query("application_id")
|
||||
@@ -63,15 +62,48 @@ func handleGetLogs(c *gin.Context) {
|
||||
}
|
||||
|
||||
if search != "" {
|
||||
query = query.Where("action LIKE ? OR details LIKE ? OR resource LIKE ?", "%"+search+"%", "%"+search+"%", "%"+search+"%")
|
||||
p := "%" + escapeLike(search) + "%"
|
||||
query = query.Where("action LIKE ? OR details LIKE ? OR resource LIKE ?", p, p, p)
|
||||
}
|
||||
|
||||
query.Count(&total)
|
||||
|
||||
// 三个统计数字必须和列表同源(同一个 Log 表 + 同一套筛选),
|
||||
// 否则会出现「列表 0 条、顶部写着成功 128」这种对不上的情况。
|
||||
// 以前用的是 ApiUsage 表,而且完全不带筛选条件。
|
||||
baseQuery := func() *gorm.DB {
|
||||
q := database.DB.Model(&model.Log{})
|
||||
if len(appIDs) > 0 {
|
||||
q = q.Where("application_id IN ? OR user_id = ?", appIDs, userID)
|
||||
} else {
|
||||
q = q.Where("user_id = ?", userID)
|
||||
}
|
||||
if logType != "" && logType != "all" {
|
||||
q = q.Where("log_type = ?", logType)
|
||||
}
|
||||
if status != "" && status != "all" {
|
||||
q = q.Where("status = ?", status)
|
||||
}
|
||||
if applicationID != "" && applicationID != "all" {
|
||||
q = q.Where("application_id = ?", applicationID)
|
||||
}
|
||||
if startDate != "" {
|
||||
q = q.Where("created_at >= ?", startDate+" 00:00:00")
|
||||
}
|
||||
if endDate != "" {
|
||||
q = q.Where("created_at <= ?", endDate+" 23:59:59")
|
||||
}
|
||||
if search != "" {
|
||||
p := "%" + escapeLike(search) + "%"
|
||||
q = q.Where("action LIKE ? OR details LIKE ? OR resource LIKE ?", p, p, p)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
var successCount, failedCount, operationCount int64
|
||||
database.DB.Model(&model.ApiUsage{}).Where("application_id IN ? OR user_id = ?", appIDs, userID).Where("status = ?", "success").Count(&successCount)
|
||||
database.DB.Model(&model.ApiUsage{}).Where("application_id IN ? OR user_id = ?", appIDs, userID).Where("status = ?", "failed").Count(&failedCount)
|
||||
database.DB.Model(&model.ApiUsage{}).Where("application_id IN ? OR user_id = ?", appIDs, userID).Where("log_type = ?", "operation").Count(&operationCount)
|
||||
baseQuery().Where("status = ?", "success").Count(&successCount)
|
||||
baseQuery().Where("status = ?", "failed").Count(&failedCount)
|
||||
baseQuery().Where("log_type = ?", "operation").Count(&operationCount)
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
if err := query.Preload("User").Preload("Application").Preload("AppUser").Order("created_at DESC").Offset(offset).Limit(pageSize).Find(&logs).Error; err != nil {
|
||||
@@ -80,13 +112,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,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
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 分页参数的统一入口。
|
||||
//
|
||||
// 之前每个 handler 都自己 strconv.Atoi 然后用,没有下限也没有上限:
|
||||
// - page=0 / 负数 → offset 变负数,MySQL 里直接报错或结果诡异
|
||||
// - page_size=-1 → GORM 的 Limit(-1) 等于「不加 LIMIT」,一次把全表拉出来
|
||||
// - page_size=100000 → 同样等于导出全表
|
||||
// 所以统一在这里夹紧:page >= 1,pageSize ∈ [1, maxPageSize],默认 20。
|
||||
const (
|
||||
defaultPageSize = 20
|
||||
maxPageSize = 200
|
||||
)
|
||||
|
||||
func parsePageParams(c *gin.Context) (page, pageSize int) {
|
||||
page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
if err != nil || page < 1 {
|
||||
page = 1
|
||||
}
|
||||
pageSize, err = strconv.Atoi(c.DefaultQuery("page_size", strconv.Itoa(defaultPageSize)))
|
||||
if err != nil || pageSize < 1 {
|
||||
pageSize = defaultPageSize
|
||||
}
|
||||
if pageSize > maxPageSize {
|
||||
pageSize = maxPageSize
|
||||
}
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
// escapeLike 转义 LIKE 里的通配符:用户搜 "100%" 时不该变成"匹配一切"。
|
||||
// MySQL / SQLite 默认转义符都是反斜杠。
|
||||
func escapeLike(s string) string {
|
||||
s = strings.ReplaceAll(s, `\`, `\\`)
|
||||
s = strings.ReplaceAll(s, "%", `\%`)
|
||||
s = strings.ReplaceAll(s, "_", `\_`)
|
||||
return s
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,9 @@ import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"verification-platform-backend/internal/config"
|
||||
"verification-platform-backend/internal/database"
|
||||
"verification-platform-backend/internal/model"
|
||||
"verification-platform-backend/internal/protect"
|
||||
@@ -30,8 +32,14 @@ func SetupProtectRoutes(r *gin.RouterGroup) {
|
||||
}
|
||||
}
|
||||
|
||||
// baseURL 从请求推断站点根地址(面板/应用共用同一域名)
|
||||
func baseURL(c *gin.Context) string {
|
||||
// baseURL 推断站点根地址(面板/应用共用同一域名)。
|
||||
//
|
||||
// 这里踩过一次真实的坑:AcePanel 默认的反代模板写的是 `proxy_set_header Host $proxy_host`,
|
||||
// 于是后端看到的 Host 是 `127.0.0.1:9998`,打包出来的每个客户端都会把
|
||||
// `https://127.0.0.1:9998/api/v1/app/<key>/login` 写进壳 cfg —— 到了客户机上根本连不上。
|
||||
// 所以:优先 X-Forwarded-Host,其次(配置里的站点地址),最后才是请求 Host;
|
||||
// 一旦推断出来是本机/内网地址,宁可让加壳任务报错,也不要产出一个连不上服务器的产物。
|
||||
func baseURL(c *gin.Context) (string, error) {
|
||||
scheme := c.GetHeader("X-Forwarded-Proto")
|
||||
if scheme == "" {
|
||||
if c.Request.TLS != nil {
|
||||
@@ -40,11 +48,48 @@ func baseURL(c *gin.Context) string {
|
||||
scheme = "http"
|
||||
}
|
||||
}
|
||||
host := c.GetHeader("X-Forwarded-Host")
|
||||
|
||||
// 反代应当带上 X-Forwarded-Host;它才是用户浏览器里那个域名
|
||||
host := strings.TrimSpace(c.GetHeader("X-Forwarded-Host"))
|
||||
if host == "" {
|
||||
host = c.Request.Host
|
||||
host = strings.TrimSpace(c.Request.Host)
|
||||
}
|
||||
return fmt.Sprintf("%s://%s", scheme, host)
|
||||
|
||||
// 站点地址可以在 config.yaml 里显式指定(app.public_url),配了就优先用
|
||||
if pub := strings.TrimRight(config.GetString("app.public_url"), "/"); pub != "" {
|
||||
return pub, nil
|
||||
}
|
||||
|
||||
if host == "" || isInternalHost(host) {
|
||||
return "", fmt.Errorf("无法推断站点地址(反向代理没有传 X-Forwarded-Host,Host 为 %q),请在 config.yaml 配置 app.public_url", host)
|
||||
}
|
||||
return fmt.Sprintf("%s://%s", scheme, host), nil
|
||||
}
|
||||
|
||||
// isInternalHost 判断 host 是不是只在本机/内网有意义(127.x、localhost、内网网段、无域名端口等)
|
||||
func isInternalHost(host string) bool {
|
||||
h := host
|
||||
if i := strings.LastIndex(h, ":"); i > 0 && !strings.Contains(h[i:], "]") {
|
||||
h = h[:i] // 去掉端口
|
||||
}
|
||||
h = strings.ToLower(strings.Trim(h, "[]"))
|
||||
switch {
|
||||
case h == "", h == "localhost", h == "0.0.0.0", h == "::1":
|
||||
return true
|
||||
case strings.HasPrefix(h, "127."), strings.HasPrefix(h, "10."), strings.HasPrefix(h, "192.168."):
|
||||
return true
|
||||
case strings.HasPrefix(h, "172."):
|
||||
// 172.16.0.0/12
|
||||
parts := strings.Split(h, ".")
|
||||
if len(parts) == 4 {
|
||||
if n, err := strconv.Atoi(parts[1]); err == nil && n >= 16 && n <= 31 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case strings.HasPrefix(h, "169.254."):
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HandleCreateProtectTask 上传原始程序 → 建任务 → 异步加壳
|
||||
@@ -69,8 +114,11 @@ func HandleCreateProtectTask(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
name := filepath.Base(fh.Filename)
|
||||
if !strings.HasSuffix(strings.ToLower(name), ".exe") {
|
||||
response.ParamError(c, "目前只支持 Windows PE(.exe)")
|
||||
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 {
|
||||
@@ -89,16 +137,160 @@ func HandleCreateProtectTask(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
task, err := protect.CreateAndRun(&app, userID, name, data, baseURL(c))
|
||||
// 可选:指定重签证书(必须是自己的、平台与文件类型匹配的资产)。
|
||||
// 校验放在建任务之前,并且把证书直接交给 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
|
||||
}
|
||||
siteURL, err := baseURL(c)
|
||||
if err != nil {
|
||||
response.Error(c, 400, err.Error())
|
||||
return
|
||||
}
|
||||
task, err := protect.CreateAndRunThemedVer(&app, userID, name, data, siteURL, signProfileID, certIdentity, theme, programVer)
|
||||
if err != nil {
|
||||
response.ParamError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.SuccessWithMessage(c, "任务已创建,正在加壳", gin.H{
|
||||
|
||||
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 任务列表
|
||||
@@ -226,3 +418,15 @@ func HandleDeleteProtectTask(c *gin.Context) {
|
||||
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,80 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestIsInternalHost(t *testing.T) {
|
||||
cases := map[string]bool{
|
||||
"127.0.0.1:9998": true,
|
||||
"127.0.0.1": true,
|
||||
"localhost:8080": true,
|
||||
"localhost": true,
|
||||
"10.0.0.5": true,
|
||||
"192.168.1.10:443": true,
|
||||
"172.16.0.1": true,
|
||||
"172.31.255.1:8080": true,
|
||||
"169.254.1.1": true,
|
||||
"": true,
|
||||
"[::1]:8080": true,
|
||||
"0.0.0.0:8080": true,
|
||||
"v.viaeon.com": false,
|
||||
"v.viaeon.com:443": false,
|
||||
"172.32.0.1": false, // 不在 172.16/12 里
|
||||
"verify.example.com": false,
|
||||
"8.8.8.8": false,
|
||||
}
|
||||
for host, want := range cases {
|
||||
if got := isInternalHost(host); got != want {
|
||||
t.Fatalf("isInternalHost(%q) = %v, want %v", host, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newCtx(host, xfh, proto string) *gin.Context {
|
||||
gin.SetMode(gin.TestMode)
|
||||
req := httptest.NewRequest("POST", "/", nil)
|
||||
req.Host = host
|
||||
if xfh != "" {
|
||||
req.Header.Set("X-Forwarded-Host", xfh)
|
||||
}
|
||||
if proto != "" {
|
||||
req.Header.Set("X-Forwarded-Proto", proto)
|
||||
}
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = req
|
||||
return c
|
||||
}
|
||||
|
||||
// 反代把 Host 改写成 127.0.0.1 时必须报错,绝不能把内网地址打进产物
|
||||
func TestBaseURLRejectsLoopback(t *testing.T) {
|
||||
u, err := baseURL(newCtx("127.0.0.1:9998", "", "https"))
|
||||
if err == nil {
|
||||
t.Fatalf("期望报错,实际返回 %q", u)
|
||||
}
|
||||
}
|
||||
|
||||
// 反代带了 X-Forwarded-Host 就用它
|
||||
func TestBaseURLPrefersForwardedHost(t *testing.T) {
|
||||
u, err := baseURL(newCtx("127.0.0.1:9998", "v.viaeon.com", "https"))
|
||||
if err != nil {
|
||||
t.Fatalf("期望成功,实际 %v", err)
|
||||
}
|
||||
if want := "https://v.viaeon.com"; u != want {
|
||||
t.Fatalf("baseURL = %q, want %q", u, want)
|
||||
}
|
||||
}
|
||||
|
||||
// 直连(无反代)时用请求 Host
|
||||
func TestBaseURLUsesRequestHost(t *testing.T) {
|
||||
u, err := baseURL(newCtx("v.viaeon.com", "", "https"))
|
||||
if err != nil {
|
||||
t.Fatalf("期望成功,实际 %v", err)
|
||||
}
|
||||
if want := "https://v.viaeon.com"; u != want {
|
||||
t.Fatalf("baseURL = %q, want %q", u, want)
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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,4 +1,4 @@
|
||||
package admin
|
||||
package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
response.Error(c, 400, "该应用未开启卡密绑定邮箱")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var smtpConfig model.AppSMTPConfig
|
||||
@@ -198,17 +207,30 @@ func handleAppRegister(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 卡密直登模式下注册出来的账号没有登录入口,直接挡掉(宽限期内放行,和登录 gate 保持一致)
|
||||
if service.AppLoginMode(appModel) == "card" && service.AppLoginModeEnforce(appModel) == "strict" && service.LoginModeGraceDaysLeft(appModel) == 0 {
|
||||
service.LogVerification(c, &appModel.ID, nil, "register_blocked",
|
||||
"注册被登录方式策略拦截: mode=card", "", fmt.Errorf("该应用仅支持卡密登录"))
|
||||
c.JSON(403, gin.H{
|
||||
"code": 403,
|
||||
"message": "该应用使用卡密登录,无需注册",
|
||||
"error_code": "LOGIN_MODE_DISABLED",
|
||||
"data": gin.H{"login_mode": "card", "allowed": []string{"card"}},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
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 +316,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 +392,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 +439,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,28 +451,110 @@ 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
|
||||
// 登录方式开关(login_mode):这是应用级登录策略,客户端界面只是体验,判定必须在服务端。
|
||||
// 位置故意放在查询主体、写设备绑定、记失败次数之前——被策略拒绝的请求不产生任何副作用。
|
||||
loginDeprecated := false
|
||||
graceDaysLeft := 0
|
||||
if !service.LoginTypeAllowedByMode(appModel, req.LoginType) {
|
||||
mode := service.AppLoginMode(appModel)
|
||||
switch service.AppLoginModeEnforce(appModel) {
|
||||
case "strict":
|
||||
if days := service.LoginModeGraceDaysLeft(appModel); days > 0 {
|
||||
// 宽限期内旧凭证仍然可用,只在响应里提醒用户尽快换钥匙
|
||||
loginDeprecated, graceDaysLeft = true, days
|
||||
log.Printf("[INFO] login_mode grace: app=%s mode=%s login_type=%s days_left=%d", appKey, mode, req.LoginType, days)
|
||||
} else {
|
||||
service.LogVerification(c, &appModel.ID, nil, "login_mode_blocked",
|
||||
"登录被登录方式策略拦截: mode="+mode+" login_type="+req.LoginType, req.DeviceID,
|
||||
fmt.Errorf("该应用仅允许: %s", strings.Join(service.AllowedLoginTypes(mode), ",")))
|
||||
c.JSON(403, gin.H{
|
||||
"code": 403,
|
||||
"message": service.LoginModeBlockMessage(mode),
|
||||
"error_code": "LOGIN_MODE_DISABLED",
|
||||
"data": gin.H{
|
||||
"login_mode": mode,
|
||||
"allowed": service.AllowedLoginTypes(mode),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
case "warn":
|
||||
log.Printf("[WARN] login_mode(warn-only) 会拦截但已放行: app=%s mode=%s login_type=%s", appKey, mode, req.LoginType)
|
||||
_ = service.LogVerification(c, &appModel.ID, nil, "login_mode_blocked",
|
||||
"[warn-only] 登录方式与策略不符,已放行: mode="+mode+" login_type="+req.LoginType, req.DeviceID, nil)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
service.LogVerification(c, &appModel.ID, &user.ID, "login_blocked", "登录被拦截: "+reason, req.DeviceID, fmt.Errorf(reason))
|
||||
@@ -500,7 +611,7 @@ func handleAppLogin(c *gin.Context) {
|
||||
|
||||
now := time.Now()
|
||||
deviceType := getDeviceType(c, req.DeviceType)
|
||||
|
||||
|
||||
deviceName := req.DeviceName
|
||||
if deviceName == "" {
|
||||
deviceName = req.DeviceID
|
||||
@@ -520,10 +631,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 +644,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 +668,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 +681,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 +710,7 @@ func handleAppLogin(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
device = model.UserDevice{
|
||||
UserID: user.ID,
|
||||
ApplicationID: appModel.ID,
|
||||
@@ -629,10 +740,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 +755,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 +770,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,
|
||||
@@ -718,6 +829,14 @@ func handleAppLogin(c *gin.Context) {
|
||||
loginData["balance"] = user.Balance
|
||||
}
|
||||
|
||||
// 宽限期内的旧凭证登录:明确告诉壳/用户还剩几天,好引导换钥匙
|
||||
if loginDeprecated {
|
||||
loginData["deprecated_login"] = true
|
||||
loginData["grace_days_left"] = graceDaysLeft
|
||||
loginData["login_mode"] = service.AppLoginMode(appModel)
|
||||
loginData["allowed_login_types"] = service.AllowedLoginTypes(service.AppLoginMode(appModel))
|
||||
}
|
||||
|
||||
response.SuccessWithMessage(c, "登录成功", loginData)
|
||||
}
|
||||
|
||||
@@ -789,6 +908,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 {
|
||||
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 +1265,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, "参数错误")
|
||||
|
||||
@@ -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": "解绑成功"})
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
|
||||
@@ -242,6 +242,22 @@ 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": service.AppLoginMode(&app),
|
||||
"login_mode_enforce": service.AppLoginModeEnforce(&app),
|
||||
"login_mode_grace_days": service.LoginModeGraceDaysLeft(&app),
|
||||
"allowed_login_types": service.AllowedLoginTypes(service.AppLoginMode(&app)),
|
||||
"card_login_bind_device": app.CardLoginBindDevice,
|
||||
"card_login_allow_password": app.CardLoginAllowPassword,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -549,7 +549,7 @@ func registerWriteTools(s *mcpserver.MCPServer) {
|
||||
|
||||
// ---------- 给版本加壳 ----------
|
||||
s.AddTool(sdk.NewTool("verify_protect_version",
|
||||
sdk.WithDescription("给某个版本的入口 exe 注入验证壳(改入口 + 内存加载壳 DLL + 双层 CRC32),产出单文件、可直接分发的 exe。同步执行,返回产物路径/大小/CRC。dry_run=true 只报告将用哪个文件加壳。"),
|
||||
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")),
|
||||
@@ -586,10 +586,14 @@ func registerWriteTools(s *mcpserver.MCPServer) {
|
||||
if err != nil {
|
||||
return sdk.NewToolResultErrorFromErr("读取入口文件失败", err), nil
|
||||
}
|
||||
arch, err := protect.DetectArch(data)
|
||||
if err != nil {
|
||||
return sdk.NewToolResultError("入口文件不是有效 PE: " + err.Error()), 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{
|
||||
@@ -617,6 +621,7 @@ func registerWriteTools(s *mcpserver.MCPServer) {
|
||||
"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 把产物落成新版本",
|
||||
})
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"verification-platform-backend/internal/model"
|
||||
)
|
||||
|
||||
// 登录方式开关(login_mode)的判定逻辑集中在这里,供 app 侧(登录/注册/信息下发)
|
||||
// 与 admin 侧(设置、影响面统计)共用。
|
||||
//
|
||||
// 设计约定:
|
||||
// - login_mode 是应用级**策略**,客户端界面只影响体验,真正的判定必须发生在服务端;
|
||||
// - 判定必须早于任何副作用(建绑定、记失败、改 last_login、触发风控锁定);
|
||||
// - 空值/非法值一律按 both 处理(fail-open),任何时候都不把用户锁在门外;
|
||||
// - 生效级别由 LoginModeEnforce 控制:off = 不校验,warn = 只记录,strict = 拦截;
|
||||
// - 处于宽限期(LoginModeGraceUntil 未过)时旧凭证仍可用,只在响应里带 deprecated 标记。
|
||||
|
||||
// AppLoginMode 归一化应用的登录方式;空值/未知值按 both 处理。
|
||||
func AppLoginMode(app *model.Application) string {
|
||||
if app == nil {
|
||||
return "both"
|
||||
}
|
||||
switch app.LoginMode {
|
||||
case "account", "card", "both":
|
||||
return app.LoginMode
|
||||
}
|
||||
return "both"
|
||||
}
|
||||
|
||||
// AllowedLoginTypes 返回该模式下允许的凭证类型。
|
||||
func AllowedLoginTypes(mode string) []string {
|
||||
switch mode {
|
||||
case "account":
|
||||
return []string{"account"}
|
||||
case "card":
|
||||
return []string{"card"}
|
||||
default:
|
||||
return []string{"account", "card"}
|
||||
}
|
||||
}
|
||||
|
||||
// AppLoginModeEnforce 归一化生效级别;空值/未知值按 off 处理,保证升级后行为不变。
|
||||
func AppLoginModeEnforce(app *model.Application) string {
|
||||
if app == nil {
|
||||
return "off"
|
||||
}
|
||||
switch app.LoginModeEnforce {
|
||||
case "off", "warn", "strict":
|
||||
return app.LoginModeEnforce
|
||||
}
|
||||
return "off"
|
||||
}
|
||||
|
||||
// LoginModeLabel 用于错误文案。
|
||||
func LoginModeLabel(mode string) string {
|
||||
switch mode {
|
||||
case "account":
|
||||
return "账号密码"
|
||||
case "card":
|
||||
return "卡密"
|
||||
default:
|
||||
return "账号密码或卡密"
|
||||
}
|
||||
}
|
||||
|
||||
// LoginModeGraceDaysLeft 返回宽限期剩余天数(向上取整);不在宽限期返回 0。
|
||||
func LoginModeGraceDaysLeft(app *model.Application) int {
|
||||
if app == nil || app.LoginModeGraceUntil == nil {
|
||||
return 0
|
||||
}
|
||||
d := time.Until(*app.LoginModeGraceUntil)
|
||||
if d <= 0 {
|
||||
return 0
|
||||
}
|
||||
days := int(math.Ceil(d.Hours() / 24))
|
||||
if days < 1 {
|
||||
days = 1
|
||||
}
|
||||
return days
|
||||
}
|
||||
|
||||
// LoginTypeAllowedByMode 判断某凭证类型在当前模式下是否允许。
|
||||
func LoginTypeAllowedByMode(app *model.Application, loginType string) bool {
|
||||
for _, t := range AllowedLoginTypes(AppLoginMode(app)) {
|
||||
if t == loginType {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// LoginModeBlockMessage 生成给终端用户看的拒绝文案。
|
||||
func LoginModeBlockMessage(mode string) string {
|
||||
switch mode {
|
||||
case "account":
|
||||
return "该应用仅支持账号密码登录"
|
||||
case "card":
|
||||
return "该应用仅支持卡密登录"
|
||||
default:
|
||||
return "该应用当前不支持的登录方式"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"verification-platform-backend/internal/model"
|
||||
)
|
||||
|
||||
func TestAppLoginModeNormalize(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"account", "account"},
|
||||
{"card", "card"},
|
||||
{"both", "both"},
|
||||
{"", "both"}, // 空值按 both:任何情况下都不把用户锁在门外
|
||||
{"weird", "both"}, // 非法值同上
|
||||
}
|
||||
for _, c := range cases {
|
||||
app := &model.Application{LoginMode: c.in}
|
||||
if got := AppLoginMode(app); got != c.want {
|
||||
t.Fatalf("AppLoginMode(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
if got := AppLoginMode(nil); got != "both" {
|
||||
t.Fatalf("AppLoginMode(nil) = %q, want both", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppLoginModeEnforceNormalize(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"off", "off"},
|
||||
{"warn", "warn"},
|
||||
{"strict", "strict"},
|
||||
{"", "off"}, // 空值不拦截
|
||||
{"bogus", "off"}, // 非法值不拦截
|
||||
}
|
||||
for _, c := range cases {
|
||||
app := &model.Application{LoginModeEnforce: c.in}
|
||||
if got := AppLoginModeEnforce(app); got != c.want {
|
||||
t.Fatalf("AppLoginModeEnforce(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginTypeAllowedByMode(t *testing.T) {
|
||||
m := func(mode, enforce string) *model.Application {
|
||||
return &model.Application{LoginMode: mode, LoginModeEnforce: enforce}
|
||||
}
|
||||
cases := []struct {
|
||||
app *model.Application
|
||||
typ string
|
||||
allow bool
|
||||
}{
|
||||
{m("account", "strict"), "account", true},
|
||||
{m("account", "strict"), "card", false},
|
||||
{m("card", "strict"), "card", true},
|
||||
{m("card", "strict"), "account", false},
|
||||
{m("both", "strict"), "account", true},
|
||||
{m("both", "strict"), "card", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := LoginTypeAllowedByMode(c.app, c.typ); got != c.allow {
|
||||
t.Fatalf("mode=%s login_type=%s got %v want %v", c.app.LoginMode, c.typ, got, c.allow)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginModeGraceDaysLeft(t *testing.T) {
|
||||
past := time.Now().Add(-1 * time.Hour)
|
||||
future := time.Now().Add(72 * time.Hour)
|
||||
if got := LoginModeGraceDaysLeft(&model.Application{LoginModeGraceUntil: nil}); got != 0 {
|
||||
t.Fatalf("nil grace = %d, want 0", got)
|
||||
}
|
||||
if got := LoginModeGraceDaysLeft(&model.Application{LoginModeGraceUntil: &past}); got != 0 {
|
||||
t.Fatalf("expired grace = %d, want 0", got)
|
||||
}
|
||||
if got := LoginModeGraceDaysLeft(&model.Application{LoginModeGraceUntil: &future}); got != 3 {
|
||||
t.Fatalf("72h grace = %d, want 3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowedLoginTypes(t *testing.T) {
|
||||
if got := len(AllowedLoginTypes("account")); got != 1 {
|
||||
t.Fatalf("account should allow 1 type, got %d", got)
|
||||
}
|
||||
if got := len(AllowedLoginTypes("card")); got != 1 {
|
||||
t.Fatalf("card should allow 1 type, got %d", got)
|
||||
}
|
||||
if got := len(AllowedLoginTypes("both")); got != 2 {
|
||||
t.Fatalf("both should allow 2 types, got %d", got)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,2 @@
|
||||
# Add no patterns to .hgignore except for files generated by the build.
|
||||
last-change
|
||||
+28
@@ -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
@@ -0,0 +1,31 @@
|
||||
# package 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
@@ -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
@@ -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, ¶ms); 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, ¶ms); 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
@@ -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)
|
||||
}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
module software.sslmate.com/src/go-pkcs12
|
||||
|
||||
go 1.19
|
||||
|
||||
require golang.org/x/crypto v0.11.0
|
||||
Vendored
+20
@@ -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
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+71
@@ -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
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
// 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/sha1"
|
||||
"crypto/sha256"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
var (
|
||||
one = big.NewInt(1)
|
||||
)
|
||||
|
||||
// sha1Sum returns the SHA-1 hash of in.
|
||||
func sha1Sum(in []byte) []byte {
|
||||
sum := sha1.Sum(in)
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
// sha256Sum returns the SHA-256 hash of in.
|
||||
func sha256Sum(in []byte) []byte {
|
||||
sum := sha256.Sum256(in)
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
// fillWithRepeats returns v*ceiling(len(pattern) / v) bytes consisting of
|
||||
// repeats of pattern.
|
||||
func fillWithRepeats(pattern []byte, v int) []byte {
|
||||
if len(pattern) == 0 {
|
||||
return nil
|
||||
}
|
||||
outputLen := v * ((len(pattern) + v - 1) / v)
|
||||
return bytes.Repeat(pattern, (outputLen+len(pattern)-1)/len(pattern))[:outputLen]
|
||||
}
|
||||
|
||||
func pbkdf(hash func([]byte) []byte, u, v int, salt, password []byte, r int, ID byte, size int) (key []byte) {
|
||||
// implementation of https://tools.ietf.org/html/rfc7292#appendix-B.2 , RFC text verbatim in comments
|
||||
|
||||
// Let H be a hash function built around a compression function f:
|
||||
|
||||
// Z_2^u x Z_2^v -> Z_2^u
|
||||
|
||||
// (that is, H has a chaining variable and output of length u bits, and
|
||||
// the message input to the compression function of H is v bits). The
|
||||
// values for u and v are as follows:
|
||||
|
||||
// HASH FUNCTION VALUE u VALUE v
|
||||
// MD2, MD5 128 512
|
||||
// SHA-1 160 512
|
||||
// SHA-224 224 512
|
||||
// SHA-256 256 512
|
||||
// SHA-384 384 1024
|
||||
// SHA-512 512 1024
|
||||
// SHA-512/224 224 1024
|
||||
// SHA-512/256 256 1024
|
||||
|
||||
// Furthermore, let r be the iteration count.
|
||||
|
||||
// We assume here that u and v are both multiples of 8, as are the
|
||||
// lengths of the password and salt strings (which we denote by p and s,
|
||||
// respectively) and the number n of pseudorandom bits required. In
|
||||
// addition, u and v are of course non-zero.
|
||||
|
||||
// For information on security considerations for MD5 [19], see [25] and
|
||||
// [1], and on those for MD2, see [18].
|
||||
|
||||
// The following procedure can be used to produce pseudorandom bits for
|
||||
// a particular "purpose" that is identified by a byte called "ID".
|
||||
// This standard specifies 3 different values for the ID byte:
|
||||
|
||||
// 1. If ID=1, then the pseudorandom bits being produced are to be used
|
||||
// as key material for performing encryption or decryption.
|
||||
|
||||
// 2. If ID=2, then the pseudorandom bits being produced are to be used
|
||||
// as an IV (Initial Value) for encryption or decryption.
|
||||
|
||||
// 3. If ID=3, then the pseudorandom bits being produced are to be used
|
||||
// as an integrity key for MACing.
|
||||
|
||||
// 1. Construct a string, D (the "diversifier"), by concatenating v/8
|
||||
// copies of ID.
|
||||
var D []byte
|
||||
for i := 0; i < v; i++ {
|
||||
D = append(D, ID)
|
||||
}
|
||||
|
||||
// 2. Concatenate copies of the salt together to create a string S of
|
||||
// length v(ceiling(s/v)) bits (the final copy of the salt may be
|
||||
// truncated to create S). Note that if the salt is the empty
|
||||
// string, then so is S.
|
||||
|
||||
S := fillWithRepeats(salt, v)
|
||||
|
||||
// 3. Concatenate copies of the password together to create a string P
|
||||
// of length v(ceiling(p/v)) bits (the final copy of the password
|
||||
// may be truncated to create P). Note that if the password is the
|
||||
// empty string, then so is P.
|
||||
|
||||
P := fillWithRepeats(password, v)
|
||||
|
||||
// 4. Set I=S||P to be the concatenation of S and P.
|
||||
I := append(S, P...)
|
||||
|
||||
// 5. Set c=ceiling(n/u).
|
||||
c := (size + u - 1) / u
|
||||
|
||||
// 6. For i=1, 2, ..., c, do the following:
|
||||
A := make([]byte, c*u)
|
||||
var IjBuf []byte
|
||||
for i := 0; i < c; i++ {
|
||||
// A. Set A2=H^r(D||I). (i.e., the r-th hash of D||1,
|
||||
// H(H(H(... H(D||I))))
|
||||
Ai := hash(append(D, I...))
|
||||
for j := 1; j < r; j++ {
|
||||
Ai = hash(Ai)
|
||||
}
|
||||
copy(A[i*u:], Ai[:])
|
||||
|
||||
if i < c-1 { // skip on last iteration
|
||||
// B. Concatenate copies of Ai to create a string B of length v
|
||||
// bits (the final copy of Ai may be truncated to create B).
|
||||
var B []byte
|
||||
for len(B) < v {
|
||||
B = append(B, Ai[:]...)
|
||||
}
|
||||
B = B[:v]
|
||||
|
||||
// C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit
|
||||
// blocks, where k=ceiling(s/v)+ceiling(p/v), modify I by
|
||||
// setting I_j=(I_j+B+1) mod 2^v for each j.
|
||||
{
|
||||
Bbi := new(big.Int).SetBytes(B)
|
||||
Ij := new(big.Int)
|
||||
|
||||
for j := 0; j < len(I)/v; j++ {
|
||||
Ij.SetBytes(I[j*v : (j+1)*v])
|
||||
Ij.Add(Ij, Bbi)
|
||||
Ij.Add(Ij, one)
|
||||
Ijb := Ij.Bytes()
|
||||
// We expect Ijb to be exactly v bytes,
|
||||
// if it is longer or shorter we must
|
||||
// adjust it accordingly.
|
||||
if len(Ijb) > v {
|
||||
Ijb = Ijb[len(Ijb)-v:]
|
||||
}
|
||||
if len(Ijb) < v {
|
||||
if IjBuf == nil {
|
||||
IjBuf = make([]byte, v)
|
||||
}
|
||||
bytesShort := v - len(Ijb)
|
||||
for i := 0; i < bytesShort; i++ {
|
||||
IjBuf[i] = 0
|
||||
}
|
||||
copy(IjBuf[bytesShort:], Ijb)
|
||||
Ijb = IjBuf
|
||||
}
|
||||
copy(I[j*v:(j+1)*v], Ijb)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 7. Concatenate A_1, A_2, ..., A_c together to form a pseudorandom
|
||||
// bit string, A.
|
||||
|
||||
// 8. Use the first n bits of A as the output of this entire process.
|
||||
return A[:size]
|
||||
|
||||
// If the above process is being used to generate a DES key, the process
|
||||
// should be used to create 64 random bits, and the key's parity bits
|
||||
// should be set after the 64 bits have been produced. Similar concerns
|
||||
// hold for 2-key and 3-key triple-DES keys, for CDMF keys, and for any
|
||||
// similar keys with parity bits "built into them".
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user