diff --git a/backend/internal/protect/pfx.go b/backend/internal/protect/pfx.go index 56957e2..cfdfb82 100644 --- a/backend/internal/protect/pfx.go +++ b/backend/internal/protect/pfx.go @@ -22,6 +22,7 @@ type PFXIdentity struct { Subject string `json:"subject"` NotAfter time.Time `json:"not_after"` Expired bool `json:"expired"` + Usage CertUsage `json:"usage"` // 能签什么:应用 / 驱动 / 两者 } // PFXInfo 一个证书文件里到底装了什么。 @@ -314,6 +315,7 @@ func ParsePFX(data []byte, password string) (PFXInfo, error) { Subject: c.Subject.String(), NotAfter: c.NotAfter, Expired: c.NotAfter.Before(time.Now()), + Usage: ClassifyUsage(c), }) } // 保持文件内顺序,不要按到期时间重排:osslsigncode(OpenSSL PKCS12_parse) @@ -503,6 +505,7 @@ type IdentityDetail struct { Issuer *x509.Certificate // 包里能找到签发者就填,找不到为 nil Revoke RevokeInfo // 未检测时 Status = not_checked Ban RevokeInfo + Usage CertUsage // 应用 / 驱动 } // ParseIdentitiesFull 解析出每套身份,并把包里能找到的签发者一并配上。 @@ -523,6 +526,7 @@ func ParseIdentitiesFull(data []byte, password string) ([]IdentityDetail, error) Cert: c, Revoke: RevokeInfo{Status: RevokeNotChecked}, Ban: RevokeInfo{Status: RevokeNotChecked}, + Usage: ClassifyUsage(c), } // 在包内同一批证书里找签发者:能验通签名的那张就是 for _, cand := range m.certs { diff --git a/backend/internal/protect/protect.go b/backend/internal/protect/protect.go index e5396bc..0ee0dba 100644 --- a/backend/internal/protect/protect.go +++ b/backend/internal/protect/protect.go @@ -302,6 +302,27 @@ func (r *Runner) RunWithTask(task *model.ProtectTask, srcPath, outPath string, c } } 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 diff --git a/backend/internal/protect/revocation.go b/backend/internal/protect/revocation.go index a823995..7ca49f2 100644 --- a/backend/internal/protect/revocation.go +++ b/backend/internal/protect/revocation.go @@ -562,3 +562,30 @@ func CheckProfileIdentity(profileID uint, identity int, localBan map[string]stri 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 +} diff --git a/backend/internal/protect/usage.go b/backend/internal/protect/usage.go new file mode 100644 index 0000000..f744b1c --- /dev/null +++ b/backend/internal/protect/usage.go @@ -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") +} diff --git a/backend/internal/router/admin/protect.go b/backend/internal/router/admin/protect.go index 9470808..5334a10 100644 --- a/backend/internal/router/admin/protect.go +++ b/backend/internal/router/admin/protect.go @@ -72,9 +72,9 @@ func HandleCreateProtectTask(c *gin.Context) { name := filepath.Base(fh.Filename) ext := strings.ToLower(filepath.Ext(name)) switch ext { - case ".exe", ".dll", ".apk", ".ipa", ".elf", ".bin", "": + case ".exe", ".dll", ".apk", ".ipa", ".elf", ".bin", ".sys", ".efi", "": default: - response.ParamError(c, "支持 .exe/.dll/.apk/.ipa/.elf(Linux 可执行可无扩展名);其他格式还没接入") + response.ParamError(c, "支持 .exe/.dll/.sys/.apk/.ipa/.elf(Linux 可执行可无扩展名);其他格式还没接入") return } if fh.Size > 200*1024*1024 { @@ -121,6 +121,25 @@ func HandleCreateProtectTask(c *gin.Context) { 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) + if usage, usubj, uerr := protect.ProfileIdentityUsage(uint(pid), certIdentity); uerr == nil { + if isDriver && !usage.Driver { + c.JSON(400, gin.H{"code": 400, + "message": "所选证书没有内核驱动签名用途,不能签 .sys", + "hint": "证书 EKU:" + usage.Label + ";驱动签名需要含 KMCS(1.3.6.1.4.1.311.61.1.1)的证书(" + usubj + ")"}) + return + } + if !isDriver && !usage.App { + c.JSON(400, gin.H{"code": 400, + "message": "所选证书只能签内核驱动,不能签应用文件", + "hint": "证书 EKU:" + usage.Label + "(" + usubj + ")"}) + return + } + } + // 平台必须和文件类型对得上:PE 要 windows 证书,IPA 要 iOS 证书; // APK/ELF 不吃签名证书,传了直接拒,免得以为签过了。 det := protect.DetectFile(data, fh.Filename) @@ -179,6 +198,14 @@ func HandleCreateProtectTask(c *gin.Context) { } } + // 内核驱动没有用户态壳可加,必须带证书走「仅签名」 + if signProfileID == nil && protect.IsDriverPE(data, fh.Filename) { + c.JSON(400, gin.H{"code": 400, + "message": "内核驱动只能签名,不能加验证壳", + "hint": "请在「重签证书」里选一张支持驱动签名用途的证书(.sys 加壳后会加载失败)"}) + return + } + task, err := protect.CreateAndRunSignedIdentity(&app, userID, name, data, baseURL(c), signProfileID, certIdentity) if err != nil { response.ParamError(c, err.Error()) diff --git a/frontend/src/pages/admin/protect/index.vue b/frontend/src/pages/admin/protect/index.vue index b49db3e..99525b6 100644 --- a/frontend/src/pages/admin/protect/index.vue +++ b/frontend/src/pages/admin/protect/index.vue @@ -61,13 +61,19 @@ const selectedSignProfile = ref('') // 按文件类型决定需要哪种证书:PE→windows,IPA→ios,APK/ELF 不吃证书 const fileKind = computed(() => { const n = (chosenFile.value?.name || '').toLowerCase() + // 内核驱动:.sys 只能签名、不能加壳(用户态壳注进内核模块会直接加载失败) + if (n.endsWith('.sys')) return 'driver' if (n.endsWith('.exe') || n.endsWith('.dll')) return 'pe' if (n.endsWith('.ipa')) return 'ipa' if (n.endsWith('.apk')) return 'apk' if (n.endsWith('.elf') || n.endsWith('.bin')) return 'elf' return '' }) -const wantPlatform = computed(() => (fileKind.value === 'pe' ? 'windows' : fileKind.value === 'ipa' ? 'ios' : '')) +const wantPlatform = computed(() => { + if (fileKind.value === 'pe' || fileKind.value === 'driver') return 'windows' + if (fileKind.value === 'ipa') return 'ios' + return '' +}) const certSupported = computed(() => wantPlatform.value !== '') // 过期证书也列出来:私服/内网分发时「有签名」比「链被信任」更重要, @@ -113,6 +119,22 @@ async function loadIdentities(profileId: string) { watch(selectedSignProfile, (v) => { if (v) loadIdentities(v); else identities.value = [] }) // 选中身份后查一次吊销 / 拉黑(只查这一套,不整包联网) +// 按上传的文件类型过滤身份:exe 只列能签应用的,.sys 只列能签驱动的 +const identitiesForFile = computed(() => { + const want = fileKind.value === 'driver' ? 'driver' : fileKind.value === 'pe' ? 'app' : '' + if (!want) return identities.value + return identities.value.filter((it: any) => it?.usage?.[want]) +}) + +const usageSummary = computed(() => { + const app = identities.value.filter((it: any) => it?.usage?.app).length + const drv = identities.value.filter((it: any) => it?.usage?.driver).length + return { app, drv } +}) + +// 当前文件类型需要的用途 +const needUsage = computed(() => (fileKind.value === 'driver' ? 'driver' : fileKind.value === 'pe' ? 'app' : '')) + const identityCheck = ref(null) const identityChecking = ref(false) @@ -145,7 +167,8 @@ const selectedExpired = computed(() => { function identityLabel(it: any) { const date = String(it.not_after || '').slice(0, 10) const cn = String(it.subject || '').split('CN=').pop()?.split(',')[0]?.trim() || it.subject - return `#${it.index} · ${cn} · ${date}${it.expired ? ' 已过期' : ''}` + const usage = it?.usage?.label ? ` · ${it.usage.label}` : '' + return `#${it.index} · ${cn} · ${date}${it.expired ? ' 已过期' : ''}${usage}` } // 把后端状态码翻成人话:good=正常 / revoked=已吊销或拉黑 / unknown=查不到 @@ -262,7 +285,8 @@ function schedulePoll() { function pickFile(file: File | null | undefined) { if (!file) return - if (!/\.(exe|dll|apk|ipa)$/i.test(file.name)) { + // 驱动 .sys 也走这条路(驱动只签名、不加壳) + if (!/\.(exe|dll|sys|efi|apk|ipa)$/i.test(file.name)) { toast.error(t('admin.protect.onlyExe')) return } @@ -500,7 +524,7 @@ onBeforeUnmount(() => { @drop.prevent="onDrop" @click="fileInput?.click()" > - + +

+ {{ t('admin.protect.driverHint') }} +

+
@@ -551,17 +579,24 @@ onBeforeUnmount(() => { - {{ identityLabel(it) }} - {{ identityLoading ? '加载中…' : t('admin.protect.certIdentityCount', { n: identities.length || selectedProfile!.key_count }) }} + {{ identityLoading ? '加载中…' : t('admin.protect.certIdentityCount', { n: needUsage ? identitiesForFile.length : (identities.length || selectedProfile!.key_count) }) }} + + + {{ t('admin.protect.usageSummary', { app: usageSummary.app, drv: usageSummary.drv }) }}

{{ t('admin.protect.certIdentityHint') }}

+

+ {{ needUsage === 'driver' ? t('admin.protect.needDriverCert') : t('admin.protect.needAppCert') }} +

{{ t('admin.protect.revokeState') }} diff --git a/frontend/src/plugins/i18n/en.json b/frontend/src/plugins/i18n/en.json index 90017f7..99f1d46 100644 --- a/frontend/src/plugins/i18n/en.json +++ b/frontend/src/plugins/i18n/en.json @@ -2643,7 +2643,11 @@ "revokeGood": "OK", "revokeBad": "Revoked/Blacklisted", "revokeUnknown": "Unavailable", - "revokeNotChecked": "Not checked" + "revokeNotChecked": "Not checked", + "usageSummary": "In this file: {app} app-capable / {drv} driver-capable", + "needDriverCert": "No driver-capable identity in this file (EKU lacks KMCS); signing a .sys with it is useless.", + "needAppCert": "No app-capable identity in this file (EKU lacks Code Signing); cannot sign exe/dll.", + "driverHint": "Kernel driver (.sys): Authenticode signing only, no verification shell (it would fail to load); a driver-capable certificate is required" }, "signProfiles": { "title": "Signing certificates", diff --git a/frontend/src/plugins/i18n/zh.json b/frontend/src/plugins/i18n/zh.json index f7e07d0..a603b92 100644 --- a/frontend/src/plugins/i18n/zh.json +++ b/frontend/src/plugins/i18n/zh.json @@ -2662,7 +2662,11 @@ "revokeGood": "正常", "revokeBad": "已吊销/已拉黑", "revokeUnknown": "查不到", - "revokeNotChecked": "未检测" + "revokeNotChecked": "未检测", + "usageSummary": "该文件里:可签应用 {app} 套 / 可签驱动 {drv} 套", + "needDriverCert": "这个证书文件里没有可签内核驱动的身份(EKU 缺 KMCS),签 .sys 无效。驱动签名需要专门的驱动证书。", + "needAppCert": "这个证书文件里没有可签应用的身份(EKU 缺 Code Signing),不能签 exe/dll。", + "driverHint": "内核驱动(.sys):只做 Authenticode 签名,不注入验证壳(注进内核模块会加载失败);必须选一张支持驱动签名用途的证书" }, "signProfiles": { "title": "签名证书",