coraza

package
v0.6.3 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 25 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package coraza implements rules.Evaluator with OWASP Coraza and the OWASP Core Rule Set (CRS), which is embedded in the binary.

Index

Constants

View Source
const (
	DefaultParanoiaLevel           = 1
	DefaultInboundAnomalyThreshold = 5
	// DefaultMaxArgs matches Coraza's own default argument limit.
	DefaultMaxArgs = 1000
)

Defaults follow CRS recommendations for a first deployment.

View Source
const MaxCRSListItems = 64

MaxCRSListItems bounds AllowedMethods and AllowedRequestContentTypes.

Variables

View Source
var CRSRuleIDs = sync.OnceValues(func() ([]int, error) {
	var ids []int
	_, err := compile(Config{}, func(r types.RuleMetadata) {
		if inRange(r.ID(), crsIDMin, crsIDMax) {
			ids = append(ids, r.ID())
		}
	})
	if err != nil {
		return nil, err
	}
	if len(ids) == 0 {
		return nil, errors.New("this Coraza version doesn't list the rules it compiles")
	}
	slices.Sort(ids)
	return slices.Compact(ids), nil
})

CRSRuleIDs returns the IDs of the embedded CRS's rules, sorted. Tools use it to expand ID ranges into exclusions.

View Source
var RuleGroups = map[string]int{
	"scanner":          913,
	"lfi":              930,
	"rfi":              931,
	"rce":              932,
	"php":              933,
	"generic":          934,
	"xss":              941,
	"sqli":             942,
	"session-fixation": 943,
	"java":             944,
}

RuleGroups maps the CRS attack families that can be disabled to their rule ID prefix. Disabling a family the application cannot be vulnerable to (for example "php" for a Go service) removes its rules from every request.

Functions

func CheckRulesBeforeCRS added in v0.6.0

func CheckRulesBeforeCRS(rules string) error

CheckRulesBeforeCRS checks that rules CheckUserRules accepted can also load before the Core Rule Set (Config.DirectivesBeforeCRS): they must not change loaded rules, which there would be none of the CRS's. The error is a *RuleError naming the line of the first such directive.

func CheckSettings added in v0.5.6

func CheckSettings(s CRSSettings, list []Exclusion) error

CheckSettings checks a policy's CRS settings and exclusions as WithCRS and WithExclusions do, without compiling rules: what they refuse whatever the rules are.

func CheckUserRules

func CheckUserRules(rules string) error

CheckUserRules checks SecLang written by policy authors, as the engine loads it: after the Core Rule Set (Config.Directives), so it may refer to CRS rules. Only the directives of UserDirectiveNames are allowed, and the last SecRule can't open a chain. The error is a *RuleError naming the line of the first problem.

func ExclusionsCompiledIn added in v0.4.5

func ExclusionsCompiledIn(cfg Config, list []Exclusion) (bool, error)

ExclusionsCompiledIn reports whether exclusions list, with the rules cfg describes, are compiled into rules of their own (WithExclusions: target exclusions on rules that negate their collection). Only those can fail to compile with the rules (one on a rule the rules remove) once CheckSettings accepts the list; checking the others needs no compiling.

func RuleGroupNames

func RuleGroupNames() []string

RuleGroupNames returns the names in RuleGroups, sorted.

func UserDirectiveNames

func UserDirectiveNames() []string

UserDirectiveNames returns the directives CheckUserRules allows, sorted.

func UserOperatorNames added in v0.2.3

func UserOperatorNames() []string

UserOperatorNames returns the operators CheckUserRules allows, sorted.

Types

type CRSSettings added in v0.5.0

type CRSSettings struct {
	// ParanoiaLevel is tx.blocking_paranoia_level, 1 (default) to 4.
	ParanoiaLevel int
	// InboundAnomalyThreshold is tx.inbound_anomaly_score_threshold,
	// DefaultInboundAnomalyThreshold by default.
	InboundAnomalyThreshold int
	// AllowedMethods is tx.allowed_methods: the request methods rule 911100
	// allows, instead of the CRS's GET, HEAD, POST and OPTIONS. Empty: the
	// CRS's.
	AllowedMethods []string
	// AllowedRequestContentTypes is tx.allowed_request_content_type: the
	// media types (without parameters) rule 920420 allows, instead of the
	// CRS's. Empty: the CRS's. Compared case-insensitively.
	AllowedRequestContentTypes []string
	// DetectionParanoiaLevel is tx.detection_paranoia_level: the rules above
	// ParanoiaLevel and up to it run and score, but never block; a request
	// they would have blocked is Result.Detected. 0: ParanoiaLevel.
	DetectionParanoiaLevel int
	// OutboundAnomalyThreshold is tx.outbound_anomaly_score_threshold, the
	// response anomaly score at which a response is blocked. 0: the CRS's
	// (4).
	OutboundAnomalyThreshold int
}

CRSSettings are the CRS's own settings, as TX variables. They are set on each transaction before phase 1, not compiled into the rules: the CRS's initialization (REQUEST-901) only sets the variables still unset, so one compiled rule set serves every value, and SecLang that sets them (before or after the CRS, globally or per path) still wins, as it runs later. Zero values are the defaults.

func (CRSSettings) Validate added in v0.5.0

func (s CRSSettings) Validate() error

Validate checks s as the engine does: the webhook refuses what an engine would.

type Config

type Config struct {
	// ParanoiaLevel is the CRS blocking paranoia level, 1 (default) to 4.
	// Higher levels detect more and produce more false positives. It is set
	// on each transaction (CRSSettings), so it is not part of Key.
	ParanoiaLevel int
	// InboundAnomalyThreshold is the CRS inbound anomaly score at which a
	// request is blocked. Defaults to 5 (one critical match). Set on each
	// transaction, as ParanoiaLevel.
	InboundAnomalyThreshold int
	// MaxArgs is the maximum number of arguments per source (query, body,
	// path). Requests with more are rejected with 400 by rules 200004
	// (phase 1) and 200005 (phase 2) before any CRS argument rule runs, so
	// padding a request with arguments is cheap to reject and cannot hide a
	// payload past the limit. Zero means DefaultMaxArgs.
	MaxArgs int
	// DirectivesBeforeCRS are SecLang directives loaded before CRS. CRS
	// runtime rule exclusions (rules using ctl:ruleRemoveById and similar)
	// must be placed here.
	DirectivesBeforeCRS string
	// Directives are SecLang directives loaded after CRS, for custom rules
	// and configure-time exclusions (SecRuleRemoveById, SecRuleUpdateTargetById).
	Directives string
	// BodyLimit, if positive, sets Coraza's request body limits
	// (SecRequestBodyLimit and SecRequestBodyInMemoryLimit) above the
	// largest body the caller will pass, so bodies within the caller's limit
	// are neither rejected by Coraza nor buffered to temporary files. It is
	// compiled in, so callers that enforce their own limits (as policies do)
	// should pass the largest of them all, for one rule set.
	BodyLimit int
	// ResponseBodyLimit, if positive, sets Coraza's response body limit
	// (SecResponseBodyLimit) above the largest response body the caller
	// will pass, so the whole of it is inspected. Compiled in, as BodyLimit.
	ResponseBodyLimit int
	// DisabledRuleGroups lists CRS attack families (keys of RuleGroups) to
	// remove. Only disable families the protected application cannot be
	// vulnerable to.
	DisabledRuleGroups []string
	// DisableCRS loads only the directives, without the Core Rule Set.
	DisableCRS bool
	// Exclusions turn rules off, everywhere or for a path or an argument.
	// They are applied to each transaction, not compiled into the rules, so
	// they are not part of Key: Evaluator.WithExclusions gives configs that
	// differ only in exclusions one compiled rule set.
	Exclusions []Exclusion
	// OnMatch, if set, is called for every rule that matches and logs. It
	// runs on the request path and must be fast and safe for concurrent use.
	OnMatch func(types.MatchedRule)
}

Config configures the evaluator.

func (Config) CRS added in v0.5.0

func (cfg Config) CRS() CRSSettings

CRS returns cfg's CRS settings, with the CRS's defaults for those Config doesn't have (Evaluator.WithCRS sets them).

func (Config) Key

func (cfg Config) Key() [sha256.Size]byte

Key identifies the rules cfg compiles to: equal keys, equal rule sets. OnMatch, Exclusions and the CRS settings (CRS) are not part of it: they are applied to each transaction.

type Directive

type Directive struct {
	// Line is the 1-based line the directive starts on.
	Line int
	// Name is the directive name in lower case, such as "secrule".
	Name string
	// Text is the directive with its continuation lines joined, as Coraza
	// evaluates it.
	Text string
}

Directive is one SecLang directive, possibly spanning several lines.

func SplitDirectives

func SplitDirectives(s string) ([]Directive, error)

SplitDirectives splits SecLang into directives the way Coraza's parser reads them: lines are trimmed, blank lines and comments skipped, a line ending in a backslash continues on the next, and a backtick at the end of a line opens a block that a line starting with a backtick closes.

type Evaluator

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

Evaluator evaluates requests with a compiled Coraza WAF and its exclusions. It is safe for concurrent use.

func New

func New(cfg Config) (*Evaluator, error)

New compiles the rule set described by cfg.

func (*Evaluator) Evaluate

func (e *Evaluator) Evaluate(_ context.Context, r *request.Request) (rules.Result, error)

Evaluate runs the request through phases 1 and 2 (headers and body).

func (*Evaluator) EvaluateExchange added in v0.4.0

func (e *Evaluator) EvaluateExchange(_ context.Context, r *request.Request) (rules.Result, rules.Exchange, error)

EvaluateExchange implements rules.ExchangeEvaluator: the transaction stays open for the response, unless the request was interrupted.

func (*Evaluator) EvaluateExchangeDetecting added in v0.5.0

func (e *Evaluator) EvaluateExchangeDetecting(_ context.Context, r *request.Request) (rules.Result, rules.Exchange, error)

EvaluateExchangeDetecting implements rules.DetectingEvaluator (#360): the transaction runs DetectionOnly, so the rules never interrupt it; the result reports the interruption they would have made (Coraza's first), and the exchange is kept for the response whatever the request scored. Rules keep running after that point, so a would-be interrupted request may list more matches than in block mode.

func (*Evaluator) WithCRS added in v0.5.0

func (e *Evaluator) WithCRS(s CRSSettings) (*Evaluator, error)

WithCRS returns an evaluator with e's rules and exclusions and the CRS settings s instead of e's. It compiles nothing: policies that differ only in their CRS settings share one rule set. Without the CRS, s is checked and has no effect.

func (*Evaluator) WithExclusions added in v0.1.1

func (e *Evaluator) WithExclusions(list []Exclusion) (*Evaluator, error)

WithExclusions returns an evaluator with e's compiled rules and the exclusions list instead of e's. It compiles no rules, so policies that differ only in exclusions share one rule set; except for target exclusions on rules that negate their collection themselves (see negationPatterns).

type Exclusion

type Exclusion struct {
	// RuleIDs are the rules to turn off.
	RuleIDs []int
	// Path limits the exclusion to an exact path ("/search") or a prefix
	// ("/api/*"), in the router's syntax. Empty: every path.
	Path string
	// Argument limits it to one query or body argument (ARGS:<argument>),
	// in the rule and the rules chained to it. Empty: the whole rule.
	// At most one of Argument, ArgumentName, Cookie and Header is set.
	Argument string
	// ArgumentName limits it to one argument's name (ARGS_NAMES:<name>).
	ArgumentName string
	// Cookie limits it to one request cookie (REQUEST_COOKIES:<name>).
	Cookie string
	// Header limits it to one request header (REQUEST_HEADERS:<name>).
	Header string
}

Exclusion turns rules off where they cause false positives.

type RuleError

type RuleError struct {
	// Line is the 1-based line of the directive, or 0 when unknown.
	Line int
	Err  error
}

RuleError is a problem in user rules, at a line.

func (*RuleError) Error

func (e *RuleError) Error() string

func (*RuleError) Unwrap

func (e *RuleError) Unwrap() error

type RuleInfo added in v0.6.0

type RuleInfo struct {
	ID int
	// Message is the rule's msg action: what it detects. Rules that only
	// set things up have none.
	Message string
	// Severity is the rule's, lower case ("critical"); "" when it has
	// none.
	Severity string
	// ParanoiaLevel is the CRS paranoia level the rule belongs to
	// (its paranoia-level/N tag); 0 when it has none.
	ParanoiaLevel int
	// File is the CRS rules file (REQUEST-942-...conf); "" for Coraza's.
	File string
}

RuleInfo describes one rule of the embedded rules (the OWASP CRS and Coraza's recommended rules), from the rule itself: tools show it next to a rule ID (inkwallctl explain).

func EmbeddedRule added in v0.6.0

func EmbeddedRule(id int) (RuleInfo, bool, error)

EmbeddedRule describes the embedded rule with this ID: CRS's (900000 to 999999) or Coraza's recommended (200000 to 200099). ok is false for any other ID, a rule of the user's own.

Jump to

Keyboard shortcuts

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