security

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2025 License: MIT Imports: 19 Imported by: 0

README

Security Package

The security package provides comprehensive plugin verification, digital signature validation, and security audit logging for the HKP plugin system.

Overview

This package implements enterprise-grade security measures to ensure plugin integrity, authenticity, and runtime safety through digital signatures, certificate chain validation, and comprehensive audit logging.

Components

Core Files
  • verification.go - Core verification engine with signature validation
  • sandbox.go - Plugin sandboxing using cgroups and seccomp
  • audit.go - Security audit logging and event tracking
  • certificates.go - Certificate management and chain validation
  • manager.go - Central security manager coordinating all components
  • alerts.go - Security alerting and notification system
  • integration_test.go - Comprehensive security testing

Key Features

Digital Signature Verification
verifier := security.NewPluginVerifier(&security.VerificationConfig{
    RequireSignature: true,
    TrustedKeys: []string{"path/to/trusted.pub"},
    SignatureAlgorithms: []security.SignatureAlgorithm{
        security.SignatureAlgorithmRSA4096,
        security.SignatureAlgorithmEd25519,
    },
})

result, err := verifier.VerifyPlugin("plugin.so")
Plugin Sandboxing
sandboxManager := security.NewSandboxManager(&security.SandboxConfig{
    EnableCgroups: true,
    EnableSeccomp: true,
    ResourceLimits: &security.ResourceLimits{
        MaxMemoryMB: 256,
        MaxCPUPercent: 50,
    },
})

err := sandboxManager.SandboxPlugin("plugin-name", 12345)
Security Audit Logging
auditLogger := security.NewSecurityAuditLogger()
auditLogger.LogPluginSecurityViolation("plugin-name", "signature_invalid", details)

Configuration

Verification Configuration
type VerificationConfig struct {
    RequireSignature    bool
    TrustedKeys        []string
    SignatureAlgorithms []SignatureAlgorithm
    CertificateChains  []string
    RequireCertificate bool
    MaxCertChainLength int
    EnableCRL          bool
    CRLEndpoints       []string
    VerificationTimeout time.Duration
}
Sandbox Configuration
type SandboxConfig struct {
    EnableCgroups     bool
    EnableSeccomp     bool
    CgroupsVersion    string
    ResourceLimits    *ResourceLimits
    AllowedSyscalls   []string
    BlockedSyscalls   []string
    NetworkPolicy     NetworkPolicy
    FilesystemPolicy  FilesystemPolicy
}

Signature Algorithms Supported

  • RSA-2048 - Standard RSA with 2048-bit keys
  • RSA-4096 - Enhanced RSA with 4096-bit keys
  • Ed25519 - Modern elliptic curve signature algorithm
  • ECDSA P-256 - NIST P-256 elliptic curve
  • ECDSA P-384 - NIST P-384 elliptic curve

Security Manager Integration

The security manager coordinates all security components:

manager := security.NewSecurityManager(&security.SecurityConfig{
    Verification: verificationConfig,
    Sandbox:     sandboxConfig,
    Audit:       auditConfig,
    Alerts:      alertConfig,
})

// Comprehensive security check
result, err := manager.SecurePlugin("plugin.so", config)

Audit Events

The system logs various security events:

  • Plugin signature verification results
  • Certificate validation outcomes
  • Sandbox policy violations
  • Resource limit breaches
  • Security configuration changes
  • Plugin loading/unloading events

Testing

The package includes comprehensive tests:

go test ./pkg/security -v

Tests cover:

  • Signature verification with multiple algorithms
  • Certificate chain validation
  • Sandbox enforcement
  • Audit logging functionality
  • Error handling scenarios

Dependencies

  • crypto/rsa - RSA signature verification
  • crypto/ed25519 - Ed25519 signature verification
  • crypto/x509 - Certificate handling
  • golang.org/x/sys/unix - Linux cgroups and seccomp
  • log/slog - Structured logging

Security Considerations

  1. Private Key Protection - Signing keys must be stored securely
  2. Certificate Validation - Always validate certificate chains
  3. Sandbox Escapes - Monitor for sandbox bypass attempts
  4. Audit Integrity - Protect audit logs from tampering
  5. Resource Monitoring - Watch for resource exhaustion attacks

Future Enhancements

  • Hardware Security Module (HSM) integration
  • Advanced threat detection using ML
  • Automated security policy generation
  • Integration with external PKI systems
  • Real-time security dashboards

Documentation

Overview

Package security provides plugin verification and security management

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CGroup

type CGroup struct {
	Name        string
	Path        string
	MemoryLimit int64
	CPULimit    float64
	PIDLimit    int64
	CreatedAt   time.Time
	Active      bool
}

CGroup represents a control group for resource management

type CacheEntry

type CacheEntry struct {
	Result    *VerificationResult
	Timestamp time.Time
	Hash      string
}

CacheEntry represents a cached verification result

type CertificateInfo

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"`
	Fingerprint  string    `json:"fingerprint"`
	KeyUsage     []string  `json:"key_usage"`
}

CertificateInfo contains certificate metadata

type CertificateMetadata

type CertificateMetadata struct {
	Fingerprint   string                 `json:"fingerprint"`
	AddedAt       time.Time              `json:"added_at"`
	AddedBy       string                 `json:"added_by"`
	TrustLevel    TrustLevel             `json:"trust_level"`
	Revoked       bool                   `json:"revoked"`
	RevokedAt     *time.Time             `json:"revoked_at,omitempty"`
	RevokedReason string                 `json:"revoked_reason,omitempty"`
	Attributes    map[string]interface{} `json:"attributes"`
}

CertificateMetadata contains additional certificate information

type CertificateStore

type CertificateStore interface {
	AddCertificate(cert *x509.Certificate) error
	RemoveCertificate(fingerprint string) error
	GetCertificate(fingerprint string) (*x509.Certificate, error)
	ListCertificates() ([]*x509.Certificate, error)
	VerifyChain(cert *x509.Certificate) error
}

CertificateStore manages trusted certificates

type EnforcementLevel

type EnforcementLevel string

EnforcementLevel determines how strictly security policies are enforced

const (
	EnforcementPermissive EnforcementLevel = "permissive" // Log violations but allow
	EnforcementWarning    EnforcementLevel = "warning"    // Log violations and warn
	EnforcementStrict     EnforcementLevel = "strict"     // Block violations
	EnforcementBlocking   EnforcementLevel = "blocking"   // Block and terminate
)

type FileCertificateStore

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

FileCertificateStore implements CertificateStore using filesystem storage

func NewFileCertificateStore

func NewFileCertificateStore(storePath string, auditLogger SecurityAuditLogger) (*FileCertificateStore, error)

NewFileCertificateStore creates a new file-based certificate store

func (*FileCertificateStore) AddCertificate

func (fs *FileCertificateStore) AddCertificate(cert *x509.Certificate) error

AddCertificate adds a certificate to the store

func (*FileCertificateStore) AddCertificateWithMetadata

func (fs *FileCertificateStore) AddCertificateWithMetadata(cert *x509.Certificate, metadata *CertificateMetadata) error

AddCertificateWithMetadata adds a certificate with specific metadata

func (*FileCertificateStore) GetCertificate

func (fs *FileCertificateStore) GetCertificate(fingerprint string) (*x509.Certificate, error)

GetCertificate retrieves a certificate by fingerprint

func (*FileCertificateStore) GetCertificateMetadata

func (fs *FileCertificateStore) GetCertificateMetadata(fingerprint string) (*CertificateMetadata, error)

GetCertificateMetadata retrieves metadata for a certificate

func (*FileCertificateStore) ListCertificates

func (fs *FileCertificateStore) ListCertificates() ([]*x509.Certificate, error)

ListCertificates returns all certificates in the store

func (*FileCertificateStore) RemoveCertificate

func (fs *FileCertificateStore) RemoveCertificate(fingerprint string) error

RemoveCertificate removes a certificate from the store

func (*FileCertificateStore) RevokeCertificate

func (fs *FileCertificateStore) RevokeCertificate(fingerprint string, reason string) error

RevokeCertificate marks a certificate as revoked

func (*FileCertificateStore) VerifyChain

func (fs *FileCertificateStore) VerifyChain(cert *x509.Certificate) error

VerifyChain verifies a certificate chain

type FileSecurityAuditLogger

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

FileSecurityAuditLogger implements SecurityAuditLogger using file-based logging

func NewFileSecurityAuditLogger

func NewFileSecurityAuditLogger(logPath string) (*FileSecurityAuditLogger, error)

NewFileSecurityAuditLogger creates a new file-based security audit logger

func (*FileSecurityAuditLogger) Close

func (fsal *FileSecurityAuditLogger) Close() error

Close closes the audit logger

func (*FileSecurityAuditLogger) Flush

func (fsal *FileSecurityAuditLogger) Flush()

Flush forces a flush of buffered events

func (*FileSecurityAuditLogger) GetAuditEvents

func (fsal *FileSecurityAuditLogger) GetAuditEvents(limit int, filter map[string]interface{}) ([]*SecurityAuditEvent, error)

GetAuditEvents retrieves audit events from the log file

func (*FileSecurityAuditLogger) LogCertificateOperation

func (fsal *FileSecurityAuditLogger) LogCertificateOperation(operation string, cert *CertificateInfo)

LogCertificateOperation logs certificate management operations

func (*FileSecurityAuditLogger) LogFailureRecovery

func (fsal *FileSecurityAuditLogger) LogFailureRecovery(pluginName string, failureType string, recoveryAction string, success bool)

LogFailureRecovery logs automatic failure recovery events

func (*FileSecurityAuditLogger) LogPluginSecurityViolation

func (fsal *FileSecurityAuditLogger) LogPluginSecurityViolation(pluginName string, violation string, details map[string]interface{})

LogPluginSecurityViolation logs security violations by plugins

func (*FileSecurityAuditLogger) LogResourceViolation

func (fsal *FileSecurityAuditLogger) LogResourceViolation(pluginName string, resource string, limit interface{}, actual interface{})

LogResourceViolation logs resource limit violations

func (*FileSecurityAuditLogger) LogSecurityEvent

func (fsal *FileSecurityAuditLogger) LogSecurityEvent(eventType string, details map[string]interface{})

LogSecurityEvent logs a general security event

func (*FileSecurityAuditLogger) LogVerification

func (fsal *FileSecurityAuditLogger) LogVerification(pluginPath string, result *VerificationResult)

LogVerification logs a plugin verification event

type PluginVerifier

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

PluginVerifier handles plugin signature verification and trust management

func NewPluginVerifier

func NewPluginVerifier(certStore CertificateStore, auditLogger SecurityAuditLogger) *PluginVerifier

NewPluginVerifier creates a new plugin verifier instance

func (*PluginVerifier) VerifyPlugin

func (pv *PluginVerifier) VerifyPlugin(pluginPath string) (*VerificationResult, error)

VerifyPlugin verifies a plugin's signature and integrity

type RevocationStatus

type RevocationStatus string

RevocationStatus indicates certificate revocation status

const (
	RevocationStatusValid   RevocationStatus = "valid"
	RevocationStatusRevoked RevocationStatus = "revoked"
	RevocationStatusUnknown RevocationStatus = "unknown"
)

type SandboxConfig

type SandboxConfig struct {
	EnableCGroups      bool     `json:"enable_cgroups"`
	EnableSeccomp      bool     `json:"enable_seccomp"`
	CGroupRoot         string   `json:"cgroup_root"`
	MaxMemoryMB        int64    `json:"max_memory_mb"`
	MaxCPUPercent      float64  `json:"max_cpu_percent"`
	MaxProcesses       int64    `json:"max_processes"`
	AllowedSyscalls    []string `json:"allowed_syscalls"`
	BlockedSyscalls    []string `json:"blocked_syscalls"`
	NetworkIsolation   bool     `json:"network_isolation"`
	FilesystemReadOnly bool     `json:"filesystem_readonly"`
	TempDirPath        string   `json:"temp_dir_path"`
	AllowedDirectories []string `json:"allowed_directories"`
	DeniedDirectories  []string `json:"denied_directories"`
}

SandboxConfig contains sandboxing configuration

func DefaultSandboxConfig

func DefaultSandboxConfig() *SandboxConfig

DefaultSandboxConfig returns a default sandbox configuration

type SandboxManager

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

SandboxManager manages plugin sandboxing using cgroups and seccomp

func NewSandboxManager

func NewSandboxManager(config *SandboxConfig, auditLogger SecurityAuditLogger, logger *slog.Logger) (*SandboxManager, error)

NewSandboxManager creates a new sandbox manager

func (*SandboxManager) CreateSandbox

func (sm *SandboxManager) CreateSandbox(pluginName string) (*SandboxedProcess, error)

CreateSandbox creates a new sandbox for a plugin

func (*SandboxManager) DestroySandbox

func (sm *SandboxManager) DestroySandbox(sandbox *SandboxedProcess) error

DestroySandbox cleans up a sandbox

func (*SandboxManager) GetSandboxStatus

func (sm *SandboxManager) GetSandboxStatus() map[string]interface{}

GetSandboxStatus returns status information about active sandboxes

func (*SandboxManager) MonitorSandboxes

func (sm *SandboxManager) MonitorSandboxes(ctx context.Context)

MonitorSandboxes monitors resource usage of sandboxed processes

func (*SandboxManager) RunInSandbox

func (sm *SandboxManager) RunInSandbox(sandbox *SandboxedProcess, command string, args []string) error

RunInSandbox executes a command in the sandbox

type SandboxedProcess

type SandboxedProcess struct {
	PID        int
	PluginName string
	CGroupPath string
	StartTime  time.Time
	Command    *exec.Cmd
	Context    context.Context
	Cancel     context.CancelFunc
}

SandboxedProcess represents a process running in a sandbox

type SeccompProfile

type SeccompProfile struct {
	DefaultAction string        `json:"default_action"`
	Syscalls      []SyscallRule `json:"syscalls"`
	Architectures []string      `json:"architectures"`
	Flags         []string      `json:"flags"`
}

SeccompProfile defines syscall filtering rules

type SecurityAuditEvent

type SecurityAuditEvent struct {
	Timestamp time.Time              `json:"timestamp"`
	EventType string                 `json:"event_type"`
	Source    string                 `json:"source"`
	Actor     string                 `json:"actor,omitempty"`
	Target    string                 `json:"target,omitempty"`
	Result    string                 `json:"result"`
	Details   map[string]interface{} `json:"details"`
	Severity  SeverityLevel          `json:"severity"`
	RequestID string                 `json:"request_id,omitempty"`
	SessionID string                 `json:"session_id,omitempty"`
}

SecurityAuditEvent represents a security audit event

type SecurityAuditLogger

type SecurityAuditLogger interface {
	LogVerification(pluginPath string, result *VerificationResult)
	LogCertificateOperation(operation string, cert *CertificateInfo)
	LogSecurityEvent(event string, details map[string]interface{})
	LogPluginSecurityViolation(pluginName string, violation string, details map[string]interface{})
	LogResourceViolation(pluginName string, resource string, limit interface{}, actual interface{})
	LogFailureRecovery(pluginName string, failureType string, recoveryAction string, success bool)
}

SecurityAuditLogger logs security events

type SecurityCheckResult

type SecurityCheckResult struct {
	Allowed      bool                `json:"allowed"`
	Reason       string              `json:"reason,omitempty"`
	Verification *VerificationResult `json:"verification,omitempty"`
	Violations   []SecurityViolation `json:"violations,omitempty"`
	Timestamp    time.Time           `json:"timestamp"`
}

SecurityCheckResult represents the result of a security check

type SecurityConfig

type SecurityConfig struct {
	RequireSignature     bool                 `json:"require_signature"`
	EnforcementLevel     EnforcementLevel     `json:"enforcement_level"`
	TrustedCertificates  []string             `json:"trusted_certificates"`
	CertificateStorePath string               `json:"certificate_store_path"`
	AuditLogPath         string               `json:"audit_log_path"`
	VerificationCacheTTL time.Duration        `json:"verification_cache_ttl"`
	AllowSelfSigned      bool                 `json:"allow_self_signed"`
	RequiredKeyUsage     []x509.KeyUsage      `json:"required_key_usage"`
	MinKeySize           int                  `json:"min_key_size"`
	AllowedAlgorithms    []SignatureAlgorithm `json:"allowed_algorithms"`
	SandboxConfig        *SandboxConfig       `json:"sandbox_config"`
}

SecurityConfig contains security configuration

func DefaultSecurityConfig

func DefaultSecurityConfig() *SecurityConfig

DefaultSecurityConfig returns a default security configuration

type SecurityManager

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

SecurityManager coordinates all security operations for plugins

func NewSecurityManager

func NewSecurityManager(config *SecurityConfig, logger *slog.Logger) (*SecurityManager, error)

NewSecurityManager creates a new security manager

func (*SecurityManager) AddTrustedCertificate

func (sm *SecurityManager) AddTrustedCertificate(cert *x509.Certificate, trustLevel TrustLevel) error

AddTrustedCertificate adds a trusted certificate to the store

func (*SecurityManager) CheckPluginSecurity

func (sm *SecurityManager) CheckPluginSecurity(pluginPath string) (*SecurityCheckResult, error)

CheckPluginSecurity performs comprehensive security check on a plugin

func (*SecurityManager) Close

func (sm *SecurityManager) Close() error

Close gracefully shuts down the security manager

func (*SecurityManager) CreatePluginSandbox

func (sm *SecurityManager) CreatePluginSandbox(pluginName string) (*SandboxedProcess, error)

CreatePluginSandbox creates a sandbox for a plugin

func (*SecurityManager) DestroyPluginSandbox

func (sm *SecurityManager) DestroyPluginSandbox(sandbox *SandboxedProcess) error

DestroyPluginSandbox destroys a plugin sandbox

func (*SecurityManager) GetSecurityStatus

func (sm *SecurityManager) GetSecurityStatus() map[string]interface{}

GetSecurityStatus returns current security system status

func (*SecurityManager) GetTrustedCertificates

func (sm *SecurityManager) GetTrustedCertificates() ([]*x509.Certificate, error)

GetTrustedCertificates returns all trusted certificates

func (*SecurityManager) RevokeCertificate

func (sm *SecurityManager) RevokeCertificate(fingerprint string, reason string) error

RevokeCertificate revokes a certificate

func (*SecurityManager) RunPluginInSandbox

func (sm *SecurityManager) RunPluginInSandbox(sandbox *SandboxedProcess, command string, args []string) error

RunPluginInSandbox executes a plugin in its sandbox

func (*SecurityManager) UpdateEnforcementLevel

func (sm *SecurityManager) UpdateEnforcementLevel(level EnforcementLevel)

UpdateEnforcementLevel updates the security enforcement level

type SecurityViolation

type SecurityViolation struct {
	Type        string                 `json:"type"`
	Severity    SeverityLevel          `json:"severity"`
	Description string                 `json:"description"`
	Details     map[string]interface{} `json:"details"`
}

SecurityViolation represents a security policy violation

type SeverityLevel

type SeverityLevel string

SeverityLevel represents the severity of a security event

const (
	SeverityInfo     SeverityLevel = "info"
	SeverityWarning  SeverityLevel = "warning"
	SeverityError    SeverityLevel = "error"
	SeverityCritical SeverityLevel = "critical"
)

type SignatureAlgorithm

type SignatureAlgorithm string

SignatureAlgorithm represents supported signature algorithms

const (
	AlgorithmRSA4096 SignatureAlgorithm = "RSA-4096"
	AlgorithmEd25519 SignatureAlgorithm = "Ed25519"
	AlgorithmECDSA   SignatureAlgorithm = "ECDSA-P256"
)

type SyscallArgument

type SyscallArgument struct {
	Index    int    `json:"index"`
	Value    uint64 `json:"value"`
	ValueTwo uint64 `json:"value_two,omitempty"`
	Op       string `json:"op"`
}

SyscallArgument defines argument constraints for syscalls

type SyscallRule

type SyscallRule struct {
	Names  []string          `json:"names"`
	Action string            `json:"action"`
	Args   []SyscallArgument `json:"args,omitempty"`
}

SyscallRule defines rules for individual syscalls

type TrustLevel

type TrustLevel string

TrustLevel represents the level of trust for a certificate

const (
	TrustLevelRoot         TrustLevel = "root"
	TrustLevelIntermediate TrustLevel = "intermediate"
	TrustLevelLeaf         TrustLevel = "leaf"
	TrustLevelUntrusted    TrustLevel = "untrusted"
)

type VerificationCache

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

VerificationCache caches verification results

func NewVerificationCache

func NewVerificationCache(maxAge time.Duration) *VerificationCache

NewVerificationCache creates a new verification cache

func (*VerificationCache) Clear

func (vc *VerificationCache) Clear()

Clear removes expired entries from cache

func (*VerificationCache) Get

func (vc *VerificationCache) Get(hash string) *CacheEntry

Get retrieves a cached verification result

func (*VerificationCache) Set

func (vc *VerificationCache) Set(hash string, result *VerificationResult)

Set stores a verification result in cache

type VerificationResult

type VerificationResult struct {
	Valid            bool               `json:"valid"`
	Algorithm        SignatureAlgorithm `json:"algorithm"`
	Certificate      *CertificateInfo   `json:"certificate"`
	Timestamp        time.Time          `json:"timestamp"`
	Error            string             `json:"error,omitempty"`
	TrustChain       []*CertificateInfo `json:"trust_chain"`
	RevocationStatus RevocationStatus   `json:"revocation_status"`
}

VerificationResult contains the result of plugin verification

Jump to

Keyboard shortcuts

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