security

package
v0.0.0-...-1f1a93d Latest Latest
Warning

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

Go to latest
Published: May 13, 2026 License: MIT Imports: 21 Imported by: 0

README

Security Audit Framework - Configuration and Usage Guide

Overview

⚠️ IMPORTANT NOTICE (2026-02-24)

The ask action is currently mapped to deny for security reasons.

  • Rules with "action": "ask" will block operations
  • This is temporary until the interactive approval workflow is implemented
  • See Important Notes section for details

Workaround: Change "action": "ask" to "action": "allow" in config if needed

The Security Audit Framework provides centralized security controls for all dangerous operations in NemesisBot, similar to how antivirus software monitors system operations.

Architecture

┌─────────────────────────────────────────────────────────────┐
│                    Security Auditor                         │
│  ┌─────────────┐  ┌──────────────┐  ┌─────────────────┐     │
│  │  Policies   │  │ Permissions  │  │  Audit Log      │     │
│  └─────────────┘  └──────────────┘  └─────────────────┘     │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                  Security Middleware                        │
│  ┌──────────┐ ┌──────────┐ ┌─────────┐ ┌──────────────┐     │
│  │   File   │ │ Process  │ │ Network │ │   Hardware   │     │
│  │ Wrapper  │ │ Wrapper  │ │ Wrapper │ │   Wrapper    │     │
│  └──────────┘ └──────────┘ └─────────┘ └──────────────┘     │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                       Tools Layer                           │
│  exec_tool, filesystem, web_fetch, i2c, spi, etc.           │
└─────────────────────────────────────────────────────────────┘

Operation Types and Danger Levels

Category Operation Type Danger Level Description
File file_read LOW Reading file contents
File file_write HIGH Creating/overwriting files
File file_delete HIGH Deleting files
File file_edit MEDIUM Editing existing files
File file_append MEDIUM Appending to files
File dir_create HIGH Creating directories
File dir_delete HIGH Deleting directories
File dir_list LOW Listing directory contents
Process process_exec CRITICAL Executing shell commands
Process process_spawn HIGH Spawning new processes
Process process_kill CRITICAL Terminating processes
Registry registry_read MEDIUM Reading registry (Windows)
Registry registry_write CRITICAL Writing registry
Registry registry_delete CRITICAL Deleting registry entries
Network network_download MEDIUM Downloading files
Network network_upload MEDIUM Uploading files
Network network_request LOW Making HTTP requests
Hardware hardware_i2c LOW I2C bus operations
Hardware hardware_spi LOW SPI bus operations
Hardware hardware_gpio LOW GPIO operations
System system_shutdown CRITICAL Shutting down system
System system_reboot CRITICAL Rebooting system
System system_config HIGH Modifying system config
System system_service HIGH Managing services
System system_install CRITICAL Installing software

Configuration Example

1. Basic Setup
package main

import (
    "github.com/276793422/NemesisBot/module/security"
)

func main() {
    // Create security auditor
    config := &security.AuditorConfig{
        Enabled:               true,
        LogAllOperations:      true,
        LogDenialsOnly:        false,
        ApprovalTimeout:       5 * time.Minute,
        MaxPendingRequests:    100,
        AuditLogRetentionDays: 90,
        AuditLogPath:          "/var/log/nemesisbot/audit.csv",
        SynchronousMode:       false,
        PolicyEngine:          "abac",
    }

    auditor := security.NewSecurityAuditor(config)

    // Create default policies
    security.CreateDefaultPolicies(auditor)

    // Set permissions for different users
    auditor.SetPermission("cli", security.CreateCLIPermission())
    auditor.SetPermission("web", security.CreateWebPermission())
    auditor.SetPermission("agent:default", security.CreateAgentPermission("default"))

    // Use the security middleware
    middleware := security.NewSecurityMiddleware(auditor, "user_id", "cli", "/workspace")
}
2. Custom Policy Example
// Create a policy to protect sensitive files
protectConfigPolicy := &security.Policy{
    Name:        "protect_config",
    Description: "Protect configuration files",
    Enabled:     true,
    Rules: []security.PolicyRule{
        {
            Name:        "block_config_write",
            MatchOpType: security.OpFileWrite,
            MatchTarget: "\\.json$|\\.yaml$|\\.toml$",
            MatchSource: "web|telegram",
            Action:      "deny",
            Reason:      "Config file writes from web/telegram are blocked",
        },
        {
            Name:        "require_approval",
            MatchOpType: security.OpFileDelete,
            MatchTarget: "\\.md$",
            Action:      "require_approval",
            Reason:      "Deleting markdown files requires approval",
        },
    },
    DefaultAction: "allow",
}

auditor.RegisterPolicy(protectConfigPolicy)
3. Permission Profiles
// Restrictive profile for web users
webProfile := &security.Permission{
    AllowedTypes: map[security.OperationType]bool{
        security.OpFileRead:   true,
        security.OpFileWrite:  true,
        security.OpDirList:    true,
    },
    AllowedTargets: []string{
        "^/workspace/",  // Only workspace directory
    },
    DeniedTargets: []string{
        "\\.env$",           // Environment files
        "\\.key$",           // Private keys
        "\\.pem$",           // Certificates
    },
    RequireApproval: map[security.OperationType]bool{
        security.OpFileDelete:   true,
        security.OpNetworkDownload: true,
    },
    MaxDangerLevel: security.DangerMedium,
}

auditor.SetPermission("web", webProfile)

Integration with Existing Tools

Example: Wrapping the Exec Tool
// module/tools/shell.go - Modified

import "github.com/276793422/NemesisBot/module/security"

type ExecTool struct {
    workingDir     string
    timeout        time.Duration
    denyPatterns   []*regexp.Regexp
    allowPatterns  []*regexp.Regexp
    securityMW     *security.SecurityMiddleware  // NEW
}

func NewExecToolWithSecurity(
    workingDir string,
    restrict bool,
    config *config.Config,
    securityMW *security.SecurityMiddleware,  // NEW
) *ExecTool {
    return &ExecTool{
        workingDir:     workingDir,
        timeout:        60 * time.Second,
        denyPatterns:   defaultDenyPatterns,
        allowPatterns:  nil,
        securityMW:     securityMW,  // NEW
    }
}

func (t *ExecTool) Execute(ctx context.Context, args map[string]interface{}) *ToolResult {
    command, _ := args["command"].(string)

    // NEW: Use security wrapper
    processWrapper := t.securityMW.Process()
    output, err := processWrapper.ExecuteCommand(command)
    if err != nil {
        return ErrorResult(err.Error())
    }

    return NewToolResult(output)
}
Example: Wrapping File Operations
// module/tools/filesystem.go - Modified

import "github.com/276793422/NemesisBot/module/security"

type WriteFileTool struct {
    workspace    string
    restrict     bool
    securityMW   *security.SecurityMiddleware  // NEW
}

func (t *WriteFileTool) Execute(ctx context.Context, args map[string]interface{}) *ToolResult {
    path, _ := args["path"].(string)
    content, _ := args["content"].(string)

    // NEW: Use security wrapper
    fileWrapper := t.securityMW.File()
    err := fileWrapper.WriteFile(path, []byte(content))
    if err != nil {
        return ErrorResult(err.Error())
    }

    return SilentResult(fmt.Sprintf("File written: %s", path))
}

Audit and Monitoring

Viewing Audit Logs
// Get all audit events
log := middleware.GetAuditLog(security.AuditFilter{})

// Filter by user
userLog := middleware.GetAuditLog(security.AuditFilter{
    User: "cli",
})

// Filter by operation type
fileOpsLog := middleware.GetAuditLog(security.AuditFilter{
    OperationType: security.OpFileWrite,
})

// Filter by decision
deniedLog := middleware.GetAuditLog(security.AuditFilter{
    Decision: "denied",
})

// Filter by time range
start := time.Now().Add(-24 * time.Hour)
recentLog := middleware.GetAuditLog(security.AuditFilter{
    StartTime: &start,
})

// Export to CSV
middleware.ExportAuditLog("/var/log/nemesisbot/audit.csv")
Monitoring Pending Approvals
// Get all pending approval requests
pending := middleware.GetSecuritySummary()["pending"].([]map[string]interface{})

for _, req := range pending {
    fmt.Printf("Request ID: %s\n", req["id"])
    fmt.Printf("  Type: %s\n", req["type"])
    fmt.Printf("  Target: %s\n", req["target"])
    fmt.Printf("  Danger: %s\n", req["danger"])

    // Approve or deny
    middleware.ApprovePendingRequest(req["id"].(string))
    // OR
    middleware.DenyPendingRequest(req["id"].(string), "Reason for denial")
}
Real-time Monitoring
// Start security monitoring in background
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go security.MonitorSecurityStatus(ctx, auditor, 5*time.Minute)

Decision Flow

┌─────────────────────────────────────────────────────────────┐
│  1. Operation Requested                                     │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Check Default Deny Patterns                             │
│     - Does target match dangerous pattern?                  │
│     - Block if yes                                          │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Check User Permissions                                  │
│     - Is operation type allowed?                            │
│     - Is target in whitelist/blacklist?                     │
│     - Is danger level within limit?                         │
│     - Does operation require approval?                      │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Evaluate Policies                                       │
│     - For each enabled policy                               │
│     - Check if rules match                                  │
│     - Apply matching rule action:                           │
│       • allow → Execute                                     │
│       • deny → Block                                        │
│       • ask → Block (temporarily mapped to deny)            │
│         ⚠️  See "Important Notes" section below              │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Decision                                                │
│     - ALLOW: Execute operation                              │
│     - DENY: Block with reason                               │
│     - ASK: Block with reason (currently, see notes)         │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Log to Audit Trail                                      │
└─────────────────────────────────────────────────────────────┘

⚠️ Important Notes

Current Status of "ask" Action

As of 2026-02-24, the ask action is mapped to deny for security reasons.

Action Current Behavior Future Behavior
allow ✅ Allows operation ✅ Allows operation
deny ❌ Blocks operation ❌ Blocks operation
ask Blocks operation (temporarily) 🔜 Will prompt for approval
Why This Mapping?

The approval workflow (prompting user interactively) is not yet implemented. To maintain security:

  • Rules with ask action block the operation (treated as deny)
  • This prevents operations from executing without proper approval
  • Once approval UI is implemented, ask will be restored to its intended behavior
Impact on Current Configuration

If your config.security.json contains rules with "action": "ask", they will currently deny the operation:

{
  "file_read": [
    {
      "pattern": "*.log",
      "action": "ask"  // Currently treated as "deny"
    }
  ]
}

Workaround: To allow these operations temporarily, change "action": "ask" to "action": "allow".

Future Implementation

When the approval workflow is completed:

  1. Interactive prompts will ask user for permission
  2. ask will be mapped back to require_approval
  3. Commands like nemesisbot security approve <id> will be functional
Code Reference

See module/security/auditor.go:normalizeDecision():

case "ask":
    // TEMPORARY: Map ask to denied until approval UI is implemented
    // This prevents operations that require approval from executing
    return "denied"

Security Best Practices

1. Principle of Least Privilege
// Different permission profiles for different contexts
permissions := map[string]*security.Permission{
    "cli":    security.CreateCLIPermission(),        // Full access
    "web":    security.CreateWebPermission(),        // Restricted
    "agent":  security.CreateAgentPermission("bot"), // Context-aware
    "cron":   createCronPermission(),                // Minimal
}
2. Workspace Isolation
// Always use workspace restrictions
middleware := security.NewSecurityMiddleware(
    auditor,
    userID,
    source,
    "/home/user/bot-workspace",  // Restrict to this directory
)
3. Require Approval for Critical Operations
criticalPolicy := &security.Policy{
    Name:    "critical_ops",
    Enabled: true,
    Rules: []security.PolicyRule{
        {
            MatchOpType: security.OpProcessExec,
            MinDanger:   security.DangerHigh,
            Action:      "require_approval",
            Reason:      "High-danger commands need approval",
        },
    },
}
4. Regular Audit Review
// Schedule regular audit log reviews
func scheduleAuditReview(auditor *security.Auditor) {
    ticker := time.NewTicker(24 * time.Hour)
    for range ticker.C {
        log := auditor.GetAuditLog(security.AuditFilter{
            StartTime: time.Now().Add(-24 * time.Hour),
        })

        // Review denied operations
        for _, event := range log {
            if event.Decision == "denied" {
                alertSecurityTeam(event)
            }
        }

        // Export logs
        auditor.ExportAuditLog(fmt.Sprintf(
            "/var/log/nemesisbot/audit-%s.csv",
            time.Now().Format("2006-01-02"),
        ))
    }
}
5. Enable All Logging
config := &security.AuditorConfig{
    Enabled:          true,
    LogAllOperations: true,  // Log everything
    LogDenialsOnly:   false,  // Not just denials
}

Migration Guide

Step 1: Initialize Security Auditor

In your main.go or initialization code:

import "github.com/276793422/NemesisBot/module/security"

func initSecurity(cfg *config.Config) *security.SecurityAuditor {
    config := &security.AuditorConfig{
        Enabled:               true,
        LogAllOperations:      true,
        ApprovalTimeout:       5 * time.Minute,
        AuditLogRetentionDays: 90,
    }

    auditor := security.NewSecurityAuditor(config)
    security.CreateDefaultPolicies(auditor)

    // Set up permissions
    auditor.SetPermission("cli", security.CreateCLIPermission())
    auditor.SetPermission("web", security.CreateWebPermission())

    return auditor
}
Step 2: Pass Security Middleware to Tools
// When creating tools
fileWrapper := security.NewSecureFileWrapper(
    auditor,
    userID,
    source,
    workspace,
)

// Modify tools to use wrapper
writeTool := &WriteFileTool{
    workspace:  workspace,
    restrict:   true,
    fileWrapper: fileWrapper,  // NEW
}
Step 3: Update Tool Execute Methods
// Before (old code)
func (t *WriteFileTool) Execute(ctx context.Context, args map[string]interface{}) *ToolResult {
    path, _ := args["path"].(string)
    content, _ := args["content"].(string)
    return os.WriteFile(path, []byte(content), 0644)
}

// After (with security)
func (t *WriteFileTool) Execute(ctx context.Context, args map[string]interface{}) *ToolResult {
    path, _ := args["path"].(string)
    content, _ := args["content"].(string)
    return t.fileWrapper.WriteFile(path, []byte(content))
}

Testing

Run the security tests:

cd /path/to/NemesisBot
go test ./module/security/... -v

Expected output:

=== RUN   TestSecurityAuditor_BasicOperation
--- PASS: TestSecurityAuditor_BasicOperation (0.00s)
=== RUN   TestSecurityAuditor_PolicyRules
--- PASS: TestSecurityAuditor_PolicyRules (0.00s)
...
PASS
ok      github.com/276793422/NemesisBot/module/security    0.123s

Troubleshooting

Issue: Operations are being blocked unexpectedly

Solution: Check the audit log to see why:

log := middleware.GetAuditLog(AuditFilter{Decision: "denied"})
for _, event := range log {
    fmt.Printf("Denied: %s - %s\n", event.Request.Target, event.Reason)
}
Issue: Want to temporarily disable security

Warning: Only do this in development!

auditor.Disable()
// ... perform operations ...
auditor.Enable()
Issue: Too many pending approvals

Solution: Adjust permissions to auto-allow more operations:

perm := security.CreateCLIPermission()
// Remove from require approval
delete(perm.RequireApproval, security.OpFileDelete)
auditor.SetPermission("cli", perm)

Advanced Features

Custom Danger Level Calculation
func customDangerLevel(op OperationType, target string) DangerLevel {
    baseLevel := GetDangerLevel(op)

    // Increase danger level for sensitive paths
    if strings.Contains(target, "/etc/") ||
       strings.Contains(target, "C:\\Windows") {
        if baseLevel < DangerHigh {
            return DangerHigh
        }
    }

    return baseLevel
}
Time-Based Policies
// Only allow dangerous operations during business hours
func businessHoursPolicy(req *OperationRequest) bool {
    hour := time.Now().Hour()
    isBusinessHours := hour >= 9 && hour < 17

    if req.DangerLevel >= DangerHigh && !isBusinessHours {
        return false
    }
    return true
}
Multi-User Approval
// Require multiple approvers for critical operations
criticalPolicy := &security.Policy{
    Name:    "multi_approver",
    Enabled: true,
    Rules: []security.PolicyRule{
        {
            MatchOpType: security.OpSystemShutdown,
            Action:      "require_approval",
            Reason:      "Requires 2 approvers",
        },
    },
}

// In your approval handler:
func approveWithMultiple(requestID string, approvers []string) error {
    approvals := 0
    for _, approver := range approvers {
        if err := auditor.ApproveRequest(requestID, approver); err == nil {
            approvals++
        }
    }

    if approvals < 2 {
        return fmt.Errorf("need at least 2 approvals, got %d", approvals)
    }
    return nil
}

File Structure

module/security/
├── auditor.go              # Main security auditor implementation
├── middleware.go           # Wrappers and middleware
├── auditor_test.go         # Test suite
├── policies.go             # Predefined policies (optional)
└── README.md              # This file

Performance Considerations

  • Synchronous Mode: Set SynchronousMode=false for non-blocking operation
  • Log Filtering: Use LogDenialsOnly=true in production to reduce log size
  • Audit Cleanup: Enable automatic cleanup with AuditLogRetentionDays
  • In-Memory Logging: Audit logs are kept in memory; export regularly

Security Recommendations

  1. Always enable security in production
  2. Use workspace restrictions
  3. Require approval for critical operations
  4. Review audit logs regularly
  5. Export audit logs for long-term storage
  6. Set up alerts for denied operations
  7. Use different permission profiles for different contexts
  8. Keep security framework updated

Documentation

Overview

NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors

Package security provides security plugin for NemesisBot

Index

Constants

This section is empty.

Variables

View Source
var DefaultDenyPatterns = map[OperationType][]string{
	OpProcessExec: {
		`\brm\s+-[rf]{1,2}\b`,
		`\bdel\s+/[fq]\b`,
		`\b(format|mkfs|diskpart)\b`,
		`\bdd\s+if=`,
		`\b(shutdown|reboot|poweroff)\b`,
		`\bsudo\b`,
		`\bchmod\s+[0-7]{3,4}\b`,
		`\bchown\b`,
		`\bpkill\b`,
		`\bkillall\b`,
		`\bkill\s+-[9]\b`,
		`\bcurl\b.*\|\s*(sh|bash)`,
		`\bwget\b.*\|\s*(sh|bash)`,
		`\beval\b`,
		`\bsource\s+.*\.sh\b`,
	},
	OpFileWrite: {
		`\.\.[/\\]`,
		`^/etc/`,
		`^/sys/`,
		`^/proc/`,
		`^/dev/`,
		`C:\\Windows\\System32`,
		`C:\\Windows\\System32\\drivers\\etc\\hosts`,
	},
	OpNetworkDownload: {
		`file://`,
		`ftp://`,
	},
}

DefaultDenyPatterns defines default dangerous patterns to block

Functions

func IsSafeCommand

func IsSafeCommand(command string) (bool, string)

IsSafeCommand checks if a command is safe to execute

func MatchCommandPattern

func MatchCommandPattern(pattern, command string) bool

MatchCommandPattern checks if a command matches a pattern Supports * wildcard for command arguments Examples:

"git *"         matches "git status", "git commit -m 'msg'"
"rm -rf *"      matches "rm -rf /tmp/test"
"*sudo*"        matches "sudo apt-get install", "sudo vim"

func MatchDomainPattern

func MatchDomainPattern(pattern, domain string) bool

MatchDomainPattern checks if a domain matches a pattern Examples:

"*.github.com"  matches "api.github.com", "raw.githubusercontent.com"
"*.openai.com"  matches "api.openai.com"
"github.com"    matches exactly "github.com"

func MatchPattern

func MatchPattern(pattern, target string) bool

MatchPattern checks if a target matches a pattern with wildcard support Supported wildcards:

  • - matches any sequence in a single directory level (e.g., *.key, D:/123/*.key) ** - matches any sequence across multiple directory levels (e.g., D:/123/**.key) No wildcard - exact match (e.g., /etc/passwd)

Special case: patterns without directory separator (e.g., *.key) match globally across all directories (e.g., *.key matches /home/user/test.key)

Examples:

*.key              matches all .key files in all directories (global pattern)
D:/123/*.key        matches .key files directly in D:/123/
D:/123/**.key       matches .key files in D:/123/ and all subdirectories
/etc/passwd        matches exactly /etc/passwd

func MonitorSecurityStatus

func MonitorSecurityStatus(ctx context.Context, auditor *SecurityAuditor, interval time.Duration)

MonitorSecurityStatus continuously monitors and logs security status

func ValidatePath

func ValidatePath(path, workspace string, operation OperationType) (string, error)

ValidatePath checks if a path is safe for the given operation

Types

type ApprovalRequiredError

type ApprovalRequiredError struct {
	RequestID string
	Reason    string
}

ApprovalRequiredError is returned when approval is required

func (*ApprovalRequiredError) Error

func (e *ApprovalRequiredError) Error() string

func (*ApprovalRequiredError) IsApprovalRequired

func (e *ApprovalRequiredError) IsApprovalRequired() bool

type AuditEvent

type AuditEvent struct {
	EventID    string           // Unique event ID
	Request    OperationRequest // Original request
	Decision   string           // "allowed", "denied", "approved", "pending"
	Reason     string           // Reason for decision
	Timestamp  time.Time        // When the decision was made
	Duration   time.Duration    // Time to process
	PolicyRule string           // Which policy rule matched
}

AuditEvent represents an audit log entry

type AuditFilter

type AuditFilter struct {
	OperationType OperationType
	User          string
	Source        string
	Decision      string
	StartTime     *time.Time
	EndTime       *time.Time
}

AuditFilter filters audit logs

func (*AuditFilter) IsEmpty

func (f *AuditFilter) IsEmpty() bool

func (*AuditFilter) Matches

func (f *AuditFilter) Matches(event AuditEvent) bool

type AuditorConfig

type AuditorConfig struct {
	Enabled               bool
	LogAllOperations      bool
	LogDenialsOnly        bool
	ApprovalTimeout       time.Duration
	MaxPendingRequests    int
	AuditLogRetentionDays int
	AuditLogPath          string
	AuditLogFileEnabled   bool
	AuditLogDir           string
	SynchronousMode       bool
	DefaultAction         string
}

AuditorConfig configures the security auditor

type BatchOperationRequest

type BatchOperationRequest struct {
	ID          string
	Operations  []*OperationRequest
	User        string
	Source      string
	Description string
}

BatchOperationRequest represents a batch of operations to be approved together

type DangerLevel

type DangerLevel int

DangerLevel represents the risk level of an operation

const (
	DangerLow      DangerLevel = iota // Safe operations with minimal risk
	DangerMedium                      // Operations that modify data/state
	DangerHigh                        // Operations that can cause significant damage
	DangerCritical                    // Operations that can compromise system security
)

func GetDangerLevel

func GetDangerLevel(opType OperationType) DangerLevel

GetDangerLevel returns the danger level for an operation type

func (DangerLevel) String

func (d DangerLevel) String() string

type OperationRequest

type OperationRequest struct {
	ID           string                 // Unique request ID
	Type         OperationType          // Type of operation
	DangerLevel  DangerLevel            // Risk level
	User         string                 // User/agent requesting the operation
	Source       string                 // Source (cli, web, telegram, etc.)
	Target       string                 // Target of operation (file path, command, URL, etc.)
	Context      map[string]interface{} // Additional context
	Timestamp    time.Time              // When the request was made
	Approver     string                 // Who approved (if applicable)
	ApprovedAt   time.Time              // When approved
	DeniedReason string                 // Reason for denial (if denied)
	AuditLog     string                 // Audit trail entry
}

OperationRequest represents a request for a dangerous operation

type OperationType

type OperationType string

OperationType represents the category of dangerous operation

const (
	// File operations
	OpFileRead   OperationType = "file_read"
	OpFileWrite  OperationType = "file_write"
	OpFileDelete OperationType = "file_delete"

	// Directory operations
	OpDirRead   OperationType = "dir_read"
	OpDirCreate OperationType = "dir_create"
	OpDirDelete OperationType = "dir_delete"

	// Process operations
	OpProcessExec    OperationType = "process_exec"
	OpProcessSpawn   OperationType = "process_spawn"
	OpProcessKill    OperationType = "process_kill"
	OpProcessSuspend OperationType = "process_suspend"

	// Network operations
	OpNetworkDownload OperationType = "network_download"
	OpNetworkUpload   OperationType = "network_upload"
	OpNetworkRequest  OperationType = "network_request"

	// Hardware operations
	OpHardwareI2C  OperationType = "hardware_i2c"
	OpHardwareSPI  OperationType = "hardware_spi"
	OpHardwareGPIO OperationType = "hardware_gpio"

	// System operations
	OpSystemShutdown OperationType = "system_shutdown"
	OpSystemReboot   OperationType = "system_reboot"
	OpSystemConfig   OperationType = "system_config"
	OpSystemService  OperationType = "system_service"
	OpSystemInstall  OperationType = "system_install"

	// Registry operations (Windows)
	OpRegistryRead   OperationType = "registry_read"
	OpRegistryWrite  OperationType = "registry_write"
	OpRegistryDelete OperationType = "registry_delete"
)

type Permission

type Permission struct {
	AllowedTypes    map[OperationType]bool
	AllowedTargets  []string               // Whitelist patterns (regexp)
	DeniedTargets   []string               // Blacklist patterns (regexp)
	RequireApproval map[OperationType]bool // Ops requiring explicit approval
	MaxDangerLevel  DangerLevel            // Maximum danger level allowed
}

Permission defines what operations are allowed

func CreateAgentPermission

func CreateAgentPermission(agentID string) *Permission

CreateAgentPermission creates permission for AI agents (context-aware)

func CreateCLIPermission

func CreateCLIPermission() *Permission

CreateCLIPermission creates permission for CLI user (less restrictive)

func CreateWebPermission

func CreateWebPermission() *Permission

CreateWebPermission creates permission for web users (more restrictive)

type Policy

type Policy struct {
	Name          string
	Description   string
	Enabled       bool
	Rules         []PolicyRule
	DefaultAction string // "allow", "deny", "require_approval"
	LogOnly       bool   // If true, log but don't block
	RequireMFA    bool   // Require multi-factor approval for critical ops
}

Policy defines security rules

type PolicyRule

type PolicyRule struct {
	Name        string
	MatchOpType OperationType
	MatchTarget string      // Regexp pattern for target
	MatchUser   string      // Regexp pattern for user
	MatchSource string      // Regexp pattern for source
	MinDanger   DangerLevel // Minimum danger level to match
	Action      string      // "allow", "deny", "require_approval"
	Reason      string      // Explanation for this rule
}

PolicyRule defines a single security rule

type SecureFileWrapper

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

SecureFileWrapper wraps file operations with security checks

func NewSecureFileWrapper

func NewSecureFileWrapper(auditor *SecurityAuditor, user, source, workspace string) *SecureFileWrapper

func (*SecureFileWrapper) AppendFile

func (w *SecureFileWrapper) AppendFile(path string, content []byte) error

AppendFile appends to a file with security check

func (*SecureFileWrapper) CreateDirectory

func (w *SecureFileWrapper) CreateDirectory(path string) error

CreateDirectory creates a directory with security check

func (*SecureFileWrapper) DeleteDirectory

func (w *SecureFileWrapper) DeleteDirectory(path string) error

DeleteDirectory deletes a directory with security check

func (*SecureFileWrapper) DeleteFile

func (w *SecureFileWrapper) DeleteFile(path string) error

DeleteFile deletes a file with security check

func (*SecureFileWrapper) EditFile

func (w *SecureFileWrapper) EditFile(path, oldText, newText string) error

EditFile edits a file with security check

func (*SecureFileWrapper) ReadDirectory

func (w *SecureFileWrapper) ReadDirectory(path string) ([]string, error)

ReadDirectory reads a directory with security check

func (*SecureFileWrapper) ReadFile

func (w *SecureFileWrapper) ReadFile(path string) ([]byte, error)

ReadFile reads a file with security check

func (*SecureFileWrapper) WriteFile

func (w *SecureFileWrapper) WriteFile(path string, content []byte) error

WriteFile writes a file with security check

type SecureHardwareWrapper

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

SecureHardwareWrapper wraps hardware operations with security checks

func NewSecureHardwareWrapper

func NewSecureHardwareWrapper(auditor *SecurityAuditor, user, source string) *SecureHardwareWrapper

func (*SecureHardwareWrapper) I2CWrite

func (w *SecureHardwareWrapper) I2CWrite(bus string, address int, data []byte) error

I2CWrite performs I2C write with security check

func (*SecureHardwareWrapper) SPIWrite

func (w *SecureHardwareWrapper) SPIWrite(device string, data []byte) error

SPIWrite performs SPI write with security check

type SecureNetworkWrapper

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

SecureNetworkWrapper wraps network operations with security checks

func NewSecureNetworkWrapper

func NewSecureNetworkWrapper(auditor *SecurityAuditor, user, source string) *SecureNetworkWrapper

func (*SecureNetworkWrapper) DownloadURL

func (w *SecureNetworkWrapper) DownloadURL(url string, savePath string) error

DownloadURL downloads a file from URL with security check

type SecureProcessWrapper

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

SecureProcessWrapper wraps process operations with security checks

func NewSecureProcessWrapper

func NewSecureProcessWrapper(auditor *SecurityAuditor, user, source, workingDir string) *SecureProcessWrapper

func (*SecureProcessWrapper) ExecuteCommand

func (w *SecureProcessWrapper) ExecuteCommand(command string) (string, error)

ExecuteCommand executes a command with security check

type SecurityAuditor

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

SecurityAuditor is the main security auditor

func GetGlobalAuditor

func GetGlobalAuditor() *SecurityAuditor

GetGlobalAuditor returns the global security auditor

func InitGlobalAuditor

func InitGlobalAuditor(config *AuditorConfig) *SecurityAuditor

InitGlobalAuditor initializes the global security auditor

func NewSecurityAuditor

func NewSecurityAuditor(auditorConfig *AuditorConfig) *SecurityAuditor

NewSecurityAuditor creates a new security auditor

func (*SecurityAuditor) ApproveRequest

func (sa *SecurityAuditor) ApproveRequest(requestID, approver string) error

ApproveRequest approves a pending operation request

func (*SecurityAuditor) CleanupOldAuditLogs

func (sa *SecurityAuditor) CleanupOldAuditLogs() error

CleanupOldAuditLogs is a no-op. Events are no longer stored in memory; all data is persisted to the audit log file. File-based retention can be handled externally by rotating the log file.

func (*SecurityAuditor) Close

func (sa *SecurityAuditor) Close() error

Close closes the audit log file

func (*SecurityAuditor) DenyRequest

func (sa *SecurityAuditor) DenyRequest(requestID, approver, reason string) error

DenyRequest denies a pending operation request

func (*SecurityAuditor) Disable

func (sa *SecurityAuditor) Disable()

Disable disables the security auditor (use with caution!)

func (*SecurityAuditor) Enable

func (sa *SecurityAuditor) Enable()

Enable enables the security auditor

func (*SecurityAuditor) ExportAuditLog

func (sa *SecurityAuditor) ExportAuditLog(filePath string) error

ExportAuditLog exports audit log to a file. Copies the persistent audit log file to the specified path. If no log file is available, creates an empty file with header.

func (*SecurityAuditor) GetApprovalManager

func (sa *SecurityAuditor) GetApprovalManager() approval.ApprovalManager

GetApprovalManager returns the current approval manager

func (*SecurityAuditor) GetAuditLog

func (sa *SecurityAuditor) GetAuditLog(filter AuditFilter) []AuditEvent

GetAuditLog returns the audit log. Events are persisted to the audit log file; this method returns an empty slice. Use ExportAuditLog to export data from the file.

func (*SecurityAuditor) GetPendingRequests

func (sa *SecurityAuditor) GetPendingRequests() []*OperationRequest

GetPendingRequests returns all pending approval requests

func (*SecurityAuditor) GetStatistics

func (sa *SecurityAuditor) GetStatistics() map[string]interface{}

GetStatistics returns security statistics

func (*SecurityAuditor) RequestPermission

func (sa *SecurityAuditor) RequestPermission(ctx context.Context, req *OperationRequest) (bool, error, string)

RequestPermission requests permission to perform a dangerous operation Returns: (allowed, error, requestID)

func (*SecurityAuditor) SetApprovalManager

func (sa *SecurityAuditor) SetApprovalManager(mgr approval.ApprovalManager)

SetApprovalManager sets the approval manager for interactive approval dialogs

func (*SecurityAuditor) SetDefaultAction

func (sa *SecurityAuditor) SetDefaultAction(action string)

SetDefaultAction sets the default action for unmatched requests

func (*SecurityAuditor) SetRules

func (sa *SecurityAuditor) SetRules(opType OperationType, rules []config.SecurityRule)

SetRules sets rules for a specific operation type

type SecurityMiddleware

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

SecurityMiddleware provides a unified security interface for tools

func NewSecurityMiddleware

func NewSecurityMiddleware(auditor *SecurityAuditor, user, source, workspace string) *SecurityMiddleware

func (*SecurityMiddleware) ApprovePendingRequest

func (sm *SecurityMiddleware) ApprovePendingRequest(requestID string) error

ApprovePendingRequest approves a pending request (for user interaction)

func (*SecurityMiddleware) DenyPendingRequest

func (sm *SecurityMiddleware) DenyPendingRequest(requestID, reason string) error

DenyPendingRequest denies a pending request (for user interaction)

func (*SecurityMiddleware) ExportAuditLog

func (sm *SecurityMiddleware) ExportAuditLog(filePath string) error

ExportAuditLog exports the audit log to a file

func (*SecurityMiddleware) File

File returns the file operations wrapper

func (*SecurityMiddleware) GetAuditLog

func (sm *SecurityMiddleware) GetAuditLog(filter AuditFilter) []AuditEvent

GetAuditLog returns the audit log with optional filtering

func (*SecurityMiddleware) GetSecuritySummary

func (sm *SecurityMiddleware) GetSecuritySummary() map[string]interface{}

GetSecuritySummary returns a summary of security status

func (*SecurityMiddleware) Hardware

func (sm *SecurityMiddleware) Hardware() *SecureHardwareWrapper

Hardware returns the hardware operations wrapper

func (*SecurityMiddleware) Network

Network returns the network operations wrapper

func (*SecurityMiddleware) Process

Process returns the process operations wrapper

func (*SecurityMiddleware) RequestBatchPermission

func (sm *SecurityMiddleware) RequestBatchPermission(ctx context.Context, batch *BatchOperationRequest) (bool, error, string)

RequestBatchPermission requests permission for multiple operations at once

type SecurityPlugin

type SecurityPlugin struct {
	*plugin.BasePlugin
	// contains filtered or unexported fields
}

SecurityPlugin implements the plugin interface for security checks

func NewSecurityPlugin

func NewSecurityPlugin() *SecurityPlugin

NewSecurityPlugin creates a new security plugin

func (*SecurityPlugin) Cleanup

func (p *SecurityPlugin) Cleanup() error

Cleanup cleans up the security plugin

func (*SecurityPlugin) Execute

func (p *SecurityPlugin) Execute(ctx context.Context, invocation *plugin.ToolInvocation) (bool, error, bool)

Execute implements the plugin interface for security checks Security layers are applied in order: 1. InjectionDetector - intercept malicious input 2. CommandGuard - check dangerous commands 3. Auditor (ABAC) - attribute-based access control 4. CredentialScanner - detect leaked credentials 5. DLP - scan sensitive data 6. SSRFGuard - validate URLs for network operations 7. ScanChain - virus scanning 8. AuditChain - Merkle integrity audit log

func (*SecurityPlugin) GetAuditChain

func (p *SecurityPlugin) GetAuditChain() *integrity.AuditChain

GetAuditChain returns the audit chain (for testing)

func (*SecurityPlugin) GetAuditor

func (p *SecurityPlugin) GetAuditor() *SecurityAuditor

GetAuditor returns the security auditor (for backward compatibility)

func (*SecurityPlugin) GetCommandGuard

func (p *SecurityPlugin) GetCommandGuard() *command.Guard

GetCommandGuard returns the command guard (for testing)

func (*SecurityPlugin) GetCredentialScanner

func (p *SecurityPlugin) GetCredentialScanner() *credential.Scanner

GetCredentialScanner returns the credential scanner (for testing)

func (*SecurityPlugin) GetDLPEngine

func (p *SecurityPlugin) GetDLPEngine() *dlp.DLPEngine

GetDLPEngine returns the DLP engine (for testing)

func (*SecurityPlugin) GetInjectionDetector

func (p *SecurityPlugin) GetInjectionDetector() *injection.Detector

GetInjectionDetector returns the injection detector (for testing)

func (*SecurityPlugin) GetSSRFGuard

func (p *SecurityPlugin) GetSSRFGuard() *ssrf.Guard

GetSSRFGuard returns the SSRF guard (for testing)

func (*SecurityPlugin) Init

func (p *SecurityPlugin) Init(pluginConfig map[string]interface{}) error

Init initializes the security plugin with configuration

func (*SecurityPlugin) IsEnabled

func (p *SecurityPlugin) IsEnabled() bool

IsEnabled returns whether the plugin is enabled

func (*SecurityPlugin) ReloadConfig

func (p *SecurityPlugin) ReloadConfig() error

ReloadConfig reloads the security configuration

func (*SecurityPlugin) SetEnabled

func (p *SecurityPlugin) SetEnabled(enabled bool)

SetEnabled sets the enabled state

Directories

Path Synopsis
NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors Package command provides dangerous command detection and blocking
NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors Package command provides dangerous command detection and blocking
NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors Package credential provides credential detection patterns for common secret types
NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors Package credential provides credential detection patterns for common secret types
Package dlp provides Data Loss Prevention scanning for NemesisBot.
Package dlp provides Data Loss Prevention scanning for NemesisBot.
NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors
NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors
NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors Package integrity provides a tamper-evident persistent audit chain
NemesisBot - AI agent License: MIT Copyright (c) 2026 NemesisBot contributors Package integrity provides a tamper-evident persistent audit chain
clamav
Package clamav provides a Go client for the ClamAV clamd daemon
Package clamav provides a Go client for the ClamAV clamd daemon
Package signature provides Ed25519-based skill signature verification for NemesisBot.
Package signature provides Ed25519-based skill signature verification for NemesisBot.

Jump to

Keyboard shortcuts

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