cert

package
v1.0.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2025 License: MIT, MIT Imports: 30 Imported by: 0

README

Cert 企业级软件授权管理解决方案

cert 包是一个功能完整的企业级软件授权管理解决方案,提供证书签发、验证、吊销以及可选的安全防护功能。专为需要软件许可控制的应用程序设计,默认开发友好,按需启用安全保护

🚀 主要特性

📜 证书管理
  • CA 证书生成:支持自定义 CA 证书和私钥管理
  • Ed25519 签名算法:使用现代高效的 Ed25519 椭圆曲线签名,提供高安全性和优异性能
  • 客户端证书签发:基于机器码的证书签发系统
  • 证书验证:完整的证书链验证和有效性检查
  • 证书吊销:动态吊销列表管理和实时更新
  • 批量处理:支持大规模证书批量签发和验证
🛡️ 安全防护(可选)
  • 分级保护:4 个安全级别,从禁用到关键防护
  • 反调试保护:多层次调试器检测和防护机制
  • 环境检测:虚拟机和沙箱环境识别
  • 进程保护:DLL 注入和代码注入检测
  • 时间篡改检测:系统时间验证和时钟偏差检查
  • 完整性验证:程序完整性校验和内存保护
  • 硬件绑定:基于机器码的硬件绑定验证
📊 授权管理
  • 版本控制:强制版本更新和兼容性管理
  • 有效期管理:灵活的证书生命周期控制
  • 授权管理:完整的客户信息和联系方式管理
  • 智能监控:自动监控证书状态,及时通知到期和异常事件
  • 缓存优化:智能缓存机制提升验证性能
  • 配置管理:灵活的配置系统支持多环境部署

📦 安装

go get github.com/darkit/machineid/cert

⚡ 快速开始

1. 创建授权管理器
import "github.com/darkit/machineid/cert"

// 开发环境(完全禁用安全检查,推荐)
auth, err := cert.ForDevelopment().Build()
if err != nil {
    log.Fatal("创建授权管理器失败:", err)
}

// 生产环境(基础安全检查)
prodAuth, err := cert.ForProduction().Build()

// 默认配置(禁用安全检查)
defaultAuth, err := cert.NewAuthorizer().Build()

// 自定义安全级别
customAuth, err := cert.NewAuthorizer().
    WithRuntimeVersion("2.0.0").
    WithSecurityLevel(2).                 // 高级安全保护
    WithMaxClockSkew(1 * time.Minute).
    Build()
2. 生成 CA 证书
caInfo := cert.CAInfo{
    CommonName:   "ZStudio Software",
    Organization: "子说软件工作室",
    Country:      "CN",
    Province:     "Guangdong",
    Locality:     "Guangzhou",
    ValidDays:    3650, // 10年有效期
}

// 生成新的CA证书
err := auth.GenerateCA(caInfo)
if err != nil {
    log.Fatal("生成CA证书失败:", err)
}

// 保存CA证书到指定目录
err = auth.SaveCA("./certificates")
3. 签发客户端证书
// 构建证书请求
bindingResult, _ := machineid.ProtectedIDResult("your.app.id")
req := &cert.ClientCertRequest{
    Identity: cert.Identity{
        MachineID:      bindingResult.Hash,
        BindingMode:    string(bindingResult.Mode),
        BindingProvider: bindingResult.Provider,
        ExpiryDate:     time.Now().AddDate(1, 0, 0), // 1年有效期
    },
    Company: cert.Company{
        Name:       "客户公司",
        Department: "技术部",
        Address: &cert.Address{
            Country:  "CN",
            Province: "广东省",
            City:     "深圳市",
            Street:   "科技园南路",
        },
    },
    Contact: &cert.Contact{
        Person: "张三",
        Phone:  "13800138000",
        Email:  "[email protected]",
    },
    Technical: cert.Technical{
        MinClientVersion:   "2.0.0",
        ValidityPeriodDays: 365,
    },
}

// 签发证书
certificate, err := auth.IssueClientCert(req)
if err != nil {
    log.Fatal("签发证书失败:", err)
}

// 保存客户端证书
err = auth.SaveClientCert(certificate, "./client-certificates")
4. 证书验证(可选安全检查)
// 证书验证(根据安全级别自动执行检查)
err := auth.ValidateCert(certificate.CertPEM, machineID)
if err != nil {
    switch {
    case cert.IsSecurityError(err):
        log.Printf("安全检查失败: %v", err)
        // 处理安全问题:调试器、虚拟机、沙箱等
        // 只有在启用安全检查时才会出现
    case cert.IsValidationError(err):
        log.Printf("证书验证失败: %v", err)
        // 处理证书问题:过期、吊销、机器码不匹配等
    default:
        log.Printf("其他错误: %v", err)
    }
    return
}

log.Println("证书验证成功")

// 手动执行安全检查
if err := auth.PerformSecurityCheck(); err != nil {
    log.Printf("手动安全检查失败: %v", err)
}
5. 客户信息提取
// 从现有证书中提取完整的客户信息
clientInfo, err := auth.ExtractClientInfo(certificate.CertPEM)
if err != nil {
    log.Fatal("提取客户信息失败:", err)
}

// 显示提取的信息
fmt.Printf("=== 客户授权信息 ===\n")
fmt.Printf("机器ID: %s\n", clientInfo.MachineID)
fmt.Printf("公司名称: %s\n", clientInfo.CompanyName)
fmt.Printf("部门: %s\n", clientInfo.Department)
fmt.Printf("联系人: %s\n", clientInfo.ContactPerson)
fmt.Printf("联系电话: %s\n", clientInfo.ContactPhone)
fmt.Printf("联系邮箱: %s\n", clientInfo.ContactEmail)
fmt.Printf("绑定模式: %s\n", clientInfo.BindingMode)
fmt.Printf("绑定提供者: %s\n", clientInfo.BindingProvider)
fmt.Printf("最低客户端版本: %s\n", clientInfo.MinClientVersion)
fmt.Printf("证书有效期: %d天\n", clientInfo.ValidityPeriodDays)
fmt.Printf("到期时间: %s\n", clientInfo.ExpiryDate.Format("2006-01-02 15:04:05"))

// 应用场景示例
// 1. 客户管理 - 快速获取授权客户联系信息
// 2. 技术支持 - 了解客户使用的软件版本
// 3. 许可审计 - 生成授权使用报告
// 4. 合规检查 - 验证授权分发记录
6. 授权监控回调

系统提供了智能的授权监控机制,自动定期检查证书状态,并通过回调通知上层应用:

// 定义监控回调函数
watchCallback := func(event cert.WatchEvent, clientInfo *cert.ClientInfo, err error) {
    switch event {
    case cert.WatchEventExpiring:
        log.Printf("警告: 证书即将到期 - %s (%s)",
            clientInfo.CompanyName, clientInfo.ContactPerson)
        // 发送邮件通知、触发续期流程等
        sendRenewalNotification(clientInfo)

    case cert.WatchEventExpired:
        log.Printf("紧急: 证书已过期 - %s", clientInfo.CompanyName)
        // 停止服务、显示过期提示等
        handleExpiredLicense(clientInfo)

    case cert.WatchEventInvalid:
        log.Printf("错误: 证书无效 - %v", err)
        // 重新验证、联系支持等
        handleInvalidCertificate(err)

    case cert.WatchEventRevoked:
        log.Printf("严重: 证书已被吊销 - %s", clientInfo.CompanyName)
        // 立即停止服务、安全审计等
        handleRevokedCertificate(clientInfo)
    }
}

// 启动监控 - 使用默认配置(1小时检查间隔,7天预警期)
watcher, err := auth.Watch(certPEM, machineID, watchCallback)

// 自定义监控间隔和预警期
watcher, err := auth.Watch(certPEM, machineID, watchCallback,
    30*time.Minute,  // 30分钟检查一次
    3*24*time.Hour)  // 3天到期预警

// 高级配置监控
watcher := cert.NewCertWatcher(auth, certPEM, machineID, watchCallback).
    WithCheckInterval(10 * time.Minute).     // 检查间隔
    WithExpiryWarning(24 * time.Hour).       // 预警期
    WithConfig(&cert.WatchConfig{
        EnableRevocationCheck: true,         // 启用吊销检查
        MaxRetries:           5,             // 最大重试次数
        RetryInterval:        2 * time.Minute, // 重试间隔
    })

if err := watcher.Start(); err != nil {
    log.Fatal("启动监控失败:", err)
}

// 获取监控统计
stats := watcher.Stats()
fmt.Printf("检查次数: %v, 运行状态: %v\n",
    stats["check_count"], stats["is_running"])

// 停止监控
watcher.Stop()
监控管理器 - 管理多个证书
// 创建监控管理器
manager := cert.NewWatcherManager()

// 添加多个证书监控
watcher1, _ := auth.Watch(cert1PEM, machineID1, callback, time.Hour)
watcher2, _ := auth.Watch(cert2PEM, machineID2, callback, 30*time.Minute)

manager.AddWatcher("license1", watcher1)
manager.AddWatcher("license2", watcher2)

// 获取所有监控统计
allStats := manager.AllStats()
for id, stats := range allStats {
    fmt.Printf("%s: 检查%v次, 运行中=%v\n",
        id, stats["check_count"], stats["is_running"])
}

// 停止所有监控
manager.StopAll()
监控事件类型
事件 触发条件 建议处理
WatchEventExpiring 距离到期时间小于预警期 发送续期提醒,准备新证书
WatchEventExpired 证书已过期 停止服务或显示过期提示
WatchEventInvalid 证书格式错误或验证失败 检查证书文件,联系技术支持
WatchEventRevoked 证书被加入吊销列表 立即停止服务,进行安全审计
默认监控配置
// 系统默认配置
config := cert.DefaultWatchConfig()
// CheckInterval: 1小时
// ExpiryWarningPeriod: 7天
// EnableExpiryWarning: true
// EnableRevocationCheck: true
// MaxRetries: 3次
// RetryInterval: 5分钟
7. 证书吊销管理
// 创建吊销管理器
revokeManager, err := cert.NewRevokeManager("1.0.0")

// 吊销特定证书
err = revokeManager.RevokeCertificate("证书序列号", "security_breach")

// 检查证书是否被吊销
isRevoked, reason := revokeManager.IsRevoked("证书序列号")

// 使用动态吊销列表
auth, err := cert.NewAuthorizer().
    WithRevokeListUpdater(func() ([]byte, error) {
        // 从远程API获取最新吊销列表
        resp, err := http.Get("https://api.example.com/revoke-list")
        if err != nil {
            return nil, err
        }
        defer resp.Body.Close()
        return io.ReadAll(resp.Body)
    }).
    Build()

🛡️ 安全级别系统

安全级别概览

系统提供 4 个可选的安全级别,默认完全禁用以确保开发友好:

级别 名称 检测项 性能影响 适用场景
0 禁用 无检测 开发、调试(默认)
1 基础 简单调试器检测 极小 生产环境
2 高级 完整反逆向保护 高价值软件
3 关键 最严格检查+进程保护 中等 关键系统
配置方式
// 方式1: 使用预设配置
devAuth := cert.ForDevelopment().Build()    // 级别0 (默认)
prodAuth := cert.ForProduction().Build()    // 级别1
testAuth := cert.ForTesting().Build()       // 级别0

// 方式2: 显式设置安全级别
auth := cert.NewAuthorizer().
    WithSecurityLevel(0).Build()            // 禁用所有安全检查
auth := cert.NewAuthorizer().
    WithSecurityLevel(2).Build()            // 高级安全保护

// 方式3: 便捷配置方法
auth := cert.NewAuthorizer().DisableSecurity().Build()      // 级别0
auth := cert.NewAuthorizer().WithBasicSecurity().Build()    // 级别1
auth := cert.NewAuthorizer().WithSecureDefaults().Build()   // 级别2
auth := cert.NewAuthorizer().WithCriticalSecurity().Build() // 级别3
各级别详细功能
🔓 级别 0:完全禁用(默认推荐)
auth := cert.ForDevelopment().Build()
// 或
auth := cert.NewAuthorizer().Build() // 默认就是级别0
  • 检测项: 无
  • 性能: 无影响
  • 用途: 开发、调试、测试
  • 特点: 完全无干扰,专注于业务逻辑开发
🛡️ 级别 1:基础防护
auth := cert.ForProduction().Build()
  • 检测项: 基础调试器检测(IsDebuggerPresent、TracerPid 等)
  • 性能: 极小影响(~1-2ms)
  • 用途: 生产环境基础保护
  • 特点: 兼容性好,检测常见调试器
🛡️ 级别 2:高级防护
auth := cert.NewAuthorizer().WithSecureDefaults().Build()
  • 检测项:
    • 高级调试器检测(时间攻击、API 监控)
    • 虚拟机环境检测(VMware、VirtualBox 等)
    • 沙箱环境检测(Cuckoo、Joe Sandbox 等)
  • 性能: 小影响(~5-10ms)
  • 用途: 高价值软件保护
  • 特点: 全面的反逆向分析保护
🔒 级别 3:关键防护
auth := cert.NewAuthorizer().WithCriticalSecurity().Build()
  • 检测项:
    • 所有级别 2 的检测项
    • 进程保护(DLL 注入、代码注入检测)
    • 内存保护(关键数据加密)
    • 系统调用监控
  • 性能: 中等影响(~10-20ms)
  • 用途: 关键系统、军工软件
  • 特点: 最严格的安全检查,不允许任何分析
反调试技术详解
🔓 级别 0 - 完全禁用(默认)
auth := cert.NewAuthorizer().Build() // 默认级别0
// 或显式设置
auth := cert.NewAuthorizer().WithSecurityLevel(0).Build()
  • 检测项: 无任何检测
  • 性能开销: 0ms
  • 适用场景: 开发、调试、单元测试
  • 特点: 完全无干扰,专注业务逻辑开发
🛡️ 级别 1 - 基础防护
auth := cert.ForProduction().Build() // 自动设为级别1
// 或手动设置
auth := cert.NewAuthorizer().WithBasicSecurity().Build()

Windows 平台检测

  • IsDebuggerPresent() - 检测调试器存在
  • PEB 结构检查 - 验证BeingDebugged标志
  • 调试堆检测 - 检查堆标志异常

Linux 平台检测

  • TracerPid 检查 - 读取/proc/self/status中的跟踪进程
  • 调试器进程扫描 - 检查gdblldb等进程

macOS 平台检测

  • P_TRACED 状态 - 通过sysctl检查进程跟踪状态
  • 调试器进程检测 - 扫描常见调试工具

性能开销: 1-2ms,适合生产环境

🛡️ 级别 2 - 高级防护
auth := cert.NewAuthorizer().WithSecureDefaults().Build()

高级反调试技术

  • 时间差攻击检测 - 测量指令执行时间,检测单步调试
  • 调试端口检查 - 通过NtQueryInformationProcess检查调试端口(Windows)
  • 异常处理检测 - 利用异常处理机制检测调试器
  • 硬件断点检测 - 检查调试寄存器DR0-DR7

虚拟机检测

  • VMware 检测 - 检查 VMware 特有设备和服务
  • VirtualBox 检测 - 查找 VBOX 相关注册表项和文件
  • Hyper-V 检测 - 检测 Microsoft 虚拟化标志
  • QEMU 检测 - 识别 QEMU/KVM 环境特征

沙箱检测

  • Cuckoo Sandbox - 检测 Cuckoo 特有的文件和注册表
  • Joe Sandbox - 识别 Joe 分析环境
  • Anubis 检测 - 检查 Anubis 恶意软件分析平台

性能开销: 5-10ms,适合高价值软件保护

🔒 级别 3 - 关键防护
auth := cert.NewAuthorizer().WithCriticalSecurity().Build()

进程保护技术

  • DLL 注入检测 - 监控异常的内存映射和模块加载
  • 代码注入检测 - 检查可执行区域的异常变化
  • 内存布局分析 - 检测内存映射异常
  • API Hook 检测 - 识别 API 拦截和重定向

内存保护机制

  • 关键数据加密 - 使用 XOR 等算法加密敏感内存区域
  • 内存权限控制 - 动态设置关键区域访问权限
  • 数据完整性校验 - 定期校验关键数据完整性
  • 内存清理 - 程序退出时安全清理敏感数据

系统监控

  • 系统调用监控 - 检测异常的系统调用模式
  • 文件系统监控 - 监控敏感文件访问
  • 网络行为分析 - 检测异常网络通信

性能开销: 10-20ms,适合关键系统和军工软件

检测技术分类说明
调试器检测
技术 级别 平台 描述
IsDebuggerPresent 1+ Windows 最基础的调试器检测 API
PEB 检查 1+ Windows 检查进程环境块中的调试标志
TracerPid 1+ Linux 检查进程跟踪状态
P_TRACED 1+ macOS 检查进程跟踪标志
时间差攻击 2+ 全平台 通过执行时间检测单步调试
调试端口检查 2+ Windows 通过 NT API 检查调试端口
异常处理检测 2+ Windows 利用结构化异常处理检测
硬件断点检测 2+ x86/x64 检查调试寄存器状态
环境检测
环境类型 检测级别 检测方法
VMware 2+ 注册表项、设备名称、MAC 地址前缀
VirtualBox 2+ 注册表项、文件系统、设备枚举
Hyper-V 2+ 系统信息、特殊标志位
QEMU/KVM 2+ CPUID 指令、设备信息
Cuckoo 沙箱 2+ 特有文件、注册表、网络配置
Joe 沙箱 2+ 环境变量、文件系统特征
环境检测技术
虚拟机检测
  • VMware: 检测 VMware 特有设备和注册表
  • VirtualBox: 检查 VBOX 相关特征
  • Hyper-V: 检测 Microsoft 虚拟化标志
  • QEMU: 检查 QEMU/KVM 环境特征
沙箱检测
  • Cuckoo Sandbox: 检测 Cuckoo 特有的文件和环境
  • Joe Sandbox: 检查 Joe 分析环境特征
  • Anubis: 检测 Anubis 恶意软件分析环境
进程保护技术
注入检测
  • DLL 注入: 监控异常的内存映射和模块加载
  • 代码注入: 检查可执行区域的异常变化
  • 内存布局: 分析内存布局异常
内存保护
  • 关键数据加密: 使用 XOR 加密保护敏感内存
  • 内存权限: 设置关键区域为只读
  • 数据清理: 程序退出时清理敏感数据

📋 配置管理

环境预设配置
// 开发环境(完全禁用安全检查)
devAuth := cert.ForDevelopment() // SecurityLevel=0

// 测试环境(禁用安全检查)
testAuth := cert.ForTesting()    // SecurityLevel=0

// 生产环境(基础安全检查)
prodAuth := cert.ForProduction() // SecurityLevel=1
自定义安全配置
// 完全禁用安全检查(推荐用于开发)
auth := cert.NewAuthorizer().
    DisableSecurity().
    Build()

// 高级安全配置(高价值软件)
auth := cert.NewAuthorizer().
    WithSecureDefaults().         // SecurityLevel=2
    WithMaxClockSkew(time.Minute).
    WithCacheTTL(time.Minute * 10).
    Build()

// 关键安全配置(最高级别)
auth := cert.NewAuthorizer().
    WithCriticalSecurity().       // SecurityLevel=3
    Build()

// 显式设置安全级别
auth := cert.NewAuthorizer().
    WithSecurityLevel(1).         // 基础安全级别
    EnableTimeValidation(true).
    Build()
配置文件支持
# config.yaml
version: "2.0.0"
enterprise_id: 62996
security:
  enable_anti_debug: true
  enable_time_validation: true
  require_hardware_binding: true
  max_clock_skew: "5m"
cache:
  ttl: "10m"
  max_size: 5000
  cleanup_interval: "30m"

🔧 高级功能

批量证书处理
// 创建批量管理器
batchManager := cert.NewBatchManager(auth)

// 批量签发证书
requests := []*cert.ClientCertRequest{ /* ... */ }
results := batchManager.IssueMultipleCerts(requests)

// 批量验证证书
validations := []cert.CertValidation{ /* ... */ }
validationResults := batchManager.ValidateMultipleCerts(validations)
缓存优化
// 方式1:通过 Builder 创建带缓存的授权管理器
cachedAuth, err := cert.NewAuthorizer().
    WithCacheConfig(cert.CacheConfig{
        TTL:             10 * time.Minute,
        MaxSize:         1000,
        CleanupInterval: 5 * time.Minute,
    }).
    BuildWithCache()

// 方式2:为现有授权管理器添加缓存
auth, _ := cert.NewAuthorizer().Build()
cachedAuth := auth.WithCache()

// 验证会自动使用缓存
err := cachedAuth.ValidateCert(certPEM, machineID)

// 查看缓存统计
stats := cachedAuth.CacheStats()
fmt.Printf("命中率: %.2f%%\n", cachedAuth.CacheHitRate()*100)

// 清空缓存
cachedAuth.ClearCache()
模板系统
// 创建模板管理器
templateMgr := cert.NewTemplateManager()

// 使用预定义模板
template, _ := templateMgr.Template("enterprise")
fmt.Printf("有效期: %d天\n", template.ValidityDays)

// 添加自定义模板
customTemplate := &cert.CertTemplate{
    Name:           "自定义模板",
    Description:    "适用于特殊场景",
    ValidityDays:   730, // 2年
    SecurityLevel:  cert.TemplateSecurityLevelHigh,
    RequiredFields: []string{"MachineID", "CompanyName"},
}
templateMgr.AddTemplate("custom", customTemplate)

// 使用模板验证请求
err := templateMgr.ValidateRequestWithTemplate(req, "enterprise")

// 应用模板到请求
err = templateMgr.ApplyTemplate(req, "enterprise")

📊 错误处理

系统提供详细的错误分类和处理建议:

err := auth.ValidateCert(certPEM, machineID)
if err != nil {
    if certErr, ok := err.(*cert.CertError); ok {
        fmt.Printf("错误类别: %d\n", certErr.ErrorType())
        fmt.Printf("错误代码: %s\n", certErr.ErrorCode())
        fmt.Printf("错误详情: %v\n", certErr.ErrorDetails())
        fmt.Printf("解决建议: %v\n", certErr.ErrorSuggestions())
    }
}
错误类型
  • ValidationError: 证书验证错误(格式、过期等)
  • SecurityError: 安全检查错误(调试器、沙箱等)
  • ConfigError: 配置错误(CA 缺失、参数无效等)
  • SystemError: 系统错误(时钟偏差、文件系统等)

🔍 监控和日志

安全事件监控
// 初始化安全管理器
sm := auth.InitSecurityManager()

// 监控安全事件(自动记录)
// [SECURITY] 2024-01-20 15:30:45: Virtual machine environment detected
// [SECURITY] 2024-01-20 15:30:46: Defense measures activated
缓存统计
// 获取缓存授权管理器
cachedAuth := auth.WithCache()

// 获取缓存统计信息
stats := cachedAuth.CacheStats()
fmt.Printf("缓存命中: %d\n", stats.Hits)
fmt.Printf("缓存未命中: %d\n", stats.Misses)
fmt.Printf("命中率: %.2f%%\n", cachedAuth.CacheHitRate()*100)

🏗️ 系统集成

Web API 集成
func validateLicenseHandler(w http.ResponseWriter, r *http.Request) {
    certData := r.Header.Get("X-License-Cert")
    machineID := r.Header.Get("X-Machine-ID")

    // 推荐:优先验证 license 文件(Ed25519),轻量且离线可验
    // publicKeyPEM 应由服务端下发/配置,或在客户端内置
    // pub, _ := cert.ParseEd25519PublicKeyPEM(publicKeyPEM)
    // // machineID 推荐传 machineid.ProtectedIDResult(appID).Hash(而非原始 machine-id)
    // // binding, _ := machineid.ProtectedIDResult(appID)
    // // machineID := binding.Hash
    // if _, err := cert.ValidateLicenseJSON([]byte(certData), pub, machineID, time.Now().UTC()); err != nil {
    //     http.Error(w, "License validation failed", 403)
    //     return
    // }
    //
    // 如仍使用证书作为授权载体,可继续走 ValidateCert
    if err := auth.ValidateCert([]byte(certData), machineID); err != nil {
        http.Error(w, "License validation failed", 403)
        return
    }

    w.WriteHeader(200)
    json.NewEncoder(w).Encode(map[string]string{"status": "valid"})
}
gRPC 服务
service LicenseService {
    rpc ValidateLicense(ValidateRequest) returns (ValidateResponse);
    rpc IssueLicense(IssueRequest) returns (IssueResponse);
    rpc RevokeLicense(RevokeRequest) returns (RevokeResponse);
}

🚀 性能优化

最佳实践
  1. 使用缓存: 启用证书验证缓存减少重复计算
  2. 批量处理: 大规模证书操作使用批量 API
  3. 异步更新: 吊销列表和配置使用异步更新
  4. 连接池: 网络请求使用连接池复用
  5. 内存管理: 及时清理不需要的证书数据
性能指标
  • 证书验证: ~1-5ms(缓存命中)
  • 证书签发: ~10-50ms
  • 安全检查: ~5-20ms
  • 批量处理: 1000 个证书/秒

📋 部署指南

生产环境部署
// 生产环境推荐配置
auth := cert.ForProduction().
    WithCA(prodCACert, prodCAKey).      // 使用生产CA
    WithCacheTTL(30 * time.Minute).     // 适中的缓存时间
    WithMaxClockSkew(1 * time.Minute).  // 严格的时间检查
    Build()

⚠️ 重要安全说明

CA 私钥保护

CA 私钥是整个系统的核心,必须严格保护:

  • 加密存储: 使用硬件安全模块(HSM)或加密文件系统
  • 访问控制: 限制访问权限,使用最小权限原则
  • 备份策略: 安全的密钥备份和恢复机制
  • 定期轮换: 定期更换 CA 密钥(建议 2-5 年)
  • 审计日志: 记录所有密钥使用操作
安全最佳实践
  1. 网络安全: 使用 HTTPS 传输证书和验证请求
  2. 存储安全: 加密存储敏感配置和密钥文件
  3. 访问控制: 实施严格的身份认证和授权
  4. 监控告警: 部署安全事件监控和异常告警
  5. 应急响应: 建立证书泄露应急处理流程

🔧 故障排除

常见问题
证书验证失败
# 检查系统时间
ntpdate -s time.nist.gov

# 检查证书有效期
openssl x509 -in certificate.pem -noout -dates

# 检查机器码匹配
echo "当前机器码: $(go run -tags=cert ./cmd/get-machine-id)"
安全检查失败
// 临时禁用安全检查(仅用于调试)
devAuth := cert.ForDevelopment().Build() // EnableAntiDebug=false

// 或检查具体安全问题
if err := auth.PerformSecurityCheck(); err != nil {
    fmt.Printf("安全检查详情: %v\n", err)
}

📖 API 文档

完整的 API 文档请参阅:

🔄 版本兼容性

  • Go 版本: 需要 Go 1.19+
  • 平台支持: Windows, Linux, macOS
  • 架构支持: amd64, arm64, 386

📄 许可证

本项目采用 MIT 许可证。详情请参阅 LICENSE 文件。

🤝 贡献指南

欢迎贡献代码!请遵循以下步骤:

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送分支 (git push origin feature/AmazingFeature)
  5. 创建 Pull Request
开发环境设置
# 克隆代码
git clone https://github.com/darkit/machineid.git
cd machineid/cert

# 运行测试
go test -v ./...

# 运行示例
go run examples.go

📞 支持

如果您遇到问题或需要帮助:


注意: 本解决方案专为合法的软件授权管理设计,请遵守当地法律法规,不得用于恶意目的。

Documentation

Index

Constants

View Source
const (
	SecurityLevelDisabled = 0 // 完全禁用(默认)
	SecurityLevelBasic    = 1 // 基础防护(仅基本调试器检测)
	SecurityLevelAdvanced = 2 // 高级防护(完整反逆向保护)
	SecurityLevelCritical = 3 // 关键防护(最高级别保护)
)

SecurityLevel 安全防护级别

View Source
const (
	// SnapshotVersion 当前快照格式版本
	SnapshotVersion = 1

	// DefaultSnapshotValidity 默认快照有效期(90天)
	DefaultSnapshotValidity = 90 * 24 * time.Hour
)

Variables

This section is empty.

Functions

func ApplyTemplateToRequest added in v1.0.6

func ApplyTemplateToRequest(req *ClientCertRequest, templateName string) error

ApplyTemplateToRequest 将模板应用到证书请求

func CanonicalPayload added in v1.0.9

func CanonicalPayload(payload LicensePayload) ([]byte, error)

CanonicalPayload 返回用于签名/验签的稳定 JSON 表示。

func DecodeObfuscated added in v1.0.9

func DecodeObfuscated(encoded string, key byte) (string, error)

DecodeObfuscated 从 Base64 解码。

func DemoSecurityCheck added in v1.0.6

func DemoSecurityCheck()

DemoSecurityCheck 演示安全检查过程

func DemoSecurityConfiguration added in v1.0.6

func DemoSecurityConfiguration()

DemoSecurityConfiguration 演示不同配置方式

func DemoSecurityFeatures added in v1.0.6

func DemoSecurityFeatures()

DemoSecurityFeatures 演示安全功能

func DemoSecurityLevels added in v1.0.6

func DemoSecurityLevels()

DemoSecurityLevels 演示不同安全级别

func DemonstrateKeySizeDetection added in v1.0.7

func DemonstrateKeySizeDetection()

DemonstrateKeySizeDetection 演示密钥大小识别功能

func Example10_ExtractClientInfo added in v1.0.6

func Example10_ExtractClientInfo()

Example10_ExtractClientInfo 客户信息提取示例

func Example11_CertificateWatching added in v1.0.6

func Example11_CertificateWatching()

Example11_CertificateWatching 证书监控示例

func Example1_BasicUsage added in v1.0.6

func Example1_BasicUsage()

Example1_BasicUsage 基本使用示例

func Example2_WithCache added in v1.0.6

func Example2_WithCache()

Example2_WithCache 使用缓存的示例

func Example3_BatchOperations added in v1.0.6

func Example3_BatchOperations()

Example3_BatchOperations 批量操作示例

func Example4_ConfigurationFile added in v1.0.6

func Example4_ConfigurationFile()

Example4_ConfigurationFile 配置文件示例

func Example5_PresetConfigurations added in v1.0.6

func Example5_PresetConfigurations()

Example5_PresetConfigurations 预设配置示例

func Example6_CertificateInspection added in v1.0.6

func Example6_CertificateInspection()

Example6_CertificateInspection 证书检查示例

func Example7_PerformanceMonitoring added in v1.0.6

func Example7_PerformanceMonitoring()

Example7_PerformanceMonitoring 性能监控示例

func Example8_ErrorHandling added in v1.0.6

func Example8_ErrorHandling()

Example8_ErrorHandling 错误处理示例

func Example9_SystemInfoCollection added in v1.0.6

func Example9_SystemInfoCollection()

Example9_SystemInfoCollection 系统信息收集示例

func FormatDuration added in v1.0.6

func FormatDuration(d time.Duration) string

FormatDuration 格式化时长显示

func FormatFileSize added in v1.0.6

func FormatFileSize(bytes int64) string

FormatFileSize 格式化文件大小

func GenerateDefaultConfig added in v1.0.6

func GenerateDefaultConfig(filePath string) error

GenerateDefaultConfig 生成默认配置文件

func GenerateLicenseKeyPairPEM added in v1.0.9

func GenerateLicenseKeyPairPEM() (publicKeyPEM, privateKeyPEM []byte, err error)

GenerateLicenseKeyPairPEM 生成 Ed25519 license key pair(PKCS#8 PEM)。

func GetDebuggerString added in v1.0.9

func GetDebuggerString() string

GetDebuggerString 获取 "debugger" 字符串。

func GetTraceString added in v1.0.9

func GetTraceString() string

GetTraceString 获取 "trace" 字符串。

func IsConfigError added in v1.0.6

func IsConfigError(err error) bool

IsConfigError 检查是否为配置错误

func IsSecurityError added in v1.0.6

func IsSecurityError(err error) bool

IsSecurityError 检查是否为安全错误

func IsValidMachineID added in v1.0.6

func IsValidMachineID(machineID string) bool

IsValidMachineID 验证机器ID格式

func IsValidationError added in v1.0.6

func IsValidationError(err error) bool

IsValidationError 检查是否为验证错误

func IssueLicense added in v1.0.9

func IssueLicense(payload LicensePayload, privateKey ed25519.PrivateKey) ([]byte, error)

IssueLicense 使用 Ed25519 私钥签发 license(返回 JSON)。

func ParseEd25519PrivateKeyPEM added in v1.0.9

func ParseEd25519PrivateKeyPEM(privateKeyPEM []byte) (ed25519.PrivateKey, error)

func ParseEd25519PublicKeyPEM added in v1.0.9

func ParseEd25519PublicKeyPEM(publicKeyPEM []byte) (ed25519.PublicKey, error)

func RunSecurityDemo added in v1.0.6

func RunSecurityDemo()

RunSecurityDemo 运行完整的安全功能演示

func SaveConfig added in v1.0.6

func SaveConfig(config *ConfigFile, filePath string) error

SaveConfig 保存配置到文件

func ShowSecurityConfig added in v1.0.6

func ShowSecurityConfig()

ShowSecurityConfig 显示安全配置

func ShowUsageExamples added in v1.0.6

func ShowUsageExamples()

ShowUsageExamples 显示使用示例

func TestSecurityLevels added in v1.0.6

func TestSecurityLevels()

TestSecurityLevels 测试安全级别配置

func ValidateEmail added in v1.0.6

func ValidateEmail(email string) bool

ValidateEmail 验证邮箱格式

func ValidatePhoneNumber added in v1.0.6

func ValidatePhoneNumber(phone string) bool

ValidatePhoneNumber 验证电话号码格式

func ValidateRequestWithGlobalTemplate added in v1.0.6

func ValidateRequestWithGlobalTemplate(req *ClientCertRequest, templateName string) error

ValidateRequestWithGlobalTemplate 使用全局模板验证请求

func VerifySnapshot added in v1.0.9

func VerifySnapshot(snapshot *HardwareSnapshot, appID string, allowedDeviation float64) error

VerifySnapshot 验证硬件快照

参数:

  • appID: 应用标识符
  • allowedDeviation: 允许的硬件变化偏差(0.0-1.0,例如 0.2 表示允许 20% 的硬件变化)

返回错误(nil 表示验证通过)

Types

type Address added in v1.0.6

type Address struct {
	Country  string // 国家
	Province string // 省份
	City     string // 城市
	Street   string // 详细地址
}

Address 地址信息

type Authorizer

type Authorizer struct {
	// contains filtered or unexported fields
}

重新定义 Authorizer 结构体

func New

func New(opts ...func(*Authorizer) error) (*Authorizer, error)

New 创建新的授权管理器(向后兼容) Deprecated: 使用 NewAuthorizer().Build() 代替

func (*Authorizer) CACertPEM added in v1.0.9

func (a *Authorizer) CACertPEM() []byte

CACertPEM 获取PEM格式的CA证书

func (*Authorizer) Config added in v1.0.9

func (a *Authorizer) Config() AuthorizerConfig

Config 获取配置(用于调试和监控)

func (*Authorizer) ExtractClientInfo added in v1.0.6

func (a *Authorizer) ExtractClientInfo(certPEM []byte) (*ClientInfo, error)

ExtractClientInfo 从证书中提取客户信息

func (*Authorizer) GenerateCA

func (a *Authorizer) GenerateCA(info CAInfo) error

GenerateCA 生成新的CA证书和私钥,并更新授权管理器

func (*Authorizer) GetCurrentCertVersion added in v1.0.9

func (a *Authorizer) GetCurrentCertVersion() string

GetCurrentCertVersion 获取当前证书格式版本

func (*Authorizer) GetSecurityLevel added in v1.0.9

func (a *Authorizer) GetSecurityLevel() int

GetSecurityLevel 根据配置获取安全级别

func (*Authorizer) InitSecurityManager added in v1.0.6

func (a *Authorizer) InitSecurityManager() *SecurityManager

InitSecurityManager 初始化安全管理器并集成到授权管理器

func (*Authorizer) IssueClientCert

func (a *Authorizer) IssueClientCert(req *ClientCertRequest) (*Certificate, error)

IssueClientCert 签发客户端证书

func (*Authorizer) NewBatchIssue added in v1.0.6

func (a *Authorizer) NewBatchIssue() *BatchIssueBuilder

NewBatchIssue 创建批量签发构建器

func (*Authorizer) NewBatchManager added in v1.0.6

func (a *Authorizer) NewBatchManager() *BatchManager

NewBatchManager 创建批量操作管理器

func (*Authorizer) NewBatchValidate added in v1.0.6

func (a *Authorizer) NewBatchValidate() *BatchValidateBuilder

NewBatchValidate 创建批量验证构建器

func (*Authorizer) PerformSecurityCheck added in v1.0.6

func (a *Authorizer) PerformSecurityCheck() error

PerformSecurityCheck 执行安全检查(集成到证书验证流程)

func (*Authorizer) SaveCA

func (a *Authorizer) SaveCA(dirPath ...string) error

SaveCA 保存CA证书到指定目录,如果不指定目录则使用当前工作目录

func (*Authorizer) SaveClientCert

func (a *Authorizer) SaveClientCert(cert *Certificate, dirPath ...string) error

SaveClientCert 保存客户端证书到指定目录,如果不指定目录则使用当前工作目录 证书文件格式:{机器码}-{生效时间}-{结束时间}.crt

func (*Authorizer) SetCurrentCertVersion added in v1.0.4

func (a *Authorizer) SetCurrentCertVersion(version string)

SetCurrentCertVersion 设置当前证书格式版本

func (*Authorizer) ValidateCert

func (a *Authorizer) ValidateCert(certPEM []byte, machineID string) error

ValidateCert 验证客户端证书

func (*Authorizer) ValidateWithSecurity added in v1.0.6

func (a *Authorizer) ValidateWithSecurity(certPEM []byte, machineID string) error

ValidateWithSecurity 带安全检查的证书验证

func (*Authorizer) Watch added in v1.0.6

func (a *Authorizer) Watch(certPEM []byte, machineID string, callback WatchCallback, intervals ...time.Duration) (*CertWatcher, error)

Watch 是Authorizer的便捷方法,用于启动证书监控

func (*Authorizer) WithCache added in v1.0.6

func (a *Authorizer) WithCache() *CachedAuthorizer

WithCache 为授权器添加缓存功能

type AuthorizerBuilder added in v1.0.6

type AuthorizerBuilder struct {
	// contains filtered or unexported fields
}

AuthorizerBuilder 授权管理器构建器

func ForDevelopment added in v1.0.6

func ForDevelopment() *AuthorizerBuilder

ForDevelopment 开发环境预设(完全禁用安全检查)

func ForProduction added in v1.0.6

func ForProduction() *AuthorizerBuilder

ForProduction 生产环境预设(基础安全检查)

func ForTesting added in v1.0.6

func ForTesting() *AuthorizerBuilder

ForTesting 测试环境预设(禁用安全检查)

func FromConfigFile added in v1.0.6

func FromConfigFile(filePath string) (*AuthorizerBuilder, error)

FromConfigFile 从配置文件创建授权管理器构建器

func NewAuthorizer added in v1.0.6

func NewAuthorizer() *AuthorizerBuilder

NewAuthorizer 创建新的授权管理器构建器

func (*AuthorizerBuilder) Apply added in v1.0.9

func (b *AuthorizerBuilder) Apply(opts ...Option) *AuthorizerBuilder

Apply 应用多个配置选项

使用示例:

auth, err := NewAuthorizer().
    WithRuntimeVersion("1.0.0").
    Apply(
        WithHardwareBinding(machineid.BindingModeFingerprint),
        WithContainerSupport(&ContainerBindingConfig{
            Mode: machineid.ContainerBindingAuto,
        }),
        WithOfflineValidation("./snapshots"),
    ).
    Build()

func (*AuthorizerBuilder) Build added in v1.0.6

func (b *AuthorizerBuilder) Build() (*Authorizer, error)

Build 构建授权管理器

func (*AuthorizerBuilder) BuildWithCache added in v1.0.6

func (b *AuthorizerBuilder) BuildWithCache() (*CachedAuthorizer, error)

WithCache 构建带缓存的授权器

func (*AuthorizerBuilder) DisableSecurity added in v1.0.6

func (b *AuthorizerBuilder) DisableSecurity() *AuthorizerBuilder

DisableSecurity 完全禁用安全检查

func (*AuthorizerBuilder) EnableAntiDebug added in v1.0.6

func (b *AuthorizerBuilder) EnableAntiDebug(enable bool) *AuthorizerBuilder

EnableAntiDebug 启用反调试

func (*AuthorizerBuilder) EnableTimeValidation added in v1.0.6

func (b *AuthorizerBuilder) EnableTimeValidation(enable bool) *AuthorizerBuilder

EnableTimeValidation 启用时间验证

func (*AuthorizerBuilder) RequireHardwareBinding added in v1.0.6

func (b *AuthorizerBuilder) RequireHardwareBinding(require bool) *AuthorizerBuilder

RequireHardwareBinding 要求硬件绑定

func (*AuthorizerBuilder) UseCustomCA added in v1.0.6

func (b *AuthorizerBuilder) UseCustomCA(cert, key []byte) *AuthorizerBuilder

UseCustomCA 使用自定义CA配置

func (*AuthorizerBuilder) UseDefaultCA added in v1.0.6

func (b *AuthorizerBuilder) UseDefaultCA() *AuthorizerBuilder

UseDefaultCA 使用默认CA配置

func (*AuthorizerBuilder) WithBasicSecurity added in v1.0.6

func (b *AuthorizerBuilder) WithBasicSecurity() *AuthorizerBuilder

WithBasicSecurity 使用基础安全配置

func (*AuthorizerBuilder) WithCA added in v1.0.6

func (b *AuthorizerBuilder) WithCA(cert, key []byte) *AuthorizerBuilder

WithCA 设置自定义CA证书和私钥

func (*AuthorizerBuilder) WithCache added in v1.0.6

func (b *AuthorizerBuilder) WithCache(cache CacheConfig) *AuthorizerBuilder

WithCache 设置缓存配置

func (*AuthorizerBuilder) WithCacheConfig added in v1.0.6

func (b *AuthorizerBuilder) WithCacheConfig(config CacheConfig) *AuthorizerBuilder

添加缓存配置构建器方法

func (*AuthorizerBuilder) WithCacheSize added in v1.0.6

func (b *AuthorizerBuilder) WithCacheSize(size int) *AuthorizerBuilder

WithCacheSize 设置缓存大小

func (*AuthorizerBuilder) WithCacheTTL added in v1.0.6

func (b *AuthorizerBuilder) WithCacheTTL(ttl time.Duration) *AuthorizerBuilder

WithCacheTTL 设置缓存有效期

func (*AuthorizerBuilder) WithCriticalSecurity added in v1.0.6

func (b *AuthorizerBuilder) WithCriticalSecurity() *AuthorizerBuilder

WithCriticalSecurity 使用关键安全配置(最高安全级别)

func (*AuthorizerBuilder) WithEnterpriseID added in v1.0.6

func (b *AuthorizerBuilder) WithEnterpriseID(id int) *AuthorizerBuilder

WithEnterpriseID 设置企业标识符

func (*AuthorizerBuilder) WithMaxClockSkew added in v1.0.6

func (b *AuthorizerBuilder) WithMaxClockSkew(skew time.Duration) *AuthorizerBuilder

WithMaxClockSkew 设置最大时钟偏差

func (*AuthorizerBuilder) WithRelaxedSecurity added in v1.0.6

func (b *AuthorizerBuilder) WithRelaxedSecurity() *AuthorizerBuilder

WithRelaxedSecurity 使用宽松安全配置(禁用安全检查)

func (*AuthorizerBuilder) WithRuntimeVersion added in v1.0.9

func (b *AuthorizerBuilder) WithRuntimeVersion(version string) *AuthorizerBuilder

WithRuntimeVersion 设置运行时的程序版本

func (*AuthorizerBuilder) WithSecureDefaults added in v1.0.6

func (b *AuthorizerBuilder) WithSecureDefaults() *AuthorizerBuilder

WithSecureDefaults 使用安全默认配置(高级安全级别)

func (*AuthorizerBuilder) WithSecurity added in v1.0.6

func (b *AuthorizerBuilder) WithSecurity(security SecurityConfig) *AuthorizerBuilder

WithSecurity 设置安全配置

func (*AuthorizerBuilder) WithSecurityLevel added in v1.0.6

func (b *AuthorizerBuilder) WithSecurityLevel(level int) *AuthorizerBuilder

WithSecurityLevel 设置安全级别(0=禁用,1=基础,2=高级,3=关键)

type AuthorizerConfig added in v1.0.6

type AuthorizerConfig struct {
	RuntimeVersion string         // 当前运行版本
	CACert         []byte         // CA证书
	CAKey          []byte         // CA私钥
	EnterpriseID   int            // 企业标识符
	Security       SecurityConfig // 安全配置
	Cache          CacheConfig    // 缓存配置
}

AuthorizerConfig 授权管理器配置

type BatchIssueBuilder added in v1.0.6

type BatchIssueBuilder struct {
	// contains filtered or unexported fields
}

BatchIssueBuilder 批量签发构建器

func (*BatchIssueBuilder) AddRequest added in v1.0.6

AddRequest 添加证书请求

func (*BatchIssueBuilder) AddRequests added in v1.0.6

func (bb *BatchIssueBuilder) AddRequests(requests ...*ClientCertRequest) *BatchIssueBuilder

AddRequests 添加多个证书请求

func (*BatchIssueBuilder) Execute added in v1.0.6

func (bb *BatchIssueBuilder) Execute() []BatchResult

Execute 执行批量签发

func (*BatchIssueBuilder) WithMaxWorkers added in v1.0.6

func (bb *BatchIssueBuilder) WithMaxWorkers(workers int) *BatchIssueBuilder

WithMaxWorkers 设置并发工作器数量

type BatchManager added in v1.0.6

type BatchManager struct {
	// contains filtered or unexported fields
}

BatchManager 批量操作管理器

func (*BatchManager) IssueMultipleCerts added in v1.0.6

func (bm *BatchManager) IssueMultipleCerts(requests []*ClientCertRequest) []BatchResult

IssueMultipleCerts 批量签发证书

func (*BatchManager) ValidateMultipleCerts added in v1.0.6

func (bm *BatchManager) ValidateMultipleCerts(validations []CertValidation) []ValidationResult

ValidateMultipleCerts 批量验证证书

func (*BatchManager) WithMaxWorkers added in v1.0.6

func (bm *BatchManager) WithMaxWorkers(workers int) *BatchManager

WithMaxWorkers 设置最大并发工作器数量

type BatchResult added in v1.0.6

type BatchResult struct {
	Index       int           // 请求索引
	Certificate *Certificate  // 成功时的证书
	Error       error         // 失败时的错误
	Duration    time.Duration // 操作耗时
}

BatchResult 批量操作结果

type BatchStats added in v1.0.6

type BatchStats struct {
	Total         int           // 总数量
	Success       int           // 成功数量
	Failed        int           // 失败数量
	TotalDuration time.Duration // 总耗时
	AvgDuration   time.Duration // 平均耗时
	MaxDuration   time.Duration // 最大耗时
	MinDuration   time.Duration // 最小耗时
}

BatchStats 批量操作统计

func IssueStats added in v1.0.9

func IssueStats(results []BatchResult) BatchStats

IssueStats 获取批量签发统计信息

func ValidationStats added in v1.0.9

func ValidationStats(results []ValidationResult) BatchStats

ValidationStats 获取批量验证统计信息

type BatchValidateBuilder added in v1.0.6

type BatchValidateBuilder struct {
	// contains filtered or unexported fields
}

BatchValidateBuilder 批量验证构建器

func (*BatchValidateBuilder) AddValidation added in v1.0.6

func (bv *BatchValidateBuilder) AddValidation(certPEM []byte, machineID string) *BatchValidateBuilder

AddValidation 添加验证请求

func (*BatchValidateBuilder) AddValidations added in v1.0.6

func (bv *BatchValidateBuilder) AddValidations(validations ...CertValidation) *BatchValidateBuilder

AddValidations 添加多个验证请求

func (*BatchValidateBuilder) Execute added in v1.0.6

func (bv *BatchValidateBuilder) Execute() []ValidationResult

Execute 执行批量验证

func (*BatchValidateBuilder) WithMaxWorkers added in v1.0.6

func (bv *BatchValidateBuilder) WithMaxWorkers(workers int) *BatchValidateBuilder

WithMaxWorkers 设置并发工作器数量

type BindingInfo added in v1.0.9

type BindingInfo struct {
	Mode     string
	Provider string
}

BindingInfo 定义证书的绑定来源信息

type CAConfiguration added in v1.0.6

type CAConfiguration struct {
	CertPath     string `json:"cert_path" yaml:"cert_path"`
	KeyPath      string `json:"key_path" yaml:"key_path"`
	CertPEM      string `json:"cert_pem" yaml:"cert_pem"`
	KeyPEM       string `json:"key_pem" yaml:"key_pem"`
	UseDefault   bool   `json:"use_default" yaml:"use_default"`
	AutoGenerate bool   `json:"auto_generate" yaml:"auto_generate"`
}

CAConfiguration CA配置

type CAInfo

type CAInfo struct {
	// 基本信息
	CommonName string // CA名称,如 "My Software Root CA"
	ValidDays  int    // 有效期天数

	// 组织信息
	Organization string // 组织名称,如公司名称
	Country      string // 国家代码,如 "CN"
	Province     string // 省份
	Locality     string // 城市

	// 证书参数
	KeyUsages []string // 密钥用途,可选
}

CAInfo CA证书的配置信息

type CacheConfig added in v1.0.6

type CacheConfig struct {
	TTL             time.Duration // 缓存有效期
	MaxSize         int           // 最大缓存大小
	CleanupInterval time.Duration // 清理间隔
}

CacheConfig 缓存配置

type CacheConfiguration added in v1.0.6

type CacheConfiguration struct {
	TTL             string `json:"ttl" yaml:"ttl"`
	MaxSize         int    `json:"max_size" yaml:"max_size"`
	CleanupInterval string `json:"cleanup_interval" yaml:"cleanup_interval"`
	Enabled         bool   `json:"enabled" yaml:"enabled"`
}

CacheConfiguration 缓存配置

type CacheEntry added in v1.0.6

type CacheEntry struct {
	Result    error     // 验证结果(nil表示验证成功)
	ExpiresAt time.Time // 过期时间
	HitCount  int64     // 命中次数
	CreatedAt time.Time // 创建时间
	LastHit   time.Time // 最后命中时间
}

CacheEntry 缓存条目

type CacheStats added in v1.0.6

type CacheStats struct {
	Hits    int64 // 缓存命中次数
	Misses  int64 // 缓存未命中次数
	Evicted int64 // 被驱逐的条目数
	Size    int   // 当前缓存大小
	MaxSize int   // 最大缓存大小
}

CacheStats 缓存统计

type CachedAuthorizer added in v1.0.6

type CachedAuthorizer struct {
	*Authorizer
	// contains filtered or unexported fields
}

CachedAuthorizer 带缓存的授权器包装

func (*CachedAuthorizer) CacheHitRate added in v1.0.9

func (ca *CachedAuthorizer) CacheHitRate() float64

CacheHitRate 获取缓存命中率

func (*CachedAuthorizer) CacheStats added in v1.0.9

func (ca *CachedAuthorizer) CacheStats() CacheStats

CacheStats 获取缓存统计

func (*CachedAuthorizer) ClearCache added in v1.0.6

func (ca *CachedAuthorizer) ClearCache()

ClearCache 清空验证缓存

func (*CachedAuthorizer) ValidateCert added in v1.0.6

func (ca *CachedAuthorizer) ValidateCert(certPEM []byte, machineID string) error

ValidateCert 带缓存的证书验证

type CertError added in v1.0.6

type CertError struct {
	Type        ErrorType              // 错误类型
	Code        ErrorCode              // 错误代码
	Message     string                 // 错误消息
	Details     map[string]interface{} // 错误详情
	Cause       error                  // 原始错误
	Suggestions []string               // 解决建议
}

CertError 证书错误

func NewCertificateError added in v1.0.6

func NewCertificateError(code ErrorCode, message string, cause error) *CertError

NewCertificateError 创建证书错误

func NewConfigError added in v1.0.6

func NewConfigError(code ErrorCode, message string, cause error) *CertError

NewConfigError 创建配置错误

func NewSecurityError added in v1.0.6

func NewSecurityError(code ErrorCode, message string, cause error) *CertError

NewSecurityError 创建安全错误

func NewSystemError added in v1.0.6

func NewSystemError(code ErrorCode, message string, cause error) *CertError

NewSystemError 创建系统错误

func NewValidationError added in v1.0.6

func NewValidationError(code ErrorCode, message string, cause error) *CertError

NewValidationError 创建验证错误

func (*CertError) Error added in v1.0.6

func (e *CertError) Error() string

Error 实现 error 接口

func (*CertError) ErrorCode added in v1.0.9

func (e *CertError) ErrorCode() ErrorCode

ErrorCode 返回错误代码

func (*CertError) ErrorDetails added in v1.0.9

func (e *CertError) ErrorDetails() map[string]interface{}

ErrorDetails 返回错误详情

func (*CertError) ErrorSuggestions added in v1.0.9

func (e *CertError) ErrorSuggestions() []string

ErrorSuggestions 返回解决建议

func (*CertError) ErrorType added in v1.0.9

func (e *CertError) ErrorType() ErrorType

ErrorType 返回错误类型

func (*CertError) Is added in v1.0.6

func (e *CertError) Is(target error) bool

Is 检查是否为指定类型的错误

func (*CertError) Unwrap added in v1.0.6

func (e *CertError) Unwrap() error

Unwrap 解包原始错误

func (*CertError) WithDetail added in v1.0.6

func (e *CertError) WithDetail(key string, value interface{}) *CertError

WithDetail 添加错误详情

func (*CertError) WithSuggestion added in v1.0.6

func (e *CertError) WithSuggestion(suggestion string) *CertError

WithSuggestion 添加解决建议

type CertTemplate added in v1.0.6

type CertTemplate struct {
	Name             string                // 模板名称
	Description      string                // 模板描述
	ValidityDays     int                   // 有效期天数
	KeyUsages        []x509.KeyUsage       // 密钥用途
	ExtKeyUsages     []x509.ExtKeyUsage    // 扩展密钥用途
	CustomExtensions map[string]string     // 自定义扩展
	SecurityLevel    TemplateSecurityLevel // 安全级别
	RequiredFields   []string              // 必填字段
	OptionalFields   []string              // 可选字段
}

CertTemplate 证书模板

type CertValidation added in v1.0.6

type CertValidation struct {
	CertPEM   []byte // 证书PEM数据
	MachineID string // 机器ID
}

CertValidation 证书验证请求

type CertWatcher added in v1.0.6

type CertWatcher struct {
	// contains filtered or unexported fields
}

CertWatcher 证书监控器

func NewCertWatcher added in v1.0.6

func NewCertWatcher(auth *Authorizer, certPEM []byte, machineID string, callback WatchCallback) *CertWatcher

NewCertWatcher 创建证书监控器

func (*CertWatcher) IsRunning added in v1.0.6

func (w *CertWatcher) IsRunning() bool

IsRunning 检查是否正在运行

func (*CertWatcher) Start added in v1.0.6

func (w *CertWatcher) Start() error

Start 启动监控

func (*CertWatcher) Stats added in v1.0.9

func (w *CertWatcher) Stats() map[string]interface{}

Stats 获取监控统计信息

func (*CertWatcher) Stop added in v1.0.6

func (w *CertWatcher) Stop()

Stop 停止监控

func (*CertWatcher) WithCheckInterval added in v1.0.6

func (w *CertWatcher) WithCheckInterval(interval time.Duration) *CertWatcher

WithCheckInterval 设置检查间隔

func (*CertWatcher) WithConfig added in v1.0.6

func (w *CertWatcher) WithConfig(config *WatchConfig) *CertWatcher

WithConfig 设置监控配置

func (*CertWatcher) WithExpiryWarning added in v1.0.6

func (w *CertWatcher) WithExpiryWarning(period time.Duration) *CertWatcher

WithExpiryWarning 设置到期预警

type Certificate

type Certificate struct {
	CertPEM   []byte    // PEM格式的证书
	KeyPEM    []byte    // PEM格式的私钥
	MachineID string    // 机器ID
	NotBefore time.Time // 生效时间
	NotAfter  time.Time // 过期时间
}

Certificate 证书信息

type CertificateChainValidator added in v1.0.6

type CertificateChainValidator struct{}

CertificateChainValidator 证书链验证器

func NewCertificateChainValidator added in v1.0.6

func NewCertificateChainValidator() *CertificateChainValidator

NewCertificateChainValidator 创建证书链验证器

func (*CertificateChainValidator) ValidateChain added in v1.0.6

func (ccv *CertificateChainValidator) ValidateChain(certPEMs [][]byte) error

ValidateChain 验证证书链

type CertificateInfo added in v1.0.6

type CertificateInfo struct {
	Subject            string            `json:"subject"`
	Issuer             string            `json:"issuer"`
	SerialNumber       string            `json:"serial_number"`
	NotBefore          time.Time         `json:"not_before"`
	NotAfter           time.Time         `json:"not_after"`
	KeyUsage           []string          `json:"key_usage"`
	ExtKeyUsage        []string          `json:"ext_key_usage"`
	DNSNames           []string          `json:"dns_names"`
	IPAddresses        []string          `json:"ip_addresses"`
	Extensions         map[string]string `json:"extensions"`
	IsCA               bool              `json:"is_ca"`
	KeySize            int               `json:"key_size"`
	SignatureAlgorithm string            `json:"signature_algorithm"`
	Fingerprint        string            `json:"fingerprint"`
}

CertificateInfo 证书信息摘要

type CertificateInspector added in v1.0.6

type CertificateInspector struct{}

CertificateInspector 证书检查器

func NewCertificateInspector added in v1.0.6

func NewCertificateInspector() *CertificateInspector

NewCertificateInspector 创建证书检查器

func (*CertificateInspector) InspectCertificate added in v1.0.6

func (ci *CertificateInspector) InspectCertificate(cert *x509.Certificate) *CertificateInfo

InspectCertificate 检查x509证书

func (*CertificateInspector) InspectPEM added in v1.0.6

func (ci *CertificateInspector) InspectPEM(certPEM []byte) (*CertificateInfo, error)

InspectPEM 检查PEM格式证书

type ClientCertRequest added in v1.0.6

type ClientCertRequest struct {
	Identity  *Identity  // 身份标识(必需)
	Company   *Company   // 公司信息(必需)
	Contact   *Contact   // 联系信息(可选)
	Technical *Technical // 技术信息(必需)
}

ClientCertRequest 客户端证书请求

func (*ClientCertRequest) MachineIDs added in v1.0.9

func (req *ClientCertRequest) MachineIDs() []string

MachineIDs 获取所有机器码列表

func (*ClientCertRequest) SetDefaults added in v1.0.6

func (req *ClientCertRequest) SetDefaults()

SetDefaults 设置默认值

func (*ClientCertRequest) Validate added in v1.0.6

func (req *ClientCertRequest) Validate() error

Validate 验证请求参数

type ClientCertRequestBuilder added in v1.0.6

type ClientCertRequestBuilder struct {
	// contains filtered or unexported fields
}

ClientCertRequestBuilder 客户端证书请求构建器

func NewClientRequest added in v1.0.6

func NewClientRequest() *ClientCertRequestBuilder

NewClientRequest 创建新的客户端证书请求构建器

func (*ClientCertRequestBuilder) Build added in v1.0.6

Build 构建证书请求

func (*ClientCertRequestBuilder) WithAddress added in v1.0.6

func (b *ClientCertRequestBuilder) WithAddress(country, province, city, street string) *ClientCertRequestBuilder

WithAddress 设置地址信息

func (*ClientCertRequestBuilder) WithBindingInfo added in v1.0.9

func (b *ClientCertRequestBuilder) WithBindingInfo(mode, provider string) *ClientCertRequestBuilder

WithBindingInfo 设置机器码绑定信息

func (*ClientCertRequestBuilder) WithBindingResult added in v1.0.9

WithBindingResult 直接使用 machineid 包返回的绑定结果

func (*ClientCertRequestBuilder) WithCompany added in v1.0.6

func (b *ClientCertRequestBuilder) WithCompany(name, department string) *ClientCertRequestBuilder

WithCompany 设置公司信息

func (*ClientCertRequestBuilder) WithContact added in v1.0.6

func (b *ClientCertRequestBuilder) WithContact(person, phone, email string) *ClientCertRequestBuilder

WithContact 设置联系信息

func (*ClientCertRequestBuilder) WithExpiry added in v1.0.6

func (b *ClientCertRequestBuilder) WithExpiry(expiryDate time.Time) *ClientCertRequestBuilder

WithExpiry 设置过期时间

func (*ClientCertRequestBuilder) WithMachineID added in v1.0.6

func (b *ClientCertRequestBuilder) WithMachineID(machineID string) *ClientCertRequestBuilder

WithMachineID 设置机器码

func (*ClientCertRequestBuilder) WithMinClientVersion added in v1.0.9

func (b *ClientCertRequestBuilder) WithMinClientVersion(version string) *ClientCertRequestBuilder

WithMinClientVersion 设置最低客户端版本

func (*ClientCertRequestBuilder) WithTemplate added in v1.0.6

func (b *ClientCertRequestBuilder) WithTemplate(templateName string) *ClientCertRequestBuilder

WithTemplate 使用模板

func (*ClientCertRequestBuilder) WithValidityDays added in v1.0.6

func (b *ClientCertRequestBuilder) WithValidityDays(days int) *ClientCertRequestBuilder

WithValidityDays 设置证书有效期天数

type ClientInfo

type ClientInfo struct {
	// 基本信息
	MachineID       string    // 机器码可以是单个或多个(用逗号分隔)
	ExpiryDate      time.Time // 授权结束日期
	BindingMode     string    // 绑定模式
	BindingProvider string    // 绑定提供者

	// 公司信息
	CompanyName   string // 公司名称
	Department    string // 部门名称
	ContactPerson string // 联系人
	ContactPhone  string // 联系电话
	ContactEmail  string // 联系邮箱

	// 地址信息
	Country  string // 国家
	Province string // 省份
	City     string // 城市
	Address  string // 详细地址

	// 版本信息
	MinClientVersion   string // 最低客户端版本要求
	ValidityPeriodDays int    // 证书有效天数
}

ClientInfo 客户端信息

type Company added in v1.0.6

type Company struct {
	Name       string   // 公司名称
	Department string   // 部门名称
	Address    *Address // 地址信息(可选)
}

Company 公司信息

type ConfigFile added in v1.0.6

type ConfigFile struct {
	RuntimeVersion string                 `json:"runtime_version" yaml:"runtime_version"`
	EnterpriseID   int                    `json:"enterprise_id" yaml:"enterprise_id"`
	CA             CAConfiguration        `json:"ca" yaml:"ca"`
	Security       SecurityConfiguration  `json:"security" yaml:"security"`
	Cache          CacheConfiguration     `json:"cache" yaml:"cache"`
	Templates      map[string]interface{} `json:"templates" yaml:"templates"`
	Logging        LoggingConfiguration   `json:"logging" yaml:"logging"`
}

ConfigFile 配置文件结构

func (*ConfigFile) ToAuthorizerConfig added in v1.0.6

func (cf *ConfigFile) ToAuthorizerConfig() (AuthorizerConfig, error)

ToAuthorizerConfig 转换为授权管理器配置

type ConfigLoader added in v1.0.6

type ConfigLoader struct {
	// contains filtered or unexported fields
}

ConfigLoader 配置加载器

func NewConfigLoader added in v1.0.6

func NewConfigLoader() *ConfigLoader

NewConfigLoader 创建配置加载器

func (*ConfigLoader) LoadConfig added in v1.0.6

func (cl *ConfigLoader) LoadConfig() (*ConfigFile, error)

LoadConfig 加载配置文件

func (*ConfigLoader) WithFilename added in v1.0.6

func (cl *ConfigLoader) WithFilename(filename string) *ConfigLoader

WithFilename 设置配置文件名

func (*ConfigLoader) WithSearchPaths added in v1.0.6

func (cl *ConfigLoader) WithSearchPaths(paths ...string) *ConfigLoader

WithSearchPaths 设置搜索路径

type Contact added in v1.0.6

type Contact struct {
	Person string // 联系人
	Phone  string // 联系电话
	Email  string // 联系邮箱
}

Contact 联系信息

type ErrorCode added in v1.0.6

type ErrorCode string

ErrorCode 错误代码

const (
	// 验证错误代码
	ErrInvalidMachineID     ErrorCode = "INVALID_MACHINE_ID"
	ErrInvalidVersion       ErrorCode = "INVALID_VERSION"
	ErrExpiredCertificate   ErrorCode = "EXPIRED_CERTIFICATE"
	ErrInvalidCertificate   ErrorCode = "INVALID_CERTIFICATE"
	ErrMissingRequiredField ErrorCode = "MISSING_REQUIRED_FIELD"

	// 安全错误代码
	ErrDebuggerDetected   ErrorCode = "DEBUGGER_DETECTED"
	ErrTimeManipulation   ErrorCode = "TIME_MANIPULATION"
	ErrUnauthorizedAccess ErrorCode = "UNAUTHORIZED_ACCESS"
	ErrCertificateRevoked ErrorCode = "CERTIFICATE_REVOKED"
	ErrTimeRollback       ErrorCode = "TIME_ROLLBACK"    // 时间回滚
	ErrHardwareChanged    ErrorCode = "HARDWARE_CHANGED" // 硬件变更

	// 配置错误代码
	ErrInvalidCAConfig ErrorCode = "INVALID_CA_CONFIG"
	ErrMissingCA       ErrorCode = "MISSING_CA"
	ErrInvalidKeySize  ErrorCode = "INVALID_KEY_SIZE"
	ErrInvalidConfig   ErrorCode = "INVALID_CONFIG"

	// 系统错误代码
	ErrSystemClockSkew    ErrorCode = "SYSTEM_CLOCK_SKEW"
	ErrInsufficientRights ErrorCode = "INSUFFICIENT_RIGHTS"
	ErrFileSystemError    ErrorCode = "FILESYSTEM_ERROR"

	// 容器和快照错误代码
	ErrContainerBindingFailed ErrorCode = "CONTAINER_BINDING_FAILED" // 容器绑定失败
	ErrSnapshotExpired        ErrorCode = "SNAPSHOT_EXPIRED"         // 快照过期
	ErrSnapshotInvalid        ErrorCode = "SNAPSHOT_INVALID"         // 快照无效
)

type ErrorType added in v1.0.6

type ErrorType int

ErrorType 错误类型

const (
	// ValidationError 验证错误
	ValidationError ErrorType = iota
	// SecurityError 安全错误
	SecurityError
	// ConfigError 配置错误
	ConfigError
	// NetworkError 网络错误
	NetworkError
	// CertificateError 证书错误
	CertificateError
	// SystemError 系统错误
	SystemError
)

type HardwareSnapshot added in v1.0.9

type HardwareSnapshot struct {
	// Fingerprint 硬件指纹哈希
	Fingerprint string `json:"fingerprint"`

	// Components 组成指纹的硬件组件列表
	Components []string `json:"components"`

	// Weights 各组件的权重(与 Components 一一对应)
	Weights []int `json:"weights"`

	// CreatedAt 快照创建时间
	CreatedAt time.Time `json:"created_at"`

	// ExpiresAt 快照过期时间
	ExpiresAt time.Time `json:"expires_at"`

	// Signature HMAC-SHA256 签名(使用 machine ID 作为密钥)
	Signature string `json:"signature"`

	// Version 快照格式版本
	Version int `json:"version"`
}

HardwareSnapshot 硬件快照结构

用于离线验证场景: - 在联网环境下创建快照并签名 - 在离线环境下验证硬件是否发生变化 - 支持时间有效性检查

func CreateSnapshot added in v1.0.9

func CreateSnapshot(appID string, validity time.Duration) (*HardwareSnapshot, error)

CreateSnapshot 创建硬件快照

参数:

  • appID: 应用标识符(用于生成签名密钥)
  • validity: 快照有效期(传 0 使用默认 90 天)

返回快照对象和错误

func LoadSnapshotFromFile added in v1.0.9

func LoadSnapshotFromFile(filepath string) (*HardwareSnapshot, error)

LoadSnapshotFromFile 从文件加载快照

func (*HardwareSnapshot) ExtendValidity added in v1.0.9

func (s *HardwareSnapshot) ExtendValidity(appID string, extension time.Duration) error

ExtendValidity 延长快照有效期

注意:延长有效期后需要重新计算签名

func (*HardwareSnapshot) IsExpired added in v1.0.9

func (s *HardwareSnapshot) IsExpired() bool

IsExpired 检查快照是否已过期

func (*HardwareSnapshot) SaveToFile added in v1.0.9

func (s *HardwareSnapshot) SaveToFile(filepath string) error

SaveToFile 保存快照到文件

func (*HardwareSnapshot) TimeUntilExpiry added in v1.0.9

func (s *HardwareSnapshot) TimeUntilExpiry() time.Duration

TimeUntilExpiry 返回距离过期的剩余时间

type Identity added in v1.0.6

type Identity struct {
	MachineID       string    // 机器码(可以是多个,用逗号分隔)
	ExpiryDate      time.Time // 授权过期日期
	BindingMode     string    // 绑定模式
	BindingProvider string    // 绑定提供者
}

Identity 身份标识信息

type License added in v1.0.9

type License struct {
	Payload   LicensePayload `json:"payload"`
	Signature string         `json:"signature"` // base64(std) of ed25519 signature
}

License 是离线授权文件的载体(payload + 签名)。

设计目标: - 可离线校验:客户端只需要内置公钥 - 与证书授权并存:证书用于“更重”的授权体系,License 适合“轻量文件/配置”分发 - 机器绑定:可绑定 MachineID(建议使用 machineid.ProtectedIDResult 的 Hash)

注意: - Signature 覆盖 CanonicalPayload(稳定 JSON 序列化),避免字段顺序导致签名不一致

type LicensePayload added in v1.0.9

type LicensePayload struct {
	SchemaVersion int               `json:"schema_version"`
	LicenseID     string            `json:"license_id"`
	IssuedAt      time.Time         `json:"issued_at"`
	NotBefore     time.Time         `json:"not_before"`
	NotAfter      time.Time         `json:"not_after"`
	MachineID     string            `json:"machine_id"` // MachineID 建议填 machineid.ProtectedIDResult(appID).Hash(而非原始 machine-id),允许逗号分隔多个值
	Features      map[string]any    `json:"features,omitempty"`
	Meta          map[string]string `json:"meta,omitempty"`
}

func ValidateLicenseJSON added in v1.0.9

func ValidateLicenseJSON(licenseJSON []byte, publicKey ed25519.PublicKey, machineID string, now time.Time) (*LicensePayload, error)

ValidateLicenseJSON 校验 license JSON,包含: - 签名验证 - 时间有效期验证 - 机器码匹配(若传入 machineID)

func ValidateLicenseJSONWithAppID added in v1.0.9

func ValidateLicenseJSONWithAppID(licenseJSON []byte, publicKey ed25519.PublicKey, appID string, now time.Time) (*LicensePayload, error)

ValidateLicenseJSONWithAppID 是更推荐的校验入口: - machineID 使用 machineid.ProtectedIDResult(appID).Hash(避免暴露原始 machine-id) - 仍可保持 “license payload 内存储的是绑定后的 hash” 的设计

type LoggingConfiguration added in v1.0.6

type LoggingConfiguration struct {
	Level  string `json:"level" yaml:"level"`
	File   string `json:"file" yaml:"file"`
	Format string `json:"format" yaml:"format"`
}

LoggingConfiguration 日志配置

type MonotonicTime added in v1.0.9

type MonotonicTime struct {
	// contains filtered or unexported fields
}

MonotonicTime 单调时间管理器

用于检测系统时间回滚攻击: - 持久化最后已知时间戳 - 启动时检查时间一致性 - 防止通过修改系统时间绕过有效期检查

func NewMonotonicTime added in v1.0.9

func NewMonotonicTime(persistencePath string, maxClockSkew time.Duration) (*MonotonicTime, error)

NewMonotonicTime 创建单调时间管理器

func (*MonotonicTime) CheckTimeRollback added in v1.0.9

func (mt *MonotonicTime) CheckTimeRollback() error

CheckTimeRollback 检查时间回滚

返回错误表示检测到时间回滚

func (*MonotonicTime) ForceUpdate added in v1.0.9

func (mt *MonotonicTime) ForceUpdate(newTime time.Time) error

ForceUpdate 强制更新时间戳(谨慎使用)

注意:此方法应仅在确认时间正确的情况下使用, 例如从可信时间服务器同步后

func (*MonotonicTime) GetLastKnownTime added in v1.0.9

func (mt *MonotonicTime) GetLastKnownTime() time.Time

GetLastKnownTime 获取上次记录的时间

func (*MonotonicTime) Reset added in v1.0.9

func (mt *MonotonicTime) Reset() error

Reset 重置时间戳(用于测试或迁移场景)

type ObfuscatedString added in v1.0.9

type ObfuscatedString struct {
	// contains filtered or unexported fields
}

ObfuscatedString 混淆字符串。

用途说明: - 通过 XOR 对字节做轻量“扰码”,再配合 Base64 进行可打印编码; - 主要目的是避免敏感字符串以明文形式直接出现在源码/二进制的只读数据段中,降低被简单字符串扫描直接命中的概率; - 这不是密码学意义上的加密(key 也会随二进制一同分发),不要用于对抗有能力的逆向分析,只用于“去明文”。

func NewObfuscatedString added in v1.0.9

func NewObfuscatedString(plaintext string) *ObfuscatedString

NewObfuscatedString 创建混淆字符串。

使用 XOR + Base64 对敏感字符串进行混淆,避免明文暴露在二进制中。

func (*ObfuscatedString) Encode added in v1.0.9

func (o *ObfuscatedString) Encode() string

Encode 编码为 Base64。

func (*ObfuscatedString) Reveal added in v1.0.9

func (o *ObfuscatedString) Reveal() string

Reveal 解密混淆字符串。

type OperationStats added in v1.0.6

type OperationStats struct {
	Count       int64         `json:"count"`
	TotalTime   time.Duration `json:"total_time"`
	MinTime     time.Duration `json:"min_time"`
	MaxTime     time.Duration `json:"max_time"`
	AvgTime     time.Duration `json:"avg_time"`
	LastTime    time.Duration `json:"last_time"`
	LastUpdated time.Time     `json:"last_updated"`
}

OperationStats 操作统计

type Option

type Option func(*AuthorizerBuilder) *AuthorizerBuilder

Option 配置选项函数

func WithAdvancedSecurity added in v1.0.9

func WithAdvancedSecurity() Option

WithAdvancedSecurity 高级安全配置组合

使用示例:

WithAdvancedSecurity()

func WithContainerSupport added in v1.0.9

func WithContainerSupport(config interface{}) Option

WithContainerSupport 配置容器环境支持

参数:

  • config: 容器绑定配置

使用示例:

WithContainerSupport(&machineid.ContainerBindingConfig{
    Mode:                machineid.ContainerBindingAuto,
    PreferHostHardware:  true,
    FallbackToContainer: true,
})

func WithFullSecurity added in v1.0.9

func WithFullSecurity() Option

WithFullSecurity 完整安全配置组合(包括硬件绑定和离线验证)

使用示例:

WithFullSecurity()

func WithHardwareBinding added in v1.0.9

func WithHardwareBinding(mode string) Option

WithHardwareBinding 配置硬件绑定模式

参数:

  • mode: 绑定模式(fingerprint/mac/machine_id/custom)

使用示例:

WithHardwareBinding(machineid.BindingModeFingerprint)

func WithMonotonicTime added in v1.0.9

func WithMonotonicTime(persistencePath string, maxClockSkew time.Duration) Option

WithMonotonicTime 配置单调时间检查

参数:

  • persistencePath: 时间戳持久化路径
  • maxClockSkew: 允许的最大时钟偏差

使用示例:

WithMonotonicTime("./.timestamp", 5*time.Minute)

func WithOfflineValidation added in v1.0.9

func WithOfflineValidation(snapshotPath string) Option

WithOfflineValidation 配置离线验证支持

参数:

  • snapshotPath: 硬件快照存储路径

使用示例:

WithOfflineValidation("./snapshots")

func WithSecurityPreset added in v1.0.9

func WithSecurityPreset(preset string) Option

WithSecurityPreset 使用预设的安全配置组合

参数:

  • preset: 预设名称 ("development"/"production"/"testing")

使用示例:

WithSecurityPreset("production")

func WithSignedCache added in v1.0.9

func WithSignedCache(signKey []byte, config CacheConfig) Option

WithSignedCache 配置带签名的缓存

参数:

  • signKey: 签名密钥
  • config: 缓存配置

使用示例:

WithSignedCache([]byte("my-secret-key"), CacheConfig{
    TTL:             10 * time.Minute,
    MaxSize:         1000,
    CleanupInterval: time.Minute,
})

type PerformanceMonitor added in v1.0.6

type PerformanceMonitor struct {
	// contains filtered or unexported fields
}

PerformanceMonitor 性能监控器

func NewPerformanceMonitor added in v1.0.6

func NewPerformanceMonitor() *PerformanceMonitor

NewPerformanceMonitor 创建性能监控器

func (*PerformanceMonitor) RecordOperation added in v1.0.6

func (pm *PerformanceMonitor) RecordOperation(name string, duration time.Duration)

RecordOperation 记录操作性能

func (*PerformanceMonitor) Reset added in v1.0.6

func (pm *PerformanceMonitor) Reset()

Reset 重置统计

func (*PerformanceMonitor) Stats added in v1.0.9

func (pm *PerformanceMonitor) Stats() map[string]*OperationStats

Stats 获取统计信息

type RevokeInfo

type RevokeInfo struct {
	SerialNumber    string    // 证书序列号
	RevokeDate      time.Time // 吊销时间
	RevokeReason    string    // 吊销原因
	MinValidVersion string    // 最低有效版本
}

RevokeInfo 吊销信息

type RevokeList

type RevokeList struct {
	UpdateTime   time.Time              // 列表更新时间
	RevokedCerts map[string]*RevokeInfo // 已吊销证书
	MinVersion   string                 // 最低支持版本
}

RevokeList 吊销列表

type RevokeManager

type RevokeManager struct {
	// contains filtered or unexported fields
}

RevokeManager 吊销管理器

func NewRevokeManager

func NewRevokeManager(version string, opts ...RevokeOption) (*RevokeManager, error)

NewRevokeManager 创建吊销管理器

func (*RevokeManager) IsRevoked

func (rm *RevokeManager) IsRevoked(serialNumber string) (bool, string)

IsRevoked 检查证书是否被吊销

func (*RevokeManager) UpdateRevokeList

func (rm *RevokeManager) UpdateRevokeList() error

UpdateRevokeList 更新吊销列表

type RevokeOption

type RevokeOption func(*RevokeManager) error

RevokeOption 吊销管理器的配置选项

func WithRevokeList

func WithRevokeList(list []byte) RevokeOption

WithRevokeList 直接设置吊销列表

func WithRevokeListUpdater

func WithRevokeListUpdater(updater func() ([]byte, error)) RevokeOption

WithRevokeListUpdater 设置吊销列表更新函数

type SecurityConfig added in v1.0.6

type SecurityConfig struct {
	EnableAntiDebug        bool          // 启用反调试
	EnableTimeValidation   bool          // 启用时间验证
	RequireHardwareBinding bool          // 要求硬件绑定
	MaxClockSkew           time.Duration // 最大时钟偏差
	SecurityLevel          *int          // 显式安全级别(可选,优先级最高)
}

SecurityConfig 安全配置

func (*SecurityConfig) EffectiveSecurityLevel added in v1.0.9

func (sc *SecurityConfig) EffectiveSecurityLevel() (int, bool)

EffectiveSecurityLevel 获取安全级别

func (*SecurityConfig) SetSecurityLevel added in v1.0.6

func (sc *SecurityConfig) SetSecurityLevel(level int)

SetSecurityLevel 设置安全级别

type SecurityConfiguration added in v1.0.6

type SecurityConfiguration struct {
	EnableAntiDebug        bool   `json:"enable_anti_debug" yaml:"enable_anti_debug"`
	EnableTimeValidation   bool   `json:"enable_time_validation" yaml:"enable_time_validation"`
	RequireHardwareBinding bool   `json:"require_hardware_binding" yaml:"require_hardware_binding"`
	MaxClockSkew           string `json:"max_clock_skew" yaml:"max_clock_skew"`
}

SecurityConfiguration 安全配置

type SecurityManager added in v1.0.6

type SecurityManager struct {
	// contains filtered or unexported fields
}

SecurityManager 安全管理器

func NewSecurityManager added in v1.0.6

func NewSecurityManager(level int) *SecurityManager

NewSecurityManager 创建安全管理器

func (*SecurityManager) Check added in v1.0.9

func (sm *SecurityManager) Check() error

Check 执行安全检查

func (*SecurityManager) Close added in v1.0.9

func (sm *SecurityManager) Close()

Close 关闭安全管理器

func (*SecurityManager) DetectSandbox added in v1.0.6

func (sm *SecurityManager) DetectSandbox() bool

DetectSandbox 检测沙箱环境

这里的“沙箱”更偏向运行限制环境,例如: - 容器/受限 namespace(Linux) - macOS App Sandbox(需要 entitlements/系统 API,难以在纯 Go 通用检测) - Windows 的受限令牌/Job Object(同样需要 WinAPI)

因此实现策略为“低误报”的启发式检测:只在证据较强时返回 true。

func (*SecurityManager) DetectVirtualMachine added in v1.0.6

func (sm *SecurityManager) DetectVirtualMachine() bool

DetectVirtualMachine 检测虚拟机环境

设计原则: - 只做“可能性”检测:尽量避免误报导致不可用 - 不引入外部依赖;尽量使用系统可读取的只读信息 - 平台差异大:使用 runtime.GOOS 分支实现

func (*SecurityManager) GetDebuggerCount added in v1.0.9

func (sm *SecurityManager) GetDebuggerCount() int

GetDebuggerCount 获取调试器检测次数

func (*SecurityManager) ProtectProcess added in v1.0.6

func (sm *SecurityManager) ProtectProcess() error

ProtectProcess 保护进程(简化实现)

func (*SecurityManager) StopSecurityChecks added in v1.0.6

func (sm *SecurityManager) StopSecurityChecks()

StopSecurityChecks 停止后台安全检查

注意: - 此方法应可重复调用且不应 panic(与 Close 行为一致但更语义化) - 会等待后台 goroutine 退出,避免测试/调用方泄漏 goroutine

func (*SecurityManager) VerifyIntegrity added in v1.0.6

func (sm *SecurityManager) VerifyIntegrity() error

VerifyIntegrity 验证内存完整性(简化实现)

type SignedCacheEntry added in v1.0.9

type SignedCacheEntry struct {
	*CacheEntry
	Signature  string    // HMAC-SHA256 签名
	MachineID  string    // 机器ID(用于验证)
	SignedAt   time.Time // 签名时间
	DataHash   string    // 数据哈希(用于检测篡改)
	SnapshotID string    // 关联的硬件快照ID(可选)
}

SignedCacheEntry 带签名的缓存条目

用于离线验证场景,确保缓存数据的完整性和真实性

type SignedValidationCache added in v1.0.9

type SignedValidationCache struct {
	*ValidationCache
	// contains filtered or unexported fields
}

SignedValidationCache 带签名的验证缓存

func NewSignedValidationCache added in v1.0.9

func NewSignedValidationCache(config CacheConfig, signKey []byte) *SignedValidationCache

NewSignedValidationCache 创建带签名的验证缓存

func (*SignedValidationCache) ExportSignedEntry added in v1.0.9

func (svc *SignedValidationCache) ExportSignedEntry(
	certPEM []byte,
	machineID string,
) (*SignedCacheEntry, error)

ExportSignedEntry 导出签名缓存条目(用于持久化)

func (*SignedValidationCache) GetWithVerification added in v1.0.9

func (svc *SignedValidationCache) GetWithVerification(
	certPEM []byte,
	machineID string,
	signedEntry *SignedCacheEntry,
) (error, bool)

GetWithVerification 验证后获取缓存条目

参数:

  • certPEM: 证书PEM数据
  • machineID: 机器ID
  • signedEntry: 之前存储的签名条目

返回验证结果和是否有效

func (*SignedValidationCache) StoreWithSignature added in v1.0.9

func (svc *SignedValidationCache) StoreWithSignature(
	certPEM []byte,
	machineID string,
	result error,
	snapshotID string,
) (*SignedCacheEntry, error)

StoreWithSignature 带签名存储缓存条目

参数:

  • certPEM: 证书PEM数据
  • machineID: 机器ID
  • result: 验证结果
  • snapshotID: 关联的硬件快照ID(可选)

返回签名后的缓存条目

type SystemInfoCollector added in v1.0.6

type SystemInfoCollector struct{}

SystemInfoCollector 系统信息收集器

func NewSystemInfoCollector added in v1.0.6

func NewSystemInfoCollector() *SystemInfoCollector

NewSystemInfoCollector 创建系统信息收集器

func (*SystemInfoCollector) SystemInfo added in v1.0.9

func (sic *SystemInfoCollector) SystemInfo() map[string]any

GetSystemInfo 获取系统信息

type Technical added in v1.0.6

type Technical struct {
	MinClientVersion   string // 最低客户端版本要求
	ValidityPeriodDays int    // 证书有效期天数
}

Technical 技术信息

type TemplateManager added in v1.0.6

type TemplateManager struct {
	// contains filtered or unexported fields
}

TemplateManager 模板管理器

func NewTemplateManager added in v1.0.6

func NewTemplateManager() *TemplateManager

NewTemplateManager 创建模板管理器

func (*TemplateManager) AddTemplate added in v1.0.6

func (tm *TemplateManager) AddTemplate(name string, template *CertTemplate) error

AddTemplate 添加自定义模板

func (*TemplateManager) ApplyTemplate added in v1.0.6

func (tm *TemplateManager) ApplyTemplate(req *ClientCertRequest, templateName string) error

ApplyTemplate 应用模板到请求

func (*TemplateManager) ListTemplates added in v1.0.6

func (tm *TemplateManager) ListTemplates() map[string]*CertTemplate

ListTemplates 列出所有可用模板

func (*TemplateManager) Template added in v1.0.9

func (tm *TemplateManager) Template(name string) (*CertTemplate, error)

Template 获取模板

func (*TemplateManager) ValidateRequestWithTemplate added in v1.0.6

func (tm *TemplateManager) ValidateRequestWithTemplate(req *ClientCertRequest, templateName string) error

ValidateRequestWithTemplate 使用模板验证请求

type TemplateSecurityLevel added in v1.0.6

type TemplateSecurityLevel int

TemplateSecurityLevel 模板安全级别

const (
	TemplateSecurityLevelLow TemplateSecurityLevel = iota
	TemplateSecurityLevelMedium
	TemplateSecurityLevelHigh
	TemplateSecurityLevelCritical
)

type TimeDetectionConfig added in v1.0.9

type TimeDetectionConfig struct {
	BaseThreshold    time.Duration // 基础阈值(默认 10ms)
	RandomRange      time.Duration // 随机范围(默认 5ms)
	SampleCount      int           // 采样次数(默认 3)
	FailureThreshold int           // 失败阈值(默认 2,即3次中2次失败)
}

TimeDetectionConfig 时间检测配置

用于对抗基于时间的调试检测绕过: - 随机化阈值避免固定特征 - 多次采样减少误报 - 混淆工作负载防止空循环被优化

func DefaultTimeDetectionConfig added in v1.0.9

func DefaultTimeDetectionConfig() TimeDetectionConfig

DefaultTimeDetectionConfig 返回默认时间检测配置

type ValidationCache added in v1.0.6

type ValidationCache struct {
	// contains filtered or unexported fields
}

ValidationCache 验证缓存

func NewValidationCache added in v1.0.6

func NewValidationCache(config CacheConfig) *ValidationCache

NewValidationCache 创建新的验证缓存

func (*ValidationCache) Clear added in v1.0.6

func (vc *ValidationCache) Clear()

Clear 清空缓存

func (*ValidationCache) Close added in v1.0.9

func (vc *ValidationCache) Close()

Close 关闭缓存并停止清理协程

func (*ValidationCache) Get added in v1.0.6

func (vc *ValidationCache) Get(certPEM []byte, machineID string) (error, bool)

Get 从缓存获取验证结果

func (*ValidationCache) HitRate added in v1.0.9

func (vc *ValidationCache) HitRate() float64

HitRate 获取缓存命中率

func (*ValidationCache) Put added in v1.0.6

func (vc *ValidationCache) Put(certPEM []byte, machineID string, result error)

Put 将验证结果存储到缓存

func (*ValidationCache) Size added in v1.0.6

func (vc *ValidationCache) Size() int

Size 获取当前缓存大小

func (*ValidationCache) Stats added in v1.0.9

func (vc *ValidationCache) Stats() CacheStats

Stats 获取缓存统计信息

type ValidationResult added in v1.0.6

type ValidationResult struct {
	Index     int           // 请求索引
	Valid     bool          // 是否有效
	Error     error         // 错误信息(如果有)
	Duration  time.Duration // 验证耗时
	MachineID string        // 机器ID
}

ValidationResult 验证结果

type VersionInfo

type VersionInfo struct {
	MinClientVersion     string // 最低需要的客户端版本
	LicenseSchemaVersion string // 证书格式版本
	MaxValidDays         int    // 最大有效天数
}

VersionInfo 定义证书的版本信息

type WatchCallback added in v1.0.6

type WatchCallback func(event WatchEvent, clientInfo *ClientInfo, err error)

WatchCallback 监控回调函数类型

type WatchConfig added in v1.0.6

type WatchConfig struct {
	// CheckInterval 检查间隔,默认1小时
	CheckInterval time.Duration

	// ExpiryWarningPeriod 到期预警时间,默认7天
	ExpiryWarningPeriod time.Duration

	// EnableExpiryWarning 是否启用到期预警
	EnableExpiryWarning bool

	// EnableRevocationCheck 是否启用吊销检查
	EnableRevocationCheck bool

	// MaxRetries 检查失败时的最大重试次数
	MaxRetries int

	// RetryInterval 重试间隔
	RetryInterval time.Duration
}

WatchConfig 监控配置

func DefaultWatchConfig added in v1.0.6

func DefaultWatchConfig() *WatchConfig

DefaultWatchConfig 返回默认监控配置

type WatchEvent added in v1.0.6

type WatchEvent string

WatchEvent 监控事件类型

const (
	WatchEventExpiring WatchEvent = "expiring" // 即将到期
	WatchEventExpired  WatchEvent = "expired"  // 已到期
	WatchEventInvalid  WatchEvent = "invalid"  // 证书无效
	WatchEventRevoked  WatchEvent = "revoked"  // 证书被吊销
)

type WatcherManager added in v1.0.6

type WatcherManager struct {
	// contains filtered or unexported fields
}

WatcherManager 监控器管理器

func NewWatcherManager added in v1.0.6

func NewWatcherManager() *WatcherManager

NewWatcherManager 创建监控器管理器

func (*WatcherManager) AddWatcher added in v1.0.6

func (wm *WatcherManager) AddWatcher(id string, watcher *CertWatcher)

AddWatcher 添加监控器

func (*WatcherManager) AllStats added in v1.0.9

func (wm *WatcherManager) AllStats() map[string]map[string]interface{}

AllStats 获取所有监控器的统计信息

func (*WatcherManager) RemoveWatcher added in v1.0.6

func (wm *WatcherManager) RemoveWatcher(id string)

RemoveWatcher 移除监控器

func (*WatcherManager) StopAll added in v1.0.6

func (wm *WatcherManager) StopAll()

StopAll 停止所有监控器

func (*WatcherManager) Watcher added in v1.0.9

func (wm *WatcherManager) Watcher(id string) (*CertWatcher, bool)

Watcher 获取监控器

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL