Documentation
¶
Index ¶
- Constants
- func ApplyTemplateToRequest(req *ClientCertRequest, templateName string) error
- func CanonicalPayload(payload LicensePayload) ([]byte, error)
- func DecodeObfuscated(encoded string, key byte) (string, error)
- func DemoSecurityCheck()
- func DemoSecurityConfiguration()
- func DemoSecurityFeatures()
- func DemoSecurityLevels()
- func DemonstrateKeySizeDetection()
- func Example10_ExtractClientInfo()
- func Example11_CertificateWatching()
- func Example1_BasicUsage()
- func Example2_WithCache()
- func Example3_BatchOperations()
- func Example4_ConfigurationFile()
- func Example5_PresetConfigurations()
- func Example6_CertificateInspection()
- func Example7_PerformanceMonitoring()
- func Example8_ErrorHandling()
- func Example9_SystemInfoCollection()
- func FormatDuration(d time.Duration) string
- func FormatFileSize(bytes int64) string
- func GenerateDefaultConfig(filePath string) error
- func GenerateLicenseKeyPairPEM() (publicKeyPEM, privateKeyPEM []byte, err error)
- func GetDebuggerString() string
- func GetTraceString() string
- func IsConfigError(err error) bool
- func IsSecurityError(err error) bool
- func IsValidMachineID(machineID string) bool
- func IsValidationError(err error) bool
- func IssueLicense(payload LicensePayload, privateKey ed25519.PrivateKey) ([]byte, error)
- func ParseEd25519PrivateKeyPEM(privateKeyPEM []byte) (ed25519.PrivateKey, error)
- func ParseEd25519PublicKeyPEM(publicKeyPEM []byte) (ed25519.PublicKey, error)
- func RunSecurityDemo()
- func SaveConfig(config *ConfigFile, filePath string) error
- func ShowSecurityConfig()
- func ShowUsageExamples()
- func TestSecurityLevels()
- func ValidateEmail(email string) bool
- func ValidatePhoneNumber(phone string) bool
- func ValidateRequestWithGlobalTemplate(req *ClientCertRequest, templateName string) error
- func VerifySnapshot(snapshot *HardwareSnapshot, appID string, allowedDeviation float64) error
- type Address
- type Authorizer
- func (a *Authorizer) CACertPEM() []byte
- func (a *Authorizer) Config() AuthorizerConfig
- func (a *Authorizer) ExtractClientInfo(certPEM []byte) (*ClientInfo, error)
- func (a *Authorizer) GenerateCA(info CAInfo) error
- func (a *Authorizer) GetCurrentCertVersion() string
- func (a *Authorizer) GetSecurityLevel() int
- func (a *Authorizer) InitSecurityManager() *SecurityManager
- func (a *Authorizer) IssueClientCert(req *ClientCertRequest) (*Certificate, error)
- func (a *Authorizer) NewBatchIssue() *BatchIssueBuilder
- func (a *Authorizer) NewBatchManager() *BatchManager
- func (a *Authorizer) NewBatchValidate() *BatchValidateBuilder
- func (a *Authorizer) PerformSecurityCheck() error
- func (a *Authorizer) SaveCA(dirPath ...string) error
- func (a *Authorizer) SaveClientCert(cert *Certificate, dirPath ...string) error
- func (a *Authorizer) SetCurrentCertVersion(version string)
- func (a *Authorizer) ValidateCert(certPEM []byte, machineID string) error
- func (a *Authorizer) ValidateWithSecurity(certPEM []byte, machineID string) error
- func (a *Authorizer) Watch(certPEM []byte, machineID string, callback WatchCallback, ...) (*CertWatcher, error)
- func (a *Authorizer) WithCache() *CachedAuthorizer
- type AuthorizerBuilder
- func (b *AuthorizerBuilder) Apply(opts ...Option) *AuthorizerBuilder
- func (b *AuthorizerBuilder) Build() (*Authorizer, error)
- func (b *AuthorizerBuilder) BuildWithCache() (*CachedAuthorizer, error)
- func (b *AuthorizerBuilder) DisableSecurity() *AuthorizerBuilder
- func (b *AuthorizerBuilder) EnableAntiDebug(enable bool) *AuthorizerBuilder
- func (b *AuthorizerBuilder) EnableTimeValidation(enable bool) *AuthorizerBuilder
- func (b *AuthorizerBuilder) RequireHardwareBinding(require bool) *AuthorizerBuilder
- func (b *AuthorizerBuilder) UseCustomCA(cert, key []byte) *AuthorizerBuilder
- func (b *AuthorizerBuilder) UseDefaultCA() *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithBasicSecurity() *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithCA(cert, key []byte) *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithCache(cache CacheConfig) *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithCacheConfig(config CacheConfig) *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithCacheSize(size int) *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithCacheTTL(ttl time.Duration) *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithCriticalSecurity() *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithEnterpriseID(id int) *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithMaxClockSkew(skew time.Duration) *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithRelaxedSecurity() *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithRuntimeVersion(version string) *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithSecureDefaults() *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithSecurity(security SecurityConfig) *AuthorizerBuilder
- func (b *AuthorizerBuilder) WithSecurityLevel(level int) *AuthorizerBuilder
- type AuthorizerConfig
- type BatchIssueBuilder
- func (bb *BatchIssueBuilder) AddRequest(req *ClientCertRequest) *BatchIssueBuilder
- func (bb *BatchIssueBuilder) AddRequests(requests ...*ClientCertRequest) *BatchIssueBuilder
- func (bb *BatchIssueBuilder) Execute() []BatchResult
- func (bb *BatchIssueBuilder) WithMaxWorkers(workers int) *BatchIssueBuilder
- type BatchManager
- type BatchResult
- type BatchStats
- type BatchValidateBuilder
- func (bv *BatchValidateBuilder) AddValidation(certPEM []byte, machineID string) *BatchValidateBuilder
- func (bv *BatchValidateBuilder) AddValidations(validations ...CertValidation) *BatchValidateBuilder
- func (bv *BatchValidateBuilder) Execute() []ValidationResult
- func (bv *BatchValidateBuilder) WithMaxWorkers(workers int) *BatchValidateBuilder
- type BindingInfo
- type CAConfiguration
- type CAInfo
- type CacheConfig
- type CacheConfiguration
- type CacheEntry
- type CacheStats
- type CachedAuthorizer
- type CertError
- func NewCertificateError(code ErrorCode, message string, cause error) *CertError
- func NewConfigError(code ErrorCode, message string, cause error) *CertError
- func NewSecurityError(code ErrorCode, message string, cause error) *CertError
- func NewSystemError(code ErrorCode, message string, cause error) *CertError
- func NewValidationError(code ErrorCode, message string, cause error) *CertError
- func (e *CertError) Error() string
- func (e *CertError) ErrorCode() ErrorCode
- func (e *CertError) ErrorDetails() map[string]interface{}
- func (e *CertError) ErrorSuggestions() []string
- func (e *CertError) ErrorType() ErrorType
- func (e *CertError) Is(target error) bool
- func (e *CertError) Unwrap() error
- func (e *CertError) WithDetail(key string, value interface{}) *CertError
- func (e *CertError) WithSuggestion(suggestion string) *CertError
- type CertTemplate
- type CertValidation
- type CertWatcher
- func (w *CertWatcher) IsRunning() bool
- func (w *CertWatcher) Start() error
- func (w *CertWatcher) Stats() map[string]interface{}
- func (w *CertWatcher) Stop()
- func (w *CertWatcher) WithCheckInterval(interval time.Duration) *CertWatcher
- func (w *CertWatcher) WithConfig(config *WatchConfig) *CertWatcher
- func (w *CertWatcher) WithExpiryWarning(period time.Duration) *CertWatcher
- type Certificate
- type CertificateChainValidator
- type CertificateInfo
- type CertificateInspector
- type ClientCertRequest
- type ClientCertRequestBuilder
- func (b *ClientCertRequestBuilder) Build() (*ClientCertRequest, error)
- func (b *ClientCertRequestBuilder) WithAddress(country, province, city, street string) *ClientCertRequestBuilder
- func (b *ClientCertRequestBuilder) WithBindingInfo(mode, provider string) *ClientCertRequestBuilder
- func (b *ClientCertRequestBuilder) WithBindingResult(result *machineid.BindingResult) *ClientCertRequestBuilder
- func (b *ClientCertRequestBuilder) WithCompany(name, department string) *ClientCertRequestBuilder
- func (b *ClientCertRequestBuilder) WithContact(person, phone, email string) *ClientCertRequestBuilder
- func (b *ClientCertRequestBuilder) WithExpiry(expiryDate time.Time) *ClientCertRequestBuilder
- func (b *ClientCertRequestBuilder) WithMachineID(machineID string) *ClientCertRequestBuilder
- func (b *ClientCertRequestBuilder) WithMinClientVersion(version string) *ClientCertRequestBuilder
- func (b *ClientCertRequestBuilder) WithTemplate(templateName string) *ClientCertRequestBuilder
- func (b *ClientCertRequestBuilder) WithValidityDays(days int) *ClientCertRequestBuilder
- type ClientInfo
- type Company
- type ConfigFile
- type ConfigLoader
- type Contact
- type ErrorCode
- type ErrorType
- type HardwareSnapshot
- type Identity
- type License
- type LicensePayload
- type LoggingConfiguration
- type MonotonicTime
- type ObfuscatedString
- type OperationStats
- type Option
- func WithAdvancedSecurity() Option
- func WithContainerSupport(config interface{}) Option
- func WithFullSecurity() Option
- func WithHardwareBinding(mode string) Option
- func WithMonotonicTime(persistencePath string, maxClockSkew time.Duration) Option
- func WithOfflineValidation(snapshotPath string) Option
- func WithSecurityPreset(preset string) Option
- func WithSignedCache(signKey []byte, config CacheConfig) Option
- type PerformanceMonitor
- type RevokeInfo
- type RevokeList
- type RevokeManager
- type RevokeOption
- type SecurityConfig
- type SecurityConfiguration
- type SecurityManager
- func (sm *SecurityManager) Check() error
- func (sm *SecurityManager) Close()
- func (sm *SecurityManager) DetectSandbox() bool
- func (sm *SecurityManager) DetectVirtualMachine() bool
- func (sm *SecurityManager) GetDebuggerCount() int
- func (sm *SecurityManager) ProtectProcess() error
- func (sm *SecurityManager) StopSecurityChecks()
- func (sm *SecurityManager) VerifyIntegrity() error
- type SignedCacheEntry
- type SignedValidationCache
- func (svc *SignedValidationCache) ExportSignedEntry(certPEM []byte, machineID string) (*SignedCacheEntry, error)
- func (svc *SignedValidationCache) GetWithVerification(certPEM []byte, machineID string, signedEntry *SignedCacheEntry) (error, bool)
- func (svc *SignedValidationCache) StoreWithSignature(certPEM []byte, machineID string, result error, snapshotID string) (*SignedCacheEntry, error)
- type SystemInfoCollector
- type Technical
- type TemplateManager
- func (tm *TemplateManager) AddTemplate(name string, template *CertTemplate) error
- func (tm *TemplateManager) ApplyTemplate(req *ClientCertRequest, templateName string) error
- func (tm *TemplateManager) ListTemplates() map[string]*CertTemplate
- func (tm *TemplateManager) Template(name string) (*CertTemplate, error)
- func (tm *TemplateManager) ValidateRequestWithTemplate(req *ClientCertRequest, templateName string) error
- type TemplateSecurityLevel
- type TimeDetectionConfig
- type ValidationCache
- func (vc *ValidationCache) Clear()
- func (vc *ValidationCache) Close()
- func (vc *ValidationCache) Get(certPEM []byte, machineID string) (error, bool)
- func (vc *ValidationCache) HitRate() float64
- func (vc *ValidationCache) Put(certPEM []byte, machineID string, result error)
- func (vc *ValidationCache) Size() int
- func (vc *ValidationCache) Stats() CacheStats
- type ValidationResult
- type VersionInfo
- type WatchCallback
- type WatchConfig
- type WatchEvent
- type WatcherManager
Constants ¶
const ( SecurityLevelDisabled = 0 // 完全禁用(默认) SecurityLevelBasic = 1 // 基础防护(仅基本调试器检测) SecurityLevelAdvanced = 2 // 高级防护(完整反逆向保护) SecurityLevelCritical = 3 // 关键防护(最高级别保护) )
SecurityLevel 安全防护级别
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
DecodeObfuscated 从 Base64 解码。
func DemoSecurityConfiguration ¶ added in v1.0.6
func DemoSecurityConfiguration()
DemoSecurityConfiguration 演示不同配置方式
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 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
FormatDuration 格式化时长显示
func FormatFileSize ¶ added in v1.0.6
FormatFileSize 格式化文件大小
func GenerateDefaultConfig ¶ added in v1.0.6
GenerateDefaultConfig 生成默认配置文件
func GenerateLicenseKeyPairPEM ¶ added in v1.0.9
GenerateLicenseKeyPairPEM 生成 Ed25519 license key pair(PKCS#8 PEM)。
func GetDebuggerString ¶ added in v1.0.9
func GetDebuggerString() string
GetDebuggerString 获取 "debugger" 字符串。
func IsSecurityError ¶ added in v1.0.6
IsSecurityError 检查是否为安全错误
func IsValidMachineID ¶ added in v1.0.6
IsValidMachineID 验证机器ID格式
func IsValidationError ¶ added in v1.0.6
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 SaveConfig ¶ added in v1.0.6
func SaveConfig(config *ConfigFile, filePath string) error
SaveConfig 保存配置到文件
func ValidatePhoneNumber ¶ added in v1.0.6
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 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
func (bb *BatchIssueBuilder) AddRequest(req *ClientCertRequest) *BatchIssueBuilder
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
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
NewCertificateError 创建证书错误
func NewConfigError ¶ added in v1.0.6
NewConfigError 创建配置错误
func NewSecurityError ¶ added in v1.0.6
NewSecurityError 创建安全错误
func NewSystemError ¶ added in v1.0.6
NewSystemError 创建系统错误
func NewValidationError ¶ added in v1.0.6
NewValidationError 创建验证错误
func (*CertError) ErrorDetails ¶ added in v1.0.9
ErrorDetails 返回错误详情
func (*CertError) ErrorSuggestions ¶ added in v1.0.9
ErrorSuggestions 返回解决建议
func (*CertError) WithDetail ¶ added in v1.0.6
WithDetail 添加错误详情
func (*CertError) WithSuggestion ¶ added in v1.0.6
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
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) Stats ¶ added in v1.0.9
func (w *CertWatcher) Stats() map[string]interface{}
Stats 获取监控统计信息
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
func (b *ClientCertRequestBuilder) Build() (*ClientCertRequest, error)
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
func (b *ClientCertRequestBuilder) WithBindingResult(result *machineid.BindingResult) *ClientCertRequestBuilder
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 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 (*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 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" 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 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
WithHardwareBinding 配置硬件绑定模式
参数:
- mode: 绑定模式(fingerprint/mac/machine_id/custom)
使用示例:
WithHardwareBinding(machineid.BindingModeFingerprint)
func WithMonotonicTime ¶ added in v1.0.9
WithMonotonicTime 配置单调时间检查
参数:
- persistencePath: 时间戳持久化路径
- maxClockSkew: 允许的最大时钟偏差
使用示例:
WithMonotonicTime("./.timestamp", 5*time.Minute)
func WithOfflineValidation ¶ added in v1.0.9
WithOfflineValidation 配置离线验证支持
参数:
- snapshotPath: 硬件快照存储路径
使用示例:
WithOfflineValidation("./snapshots")
func WithSecurityPreset ¶ added in v1.0.9
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) 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 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) 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 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) 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) 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 获取监控器