security

package
v1.13.2 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package security – audit.go implements security auditing for DevClaw configuration. Checks for common misconfigurations, exposed secrets, and security gaps.

Package security implementa os guardrails de segurança do DevClaw. Inclui validação de input (injection, rate limit, PII), validação de output (URLs, fatos, PII) e políticas de segurança para execução de tools.

Package security – safe_merge.go provides protection against prototype pollution when merging maps. This is a security hardening measure inspired by openclaw.

Package security – ssrf.go implements SSRF (Server-Side Request Forgery) protection for web_fetch and similar tools. Resolves hostnames first to defend against DNS rebinding, then validates resolved IPs against private ranges, metadata endpoints, and blocked hosts.

Index

Constants

View Source
const (
	SeverityCritical = "critical"
	SeverityWarning  = "warning"
	SeverityInfo     = "info"
)

Severity levels for audit findings.

Variables

View Source
var (
	ErrInputTooLong         = fmt.Errorf("mensagem excede o tamanho máximo permitido")
	ErrRateLimited          = fmt.Errorf("limite de mensagens por minuto excedido, aguarde um momento")
	ErrPromptInjection      = fmt.Errorf("conteúdo potencialmente malicioso detectado")
	ErrEmptyOutput          = fmt.Errorf("resposta vazia gerada pelo modelo")
	ErrSystemPromptLeak     = fmt.Errorf("possível vazamento de instruções internas")
	ErrHallucinatedURL      = fmt.Errorf("URL na resposta não corresponde aos resultados")
	ErrConfirmationRequired = fmt.Errorf("esta ação requer confirmação do usuário")
	ErrToolNotAllowed       = fmt.Errorf("tool não permitida pela política de segurança")
)
View Source
var BlockedMergeKeys = map[string]bool{
	"__proto__":   true,
	"prototype":   true,
	"constructor": true,
}

BlockedMergeKeys are keys that should never be used in map operations as they can lead to prototype pollution attacks.

View Source
var SecurityChecks = []func(AuditOptions) *AuditFinding{
	checkVaultNotConfigured,
	checkRawAPIKeys,
	checkConfigPermissions,
	checkSessionsPermissions,
	checkGatewayBindNoAuth,
	checkCORSOpen,
	checkSudoAllowed,
	checkSSRFDisabled,
	checkEmbeddingNoKey,
	checkVaultFilePermissions,
}

SecurityChecks is the list of all security check functions run during an audit.

Functions

func IsBlockedKey added in v1.8.0

func IsBlockedKey(key string) bool

IsBlockedKey checks if a single key is in the blocked list.

func SafeMerge added in v1.8.0

func SafeMerge(dst, src map[string]any) error

SafeMerge performs a shallow merge of src into dst, but blocks any keys that could cause prototype pollution. Returns an error if blocked keys are detected in src.

func SafeMergeDeep added in v1.8.0

func SafeMergeDeep(dst, src map[string]any) error

SafeMergeDeep performs a deep merge of src into dst, but blocks any keys that could cause prototype pollution at any level. Returns an error if blocked keys are detected.

func ValidateMapKeys added in v1.8.0

func ValidateMapKeys(m map[string]any) error

ValidateMapKeys checks if a map contains any blocked keys that could cause prototype pollution. Returns an error if blocked keys are found.

Types

type AuditFinding added in v1.13.0

type AuditFinding struct {
	CheckID     string `json:"check_id"`
	Severity    string `json:"severity"`
	Title       string `json:"title"`
	Detail      string `json:"detail"`
	Remediation string `json:"remediation"`
}

AuditFinding represents a single security finding.

type AuditOptions added in v1.13.0

type AuditOptions struct {
	ConfigPath        string            // Path to config.yaml
	SessionsDir       string            // Path to sessions directory
	VaultPath         string            // Path to .devclaw.vault
	VaultConfigured   bool              // Whether vault is initialized
	APIKey            string            // Current API key value (for plaintext check)
	Provider          string            // Current LLM provider
	GatewayEnabled    bool              // Whether HTTP gateway is enabled
	GatewayBind       string            // Gateway bind address
	GatewayAuth       bool              // Whether gateway auth is configured
	CORSOrigins       []string          // CORS allowed origins
	SSRFEnabled       bool              // Whether SSRF guard is enabled
	SudoAllowed       bool              // Whether sudo is allowed in exec tools
	EmbeddingProvider string            // Embedding provider name
	EmbeddingAPIKey   string            // Embedding API key
	ExtraChecks       map[string]string // Additional key-value pairs for custom checks
}

AuditOptions configures which checks to run.

type AuditReport added in v1.13.0

type AuditReport struct {
	Timestamp     time.Time      `json:"timestamp"`
	TotalChecks   int            `json:"total_checks"`
	CriticalCount int            `json:"critical_count"`
	WarningCount  int            `json:"warning_count"`
	InfoCount     int            `json:"info_count"`
	Findings      []AuditFinding `json:"findings"`
}

AuditReport is the result of a security audit.

func RunSecurityAudit added in v1.13.0

func RunSecurityAudit(opts AuditOptions) *AuditReport

RunSecurityAudit executes all security checks and returns a report.

func (*AuditReport) Summary added in v1.13.0

func (r *AuditReport) Summary() string

Summary returns a human-readable summary line.

type InputGuardrail

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

InputGuardrail valida mensagens de entrada antes do processamento pelo LLM.

func NewInputGuardrail

func NewInputGuardrail(maxLength, rateLimit int) *InputGuardrail

NewInputGuardrail cria um novo guardrail de input.

func (*InputGuardrail) Validate

func (g *InputGuardrail) Validate(userID, input string) error

Validate executa todas as validações no input.

type OutputGuardrail

type OutputGuardrail struct{}

OutputGuardrail valida respostas geradas pelo LLM antes do envio.

func NewOutputGuardrail

func NewOutputGuardrail() *OutputGuardrail

NewOutputGuardrail cria um novo guardrail de output.

func (*OutputGuardrail) Validate

func (g *OutputGuardrail) Validate(output string) error

Validate executa todas as validações no output do LLM.

func (*OutputGuardrail) ValidateWithContext added in v1.13.0

func (g *OutputGuardrail) ValidateWithContext(output string, toolResults []ToolResultContext) error

ValidateWithContext validates output against an optional set of tool results from the current turn. Used to cross-check claimed URLs and facts.

type RateLimiter

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

RateLimiter implementa rate limiting por usuário usando sliding window.

func NewRateLimiter

func NewRateLimiter(maxRequests int, window time.Duration) *RateLimiter

NewRateLimiter cria um novo rate limiter.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(userID string) bool

Allow verifica se o usuário pode fazer uma nova requisição. Retorna true se permitido, false se excedeu o limite.

type SSRFConfig

type SSRFConfig struct {
	// AllowPrivate allows requests to private IPs (default: false).
	AllowPrivate bool `yaml:"allow_private"`

	// AllowedHosts is a whitelist. If set, only these hosts are allowed.
	AllowedHosts []string `yaml:"allowed_hosts"`

	// BlockedHosts is a blacklist (checked even if AllowPrivate is true).
	BlockedHosts []string `yaml:"blocked_hosts"`
}

SSRFConfig configures SSRF protection behavior.

type SSRFGuard

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

SSRFGuard validates URLs before outgoing HTTP requests to prevent SSRF.

func NewSSRFGuard

func NewSSRFGuard(cfg SSRFConfig, logger *slog.Logger) *SSRFGuard

NewSSRFGuard creates a new SSRF guard from config.

func (*SSRFGuard) IsAllowed

func (g *SSRFGuard) IsAllowed(rawURL string) error

IsAllowed checks if a URL is safe to fetch (not internal/private). Resolves the hostname first to defend against DNS rebinding.

type SafeMergeError added in v1.8.0

type SafeMergeError struct {
	Key string
}

SafeMergeError is returned when a blocked key is detected.

func (*SafeMergeError) Error added in v1.8.0

func (e *SafeMergeError) Error() string

type ToolResultContext added in v1.13.0

type ToolResultContext struct {
	ToolName string
	Output   string
}

ToolResultContext holds a single tool result for output validation.

type ToolSecurityPolicy

type ToolSecurityPolicy struct {
	// AllowedTools lista as tools permitidas por skill (chave = skill name, valor = tool names).
	AllowedTools map[string][]string

	// RequiresConfirmation lista tools que precisam de confirmação do usuário.
	RequiresConfirmation []string

	// ToolRateLimits define rate limits específicos por tool.
	ToolRateLimits map[string]int
}

ToolSecurityPolicy define políticas de segurança para execução de tools.

func (*ToolSecurityPolicy) BeforeToolCall

func (p *ToolSecurityPolicy) BeforeToolCall(skillName, tool string) error

BeforeToolCall valida se uma tool pode ser executada para uma skill específica.

Jump to

Keyboard shortcuts

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