cert

package
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2025 License: MIT, MIT Imports: 29 Imported by: 0

README

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

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

🚀 主要特性

📜 证书管理
  • CA 证书生成:支持自定义 CA 证书和私钥管理
  • 客户端证书签发:基于机器码的证书签发系统
  • 证书验证:完整的证书链验证和有效性检查
  • 证书吊销:动态吊销列表管理和实时更新
  • 批量处理:支持大规模证书批量签发和验证
🛡️ 安全防护(可选)
  • 分级保护: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().
    WithVersion("2.0.0").
    WithSecurityLevel(2).                 // 高级安全保护
    WithMaxClockSkew(1 * time.Minute).
    Build()
2. 生成 CA 证书
caInfo := cert.CAInfo{
    CommonName:   "ZStudio Software CA",
    Organization: "子说软件工作室",
    Country:      "CN",
    Province:     "Guangdong",
    Locality:     "Guangzhou",
    ValidDays:    3650, // 10年有效期
    KeySize:      4096,
}

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

// 保存CA证书到指定目录
err = auth.SaveCA("./certificates")
3. 签发客户端证书
// 构建证书请求
req := &cert.ClientCertRequest{
    Identity: cert.Identity{
        MachineID:  "DESKTOP-ABC123-HDD-12345678",
        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:  "zhangsan@example.com",
    },
    Technical: cert.Technical{
        Version:            "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.Version)
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.GetStats()
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.GetAllStats()
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.IssueBatch(requests)

// 并发验证多个证书
validationTasks := []cert.ValidationTask{ /* ... */ }
results := batchManager.ValidateBatch(validationTasks)
缓存优化
// 创建缓存授权管理器
cachedAuth := cert.NewCachedAuthorizer(auth, cert.CacheConfig{
    TTL:             10 * time.Minute,
    MaxSize:         1000,
    CleanupInterval: 5 * time.Minute,
})

// 验证会自动使用缓存
err := cachedAuth.ValidateCert(certPEM, machineID)
模板系统
// 使用预定义模板
template := cert.GetTemplate("enterprise")
template.MaxValidDays = 730 // 2年有效期

// 创建自定义模板
customTemplate := &cert.CertificateTemplate{
    DefaultValidDays: 365,
    KeySize:         2048,
    Organization:    "My Company",
    // ...
}

cert.RegisterTemplate("custom", customTemplate)

📊 错误处理

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

err := auth.ValidateCert(certPEM, machineID)
if err != nil {
    if certErr, ok := err.(*cert.CertError); ok {
        fmt.Printf("错误类型: %s\n", certErr.GetCode())
        fmt.Printf("错误详情: %v\n", certErr.GetDetails())
        fmt.Printf("解决建议: %v\n", certErr.GetSuggestions())
    }
}
错误类型
  • 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
性能监控
// 启用性能统计
auth.EnableMetrics(true)

// 获取统计信息
stats := auth.GetMetrics()
fmt.Printf("验证成功率: %.2f%%\n", stats.SuccessRate)
fmt.Printf("平均验证时间: %v\n", stats.AvgValidationTime)

🏗️ 系统集成

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

    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()
集群部署
// 支持多实例部署
auth := cert.NewAuthorizer().
    WithSharedCache(redis.NewClient()). // 使用Redis共享缓存
    WithDistributedLock().              // 分布式锁
    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

Overview

Package cert 提供证书管理功能,包括证书的签发、验证和吊销管理。

这个包主要用于软件授权管理,支持: - 证书签发和验证 - 证书吊销管理 - 版本控制 - 授权时间管理

Index

Constants

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

SecurityLevel 安全防护级别

Variables

This section is empty.

Functions

func ApplyTemplateToRequest added in v1.0.6

func ApplyTemplateToRequest(req *ClientCertRequest, templateName string) error

ApplyTemplateToRequest 将模板应用到证书请求

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 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 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 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 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 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 使用全局模板验证请求

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) 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) GetCACertPEM

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

GetCACertPEM 获取PEM格式的CA证书

func (*Authorizer) GetConfig added in v1.0.6

func (a *Authorizer) GetConfig() AuthorizerConfig

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

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) 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) 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=关键)

func (*AuthorizerBuilder) WithVersion added in v1.0.6

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

WithVersion 设置版本号

type AuthorizerConfig added in v1.0.6

type AuthorizerConfig struct {
	Version      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 GetIssueStats added in v1.0.6

func GetIssueStats(results []BatchResult) BatchStats

GetIssueStats 获取批量签发统计信息

func GetValidationStats added in v1.0.6

func GetValidationStats(results []ValidationResult) BatchStats

GetValidationStats 获取批量验证统计信息

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 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 // 城市

	// 证书参数
	KeySize   int      // RSA密钥大小,默认4096
	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) ClearCache added in v1.0.6

func (ca *CachedAuthorizer) ClearCache()

ClearCache 清空验证缓存

func (*CachedAuthorizer) GetCacheHitRate added in v1.0.6

func (ca *CachedAuthorizer) GetCacheHitRate() float64

GetCacheHitRate 获取缓存命中率

func (*CachedAuthorizer) GetCacheStats added in v1.0.6

func (ca *CachedAuthorizer) GetCacheStats() CacheStats

GetCacheStats 获取缓存统计

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) GetCode added in v1.0.6

func (e *CertError) GetCode() ErrorCode

GetCode 获取错误代码

func (*CertError) GetDetails added in v1.0.6

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

GetDetails 获取错误详情

func (*CertError) GetSuggestions added in v1.0.6

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

GetSuggestions 获取解决建议

func (*CertError) GetType added in v1.0.6

func (e *CertError) GetType() ErrorType

GetType 获取错误类型

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) GetStats added in v1.0.6

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

GetStats 获取监控统计信息

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) 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) GetMachineIDs added in v1.0.6

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

GetMachineIDs 获取所有机器码列表

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) 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) 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 设置证书有效期天数

func (*ClientCertRequestBuilder) WithVersion added in v1.0.6

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

WithVersion 设置程序版本

type ClientInfo

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

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

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

	// 版本信息
	Version            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 {
	Version      string                 `json:"version" yaml:"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"

	// 配置错误代码
	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"
)

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 Identity added in v1.0.6

type Identity struct {
	MachineID  string    // 机器码(可以是多个,用逗号分隔)
	ExpiryDate time.Time // 授权过期日期
}

Identity 身份标识信息

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 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 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) GetStats added in v1.0.6

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

GetStats 获取统计信息

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 重置统计

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) GetSecurityLevel added in v1.0.6

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

GetSecurityLevel 获取安全级别

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) DetectSandbox added in v1.0.6

func (sm *SecurityManager) DetectSandbox() bool

DetectSandbox 检测沙箱环境

func (*SecurityManager) DetectVirtualMachine added in v1.0.6

func (sm *SecurityManager) DetectVirtualMachine() bool

DetectVirtualMachine 检测虚拟机环境

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 停止安全检查

func (*SecurityManager) VerifyIntegrity added in v1.0.6

func (sm *SecurityManager) VerifyIntegrity() error

VerifyIntegrity 验证完整性

type SystemInfoCollector added in v1.0.6

type SystemInfoCollector struct{}

SystemInfoCollector 系统信息收集器

func NewSystemInfoCollector added in v1.0.6

func NewSystemInfoCollector() *SystemInfoCollector

NewSystemInfoCollector 创建系统信息收集器

func (*SystemInfoCollector) GetSystemInfo added in v1.0.6

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

GetSystemInfo 获取系统信息

type Technical added in v1.0.6

type Technical struct {
	Version            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) GetTemplate added in v1.0.6

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

GetTemplate 获取模板

func (*TemplateManager) ListTemplates added in v1.0.6

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

ListTemplates 列出所有可用模板

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 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) Get added in v1.0.6

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

Get 从缓存获取验证结果

func (*ValidationCache) GetHitRate added in v1.0.6

func (vc *ValidationCache) GetHitRate() float64

GetHitRate 获取缓存命中率

func (*ValidationCache) GetStats added in v1.0.6

func (vc *ValidationCache) GetStats() CacheStats

GetStats 获取缓存统计信息

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 获取当前缓存大小

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 {
	MinRequiredVersion string // 最低需要的客户端版本
	CertVersion        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) GetAllStats added in v1.0.6

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

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

func (*WatcherManager) GetWatcher added in v1.0.6

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

GetWatcher 获取监控器

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 停止所有监控器

Jump to

Keyboard shortcuts

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