feat(protect): 服务端加壳任务
- internal/protect: PE 注入(改入口 + 内嵌壳 DLL + 双层 CRC32),内嵌 x64/x86 blob 与壳 DLL - 模型 ProtectTask + 自动迁移 - 路由 /api/v1/dev/protect/tasks: 创建(异步)/列表/详情/下载/删除 - 壳侧新增 device_auto:运行时用 MachineGuid+卷序列号+计算机名算设备指纹 - 单测:资产完整性、cfg 生成、路由注册、产物命名
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
// 验证服务端加壳链路:用 protect.Patch 打一个真实 Windows 程序,落盘供 Wine 实测
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"verification-platform-backend/internal/protect"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 4 {
|
||||
fmt.Fprintln(os.Stderr, "用法: packtest <src.exe> <out.exe> <cfg.json>")
|
||||
os.Exit(2)
|
||||
}
|
||||
src, err := os.ReadFile(os.Args[1])
|
||||
must(err)
|
||||
cfg, err := os.ReadFile(os.Args[3])
|
||||
must(err)
|
||||
|
||||
arch, err := protect.DetectArch(src)
|
||||
must(err)
|
||||
fmt.Printf("源: %s 架构: %s %d 字节\n", filepath.Base(os.Args[1]), arch, len(src))
|
||||
|
||||
out, info, err := protect.Patch(src, cfg, arch)
|
||||
must(err)
|
||||
must(os.WriteFile(os.Args[2], out, 0o644))
|
||||
|
||||
fmt.Printf("产物: %s %d 字节\n", os.Args[2], info.OutSize)
|
||||
fmt.Printf("入口 0x%x → 0x%x .vfy RVA=0x%x size=%d\n", info.EntryOld, info.EntryNew, info.SecRVA, info.SecSize)
|
||||
fmt.Printf("crcVfy=%08x crcFile=%08x\n", info.CrcVfy, info.CrcFile)
|
||||
}
|
||||
|
||||
func must(err error) {
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "error:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -242,6 +242,7 @@ func runMigrations() {
|
||||
&model.EmailTemplate{},
|
||||
&model.VersionFile{},
|
||||
&model.CloudVariableRecord{},
|
||||
&model.ProtectTask{},
|
||||
}
|
||||
for _, m := range models {
|
||||
var err error
|
||||
|
||||
@@ -890,6 +890,30 @@ type PackHistory struct {
|
||||
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
|
||||
}
|
||||
|
||||
// ProtectTask 加壳任务:给原始程序注入验证壳(改入口 + 内嵌壳 DLL + 双层 CRC32)
|
||||
type ProtectTask struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
ApplicationID uint `gorm:"index" json:"application_id"`
|
||||
UserID uint `gorm:"index" json:"user_id"`
|
||||
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"`
|
||||
|
||||
Application Application `gorm:"foreignKey:ApplicationID" json:"application,omitempty"`
|
||||
User AppUser `gorm:"foreignKey:UserID" json:"user,omitempty"`
|
||||
}
|
||||
|
||||
// WebhookConfig Webhook配置
|
||||
type WebhookConfig struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,329 @@
|
||||
// Package protect:服务端给 PE 注入验证壳(改入口 + 内嵌壳 DLL + 双层 CRC32)
|
||||
//
|
||||
// 产物结构:原 exe 追加 .vfy 节 = [48B 头][引导 blob][壳 DLL][配置 JSON]
|
||||
// 入口指向 .vfy 内的引导代码;引导代码反射加载 DLL(零落盘)。
|
||||
package protect
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"debug/pe"
|
||||
"embed"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
//go:embed assets/blob64.bin assets/blob32.bin assets/shell64.bin assets/shell32.bin
|
||||
var assets embed.FS
|
||||
|
||||
const (
|
||||
hdrSize = 48
|
||||
crcOff = 36
|
||||
secName = ".vfy"
|
||||
shellVer = 8
|
||||
secAttrib = 0x60000020 // CODE | EXECUTE | READ
|
||||
)
|
||||
|
||||
// Assets 取出指定架构的 blob 与壳 DLL
|
||||
func Assets(arch string) (blob, dll []byte, err error) {
|
||||
var bp, dp string
|
||||
switch arch {
|
||||
case "x64":
|
||||
bp, dp = "assets/blob64.bin", "assets/shell64.bin"
|
||||
case "x86":
|
||||
bp, dp = "assets/blob32.bin", "assets/shell32.bin"
|
||||
default:
|
||||
return nil, nil, fmt.Errorf("不支持的架构: %s", arch)
|
||||
}
|
||||
blob, err = assets.ReadFile(bp)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
dll, err = assets.ReadFile(dp)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return blob, dll, nil
|
||||
}
|
||||
|
||||
// DetectArch 判断目标 PE 是 x64 还是 x86
|
||||
func DetectArch(target []byte) (string, error) {
|
||||
f, err := pe.NewFile(bytes.NewReader(target))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("不是有效 PE: %w", err)
|
||||
}
|
||||
switch f.Machine {
|
||||
case pe.IMAGE_FILE_MACHINE_AMD64:
|
||||
return "x64", nil
|
||||
case pe.IMAGE_FILE_MACHINE_I386:
|
||||
return "x86", nil
|
||||
}
|
||||
return "", fmt.Errorf("不支持的架构 machine=0x%x", f.Machine)
|
||||
}
|
||||
|
||||
// Patch 把验证壳注入 target,返回产物与两份 CRC
|
||||
func Patch(target, cfg []byte, arch string) (out []byte, info Info, err error) {
|
||||
blob, dll, err := Assets(arch)
|
||||
if err != nil {
|
||||
return nil, info, err
|
||||
}
|
||||
return patchWith(target, blob, dll, cfg)
|
||||
}
|
||||
|
||||
// Info 打包结果摘要
|
||||
type Info struct {
|
||||
Arch string
|
||||
EntryOld uint32
|
||||
EntryNew uint32
|
||||
SecRVA uint32
|
||||
SecSize uint32
|
||||
CrcVfy uint32
|
||||
CrcFile uint32
|
||||
OutSize int
|
||||
OriginalSource int
|
||||
}
|
||||
|
||||
func patchWith(raw, blob, dll, cfg []byte) ([]byte, Info, error) {
|
||||
var info Info
|
||||
f, err := pe.NewFile(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, info, fmt.Errorf("解析 PE: %w", err)
|
||||
}
|
||||
is64 := f.Machine == pe.IMAGE_FILE_MACHINE_AMD64
|
||||
is32 := f.Machine == pe.IMAGE_FILE_MACHINE_I386
|
||||
if !is64 && !is32 {
|
||||
return nil, info, fmt.Errorf("不支持的架构 machine=0x%x", f.Machine)
|
||||
}
|
||||
info.Arch = map[bool]string{true: "x64", false: "x86"}[is64]
|
||||
info.OriginalSource = len(raw)
|
||||
|
||||
peOff := int(binary.LittleEndian.Uint32(raw[0x3C:0x40])) + 4 + 20
|
||||
var numSections uint16
|
||||
var sizeOfHeaders, fileAlign, sectAlign, entryRVA uint32
|
||||
if is64 {
|
||||
oh := f.OptionalHeader.(*pe.OptionalHeader64)
|
||||
numSections, sizeOfHeaders = f.FileHeader.NumberOfSections, oh.SizeOfHeaders
|
||||
fileAlign, sectAlign, entryRVA = oh.FileAlignment, oh.SectionAlignment, oh.AddressOfEntryPoint
|
||||
} else {
|
||||
oh := f.OptionalHeader.(*pe.OptionalHeader32)
|
||||
numSections, sizeOfHeaders = f.FileHeader.NumberOfSections, oh.SizeOfHeaders
|
||||
fileAlign, sectAlign, entryRVA = oh.FileAlignment, oh.SectionAlignment, oh.AddressOfEntryPoint
|
||||
}
|
||||
if fileAlign == 0 {
|
||||
fileAlign = 0x200
|
||||
}
|
||||
if sectAlign == 0 {
|
||||
sectAlign = 0x1000
|
||||
}
|
||||
|
||||
var maxEnd, maxRVAEnd uint32
|
||||
for _, s := range f.Sections {
|
||||
if end := s.Offset + s.Size; end > maxEnd {
|
||||
maxEnd = end
|
||||
}
|
||||
for _, e := range []uint32{s.VirtualAddress + s.VirtualSize, s.VirtualAddress + s.Size} {
|
||||
if e > maxRVAEnd {
|
||||
maxRVAEnd = e
|
||||
}
|
||||
}
|
||||
}
|
||||
newFileOff := align(maxEnd, fileAlign)
|
||||
newRVA := align(maxRVAEnd, sectAlign)
|
||||
|
||||
shOff := uint32(peOff) + uint32(optSize(is64)) + uint32(numSections)*40
|
||||
if shOff+40 > sizeOfHeaders {
|
||||
return nil, info, fmt.Errorf("头部空间不足(SizeOfHeaders=0x%x)", sizeOfHeaders)
|
||||
}
|
||||
|
||||
hdr := make([]byte, hdrSize)
|
||||
copy(hdr[0:4], []byte("VFY4"))
|
||||
binary.LittleEndian.PutUint32(hdr[4:], 4)
|
||||
dllOff := uint32(hdrSize) + uint32(len(blob))
|
||||
cfgOff := dllOff + uint32(len(dll))
|
||||
binary.LittleEndian.PutUint32(hdr[8:], dllOff)
|
||||
binary.LittleEndian.PutUint32(hdr[12:], uint32(len(dll)))
|
||||
binary.LittleEndian.PutUint32(hdr[16:], cfgOff)
|
||||
binary.LittleEndian.PutUint32(hdr[20:], uint32(len(cfg)))
|
||||
binary.LittleEndian.PutUint32(hdr[24:], entryRVA)
|
||||
binary.LittleEndian.PutUint32(hdr[28:], uint32(len(blob)))
|
||||
binary.LittleEndian.PutUint32(hdr[32:], 0) // flags
|
||||
|
||||
var sec bytes.Buffer
|
||||
sec.Write(hdr)
|
||||
sec.Write(blob)
|
||||
sec.Write(dll)
|
||||
sec.Write(cfg)
|
||||
sectionData := sec.Bytes()
|
||||
|
||||
binary.LittleEndian.PutUint32(sectionData[crcOff:], 0)
|
||||
binary.LittleEndian.PutUint32(sectionData[crcOff+4:], 0)
|
||||
crcV := crcSkip(sectionData[:crcOff], sectionData[crcOff+8:])
|
||||
binary.LittleEndian.PutUint32(sectionData[crcOff:], crcV)
|
||||
|
||||
padded := make([]byte, align(uint32(len(sectionData)), fileAlign))
|
||||
copy(padded, sectionData)
|
||||
|
||||
out := make([]byte, 0, int(newFileOff)+len(padded))
|
||||
out = append(out, raw...)
|
||||
for uint32(len(out)) < newFileOff {
|
||||
out = append(out, 0)
|
||||
}
|
||||
out = append(out, padded...)
|
||||
|
||||
sh := make([]byte, 40)
|
||||
copy(sh[0:8], secName)
|
||||
binary.LittleEndian.PutUint32(sh[8:], uint32(len(sectionData)))
|
||||
binary.LittleEndian.PutUint32(sh[12:], newRVA)
|
||||
binary.LittleEndian.PutUint32(sh[16:], uint32(len(padded)))
|
||||
binary.LittleEndian.PutUint32(sh[20:], newFileOff)
|
||||
binary.LittleEndian.PutUint32(sh[36:], secAttrib)
|
||||
copy(out[shOff:], sh)
|
||||
|
||||
lfanew := int(binary.LittleEndian.Uint32(out[0x3C:0x40]))
|
||||
binary.LittleEndian.PutUint16(out[lfanew+4+2:], numSections+1)
|
||||
binary.LittleEndian.PutUint32(out[peOff+16:], newRVA+hdrSize)
|
||||
newSizeOfImage := align(newRVA+uint32(len(sectionData)), sectAlign)
|
||||
binary.LittleEndian.PutUint32(out[peOff+56:], newSizeOfImage)
|
||||
curInit := binary.LittleEndian.Uint32(out[peOff+8:])
|
||||
binary.LittleEndian.PutUint32(out[peOff+8:], curInit+uint32(len(padded)))
|
||||
|
||||
ckOff := peOff + 64
|
||||
binary.LittleEndian.PutUint32(out[ckOff:], 0)
|
||||
binary.LittleEndian.PutUint32(out[ckOff:], peChecksum(out))
|
||||
|
||||
skipAt := int(newFileOff) + crcOff
|
||||
binary.LittleEndian.PutUint32(out[skipAt:], 0)
|
||||
binary.LittleEndian.PutUint32(out[skipAt+4:], 0)
|
||||
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.SecSize = uint32(len(sectionData))
|
||||
info.CrcVfy = crcV
|
||||
info.CrcFile = crcF
|
||||
info.OutSize = len(out)
|
||||
return out, info, nil
|
||||
}
|
||||
|
||||
// BuildCfg 生成壳配置(api 指向调用方所在站点)
|
||||
func BuildCfg(appKey, appName, baseURL string) []byte {
|
||||
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)
|
||||
return []byte(cfg)
|
||||
}
|
||||
|
||||
// ---------- 任务存储与执行 ----------
|
||||
type Runner struct {
|
||||
Dir string
|
||||
}
|
||||
|
||||
func NewRunner(dir string) *Runner {
|
||||
if dir == "" {
|
||||
dir = filepath.Join("data", "protect")
|
||||
}
|
||||
os.MkdirAll(dir, 0o755)
|
||||
return &Runner{Dir: dir}
|
||||
}
|
||||
|
||||
// Run 对已落盘的源文件加壳,返回产物路径与信息
|
||||
func (r *Runner) Run(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
|
||||
}
|
||||
out, info, err := Patch(src, cfg, arch)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
|
||||
return info, err
|
||||
}
|
||||
if err := os.WriteFile(outPath, out, 0o644); err != nil {
|
||||
return info, fmt.Errorf("写产物: %w", err)
|
||||
}
|
||||
return info, nil
|
||||
}
|
||||
|
||||
// SaveSource 把上传的原始程序落盘
|
||||
func (r *Runner) SaveSource(taskID uint, name string, data []byte) (string, error) {
|
||||
d := filepath.Join(r.Dir, fmt.Sprintf("%d", taskID))
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
base := filepath.Base(name)
|
||||
if base == "" || base == "." || base == string(filepath.Separator) {
|
||||
base = "app.exe"
|
||||
}
|
||||
p := filepath.Join(d, "src_"+base)
|
||||
if err := os.WriteFile(p, data, 0o644); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// OutPath 产物路径
|
||||
func (r *Runner) OutPath(taskID uint, name string) string {
|
||||
base := filepath.Base(name)
|
||||
if base == "" {
|
||||
base = "app.exe"
|
||||
}
|
||||
if i := strings.LastIndex(base, "."); i > 0 {
|
||||
base = base[:i] + "_protected" + base[i:]
|
||||
} else {
|
||||
base += "_protected.exe"
|
||||
}
|
||||
return filepath.Join(r.Dir, fmt.Sprintf("%d", taskID), base)
|
||||
}
|
||||
|
||||
func (r *Runner) Now() time.Time { return time.Now() }
|
||||
|
||||
// ---------- 内部工具 ----------
|
||||
func align(v, a uint32) uint32 {
|
||||
if a == 0 {
|
||||
return v
|
||||
}
|
||||
return (v + a - 1) / a * a
|
||||
}
|
||||
|
||||
func optSize(is64 bool) int {
|
||||
if is64 {
|
||||
return 240
|
||||
}
|
||||
return 224
|
||||
}
|
||||
|
||||
func crcSkip(chunks ...[]byte) uint32 {
|
||||
h := crc32.NewIEEE()
|
||||
for _, c := range chunks {
|
||||
h.Write(c)
|
||||
}
|
||||
return h.Sum32()
|
||||
}
|
||||
|
||||
func peChecksum(data []byte) uint32 {
|
||||
var sum uint64
|
||||
n := len(data)
|
||||
i := 0
|
||||
for ; i+1 < n; i += 2 {
|
||||
sum += uint64(binary.LittleEndian.Uint16(data[i:]))
|
||||
sum = (sum & 0xffff) + (sum >> 16)
|
||||
}
|
||||
if i < n {
|
||||
sum += uint64(data[i])
|
||||
sum = (sum & 0xffff) + (sum >> 16)
|
||||
}
|
||||
sum = (sum & 0xffff) + (sum >> 16)
|
||||
return uint32(sum) + uint32(n)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package protect
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 用仓库内嵌资产对一个构造的最小 PE 走一遍 Patch,验证结构与 CRC 自洽
|
||||
func TestPatchProducesValidHeader(t *testing.T) {
|
||||
for _, arch := range []string{"x64", "x86"} {
|
||||
blob, dll, err := Assets(arch)
|
||||
if err != nil {
|
||||
t.Fatalf("%s 资产缺失: %v", arch, err)
|
||||
}
|
||||
if len(blob) < 1000 || len(dll) < 100000 {
|
||||
t.Fatalf("%s 资产异常: blob=%d dll=%d", arch, len(blob), len(dll))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BuildCfg 必须生成可解析的 JSON 且带 device_auto
|
||||
func TestBuildCfg(t *testing.T) {
|
||||
cfg := BuildCfg("abc123", "客服助手", "https://v.example.com/")
|
||||
s := string(cfg)
|
||||
for _, want := range []string{
|
||||
`"api":"https://v.example.com/api/v1/app/abc123/login"`,
|
||||
`"device_auto":1`,
|
||||
`"name":"客服助手"`,
|
||||
} {
|
||||
if !contains(s, want) {
|
||||
t.Fatalf("cfg 缺少 %s,实际: %s", want, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
return len(s) >= len(sub) && (func() bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})()
|
||||
}
|
||||
|
||||
// Runner 的产物命名与目录
|
||||
func TestOutPath(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
r := NewRunner(dir)
|
||||
p := r.OutPath(7, "拼多多客服助手.exe")
|
||||
if filepath.Ext(p) != ".exe" || filepath.Dir(p) != filepath.Join(dir, "7") {
|
||||
t.Fatalf("产物路径不符合预期: %s", p)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Dir(p)); err == nil {
|
||||
t.Fatalf("目录不应提前创建")
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ func SetupRoutes(r *gin.RouterGroup) {
|
||||
SetupUsageRoutes(r)
|
||||
SetupAnnouncementRoutes(r)
|
||||
SetupVersionRoutes(r)
|
||||
SetupProtectRoutes(r)
|
||||
SetupProfileRoutes(r)
|
||||
SetupEmailRoutes(r)
|
||||
SetupSystemSettingsRoutes(r)
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
package admin
|
||||
|
||||
// 加壳任务:把验证壳注入用户上传的原始程序(异步,产物可下载)
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"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"
|
||||
)
|
||||
|
||||
var (
|
||||
protectRunner *protect.Runner
|
||||
protectOnce sync.Once
|
||||
)
|
||||
|
||||
func getRunner() *protect.Runner {
|
||||
protectOnce.Do(func() {
|
||||
dir := os.Getenv("PROTECT_DIR")
|
||||
protectRunner = protect.NewRunner(dir)
|
||||
})
|
||||
return protectRunner
|
||||
}
|
||||
|
||||
func SetupProtectRoutes(r *gin.RouterGroup) {
|
||||
g := r.Group("/protect")
|
||||
{
|
||||
g.POST("/tasks", HandleCreateProtectTask)
|
||||
g.GET("/tasks", HandleListProtectTasks)
|
||||
g.GET("/tasks/:id", HandleGetProtectTask)
|
||||
g.GET("/tasks/:id/download", HandleDownloadProtectTask)
|
||||
g.DELETE("/tasks/:id", HandleDeleteProtectTask)
|
||||
}
|
||||
}
|
||||
|
||||
// baseURL 从请求推断站点根地址(面板/应用共用同一域名)
|
||||
func baseURL(c *gin.Context) string {
|
||||
scheme := c.GetHeader("X-Forwarded-Proto")
|
||||
if scheme == "" {
|
||||
if c.Request.TLS != nil {
|
||||
scheme = "https"
|
||||
} else {
|
||||
scheme = "http"
|
||||
}
|
||||
}
|
||||
host := c.GetHeader("X-Forwarded-Host")
|
||||
if host == "" {
|
||||
host = c.Request.Host
|
||||
}
|
||||
return fmt.Sprintf("%s://%s", scheme, host)
|
||||
}
|
||||
|
||||
// HandleCreateProtectTask 上传原始程序 → 建任务 → 异步加壳
|
||||
func HandleCreateProtectTask(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
|
||||
appIDStr := c.PostForm("application_id")
|
||||
appID, err := strconv.ParseUint(appIDStr, 10, 64)
|
||||
if err != nil || appID == 0 {
|
||||
response.ParamError(c, "缺少 application_id")
|
||||
return
|
||||
}
|
||||
var app model.Application
|
||||
if err := database.DB.Where("id = ? AND user_id = ?", appID, userID).First(&app).Error; err != nil {
|
||||
response.NotFound(c, "应用不存在或无权操作")
|
||||
return
|
||||
}
|
||||
|
||||
fh, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
response.ParamError(c, "请上传要加壳的程序(form 字段 file)")
|
||||
return
|
||||
}
|
||||
name := filepath.Base(fh.Filename)
|
||||
if !strings.HasSuffix(strings.ToLower(name), ".exe") {
|
||||
response.ParamError(c, "目前只支持 Windows PE(.exe)")
|
||||
return
|
||||
}
|
||||
if fh.Size > 200*1024*1024 {
|
||||
response.ParamError(c, "文件过大(上限 200MB)")
|
||||
return
|
||||
}
|
||||
src, err := fh.Open()
|
||||
if err != nil {
|
||||
response.InternalError(c, "读取上传文件失败")
|
||||
return
|
||||
}
|
||||
data, err := io.ReadAll(src)
|
||||
src.Close()
|
||||
if err != nil {
|
||||
response.InternalError(c, "读取上传文件失败")
|
||||
return
|
||||
}
|
||||
|
||||
arch, err := protect.DetectArch(data)
|
||||
if err != nil {
|
||||
response.ParamError(c, "不是有效的 Windows 程序:"+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
task := model.ProtectTask{
|
||||
ApplicationID: uint(appID),
|
||||
UserID: userID,
|
||||
SourceName: name,
|
||||
SourceSize: int64(len(data)),
|
||||
Arch: arch,
|
||||
Status: "pending",
|
||||
}
|
||||
if err := database.DB.Create(&task).Error; err != nil {
|
||||
response.InternalError(c, "创建任务失败")
|
||||
return
|
||||
}
|
||||
|
||||
runner := getRunner()
|
||||
srcPath, err := runner.SaveSource(task.ID, name, data)
|
||||
if err != nil {
|
||||
database.DB.Model(&task).Updates(map[string]interface{}{"status": "failed", "message": "保存源文件失败: " + err.Error()})
|
||||
response.InternalError(c, "保存源文件失败")
|
||||
return
|
||||
}
|
||||
|
||||
cfg := protect.BuildCfg(app.AppKey, app.Name, baseURL(c))
|
||||
go runProtectTask(task.ID, srcPath, name, cfg)
|
||||
|
||||
response.SuccessWithMessage(c, "任务已创建,正在加壳", gin.H{
|
||||
"task_id": task.ID,
|
||||
"arch": arch,
|
||||
"status": "pending",
|
||||
})
|
||||
}
|
||||
|
||||
func runProtectTask(taskID uint, srcPath, srcName string, cfg []byte) {
|
||||
runner := getRunner()
|
||||
now := time.Now()
|
||||
database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).
|
||||
Updates(map[string]interface{}{"status": "running", "started_at": &now})
|
||||
|
||||
outPath := runner.OutPath(taskID, srcName)
|
||||
info, err := runner.Run(srcPath, outPath, cfg)
|
||||
if err != nil {
|
||||
log.Printf("[protect] task %d failed: %v", taskID, err)
|
||||
fin := time.Now()
|
||||
database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).Updates(map[string]interface{}{
|
||||
"status": "failed", "message": err.Error(), "finished_at": &fin,
|
||||
})
|
||||
return
|
||||
}
|
||||
fin := time.Now()
|
||||
updates := map[string]interface{}{
|
||||
"status": "done",
|
||||
"message": fmt.Sprintf("入口 0x%x → 0x%x,.vfy RVA=0x%x", info.EntryOld, info.EntryNew, info.SecRVA),
|
||||
"output_name": filepath.Base(outPath),
|
||||
"output_size": int64(info.OutSize),
|
||||
"output_path": outPath,
|
||||
"crc_vfy": fmt.Sprintf("%08x", info.CrcVfy),
|
||||
"crc_file": fmt.Sprintf("%08x", info.CrcFile),
|
||||
"finished_at": &fin,
|
||||
"arch": info.Arch,
|
||||
}
|
||||
database.DB.Model(&model.ProtectTask{}).Where("id = ?", taskID).Updates(updates)
|
||||
log.Printf("[protect] task %d done: %s (%d → %d 字节)", taskID, outPath, info.OriginalSource, info.OutSize)
|
||||
}
|
||||
|
||||
// HandleListProtectTasks 任务列表
|
||||
func HandleListProtectTasks(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
q := database.DB.Model(&model.ProtectTask{}).Where("user_id = ?", userID)
|
||||
if v := c.Query("application_id"); v != "" {
|
||||
q = q.Where("application_id = ?", v)
|
||||
}
|
||||
if v := c.Query("status"); v != "" {
|
||||
q = q.Where("status = ?", v)
|
||||
}
|
||||
var total int64
|
||||
q.Count(&total)
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
perPage, _ := strconv.Atoi(c.DefaultQuery("per_page", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if perPage < 1 || perPage > 100 {
|
||||
perPage = 20
|
||||
}
|
||||
var tasks []model.ProtectTask
|
||||
q.Order("id DESC").Limit(perPage).Offset((page - 1) * perPage).Find(&tasks)
|
||||
response.PageSuccess(c, tasks, total, page, perPage)
|
||||
}
|
||||
|
||||
// HandleGetProtectTask 单任务详情
|
||||
func HandleGetProtectTask(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
var task model.ProtectTask
|
||||
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&task).Error; err != nil {
|
||||
response.NotFound(c, "任务不存在")
|
||||
return
|
||||
}
|
||||
response.Success(c, task)
|
||||
}
|
||||
|
||||
// HandleDownloadProtectTask 下载加壳产物
|
||||
func HandleDownloadProtectTask(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
var task model.ProtectTask
|
||||
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&task).Error; err != nil {
|
||||
response.NotFound(c, "任务不存在")
|
||||
return
|
||||
}
|
||||
if task.Status != "done" || task.OutputPath == "" {
|
||||
response.Error(c, 400, "任务尚未完成")
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(task.OutputPath); err != nil {
|
||||
response.NotFound(c, "产物文件已丢失")
|
||||
return
|
||||
}
|
||||
c.FileAttachment(task.OutputPath, task.OutputName)
|
||||
}
|
||||
|
||||
// HandleDeleteProtectTask 删除任务(含源文件与产物)
|
||||
func HandleDeleteProtectTask(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
id, _ := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
var task model.ProtectTask
|
||||
if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&task).Error; err != nil {
|
||||
response.NotFound(c, "任务不存在")
|
||||
return
|
||||
}
|
||||
if task.Status == "running" {
|
||||
response.Error(c, 400, "任务正在执行,稍后再删")
|
||||
return
|
||||
}
|
||||
if task.OutputPath != "" {
|
||||
os.Remove(task.OutputPath)
|
||||
}
|
||||
os.RemoveAll(filepath.Dir(filepath.Join(getRunner().Dir, strconv.FormatUint(uint64(task.ID), 10))))
|
||||
database.DB.Delete(&model.ProtectTask{}, task.ID)
|
||||
response.SuccessWithMessage(c, "已删除", nil)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 确认加壳任务路由已挂到 /api/v1/dev 下(防止注册漏掉)
|
||||
func TestProtectRoutesRegistered(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
g := r.Group("/api/v1/dev")
|
||||
SetupProtectRoutes(g)
|
||||
|
||||
want := map[string]bool{
|
||||
"/api/v1/dev/protect/tasks": false,
|
||||
"/api/v1/dev/protect/tasks/:id": false,
|
||||
"/api/v1/dev/protect/tasks/:id/download": false,
|
||||
}
|
||||
for _, ri := range r.Routes() {
|
||||
if _, ok := want[ri.Path]; ok {
|
||||
want[ri.Path] = true
|
||||
}
|
||||
}
|
||||
for p, ok := range want {
|
||||
if !ok {
|
||||
t.Fatalf("路由未注册: %s", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user