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
- Variables
- func CheckSettings(s CRSSettings, list []Exclusion) error
- func CheckUserRules(rules string) error
- func ExclusionsCompiledIn(cfg Config, list []Exclusion) (bool, error)
- func RuleGroupNames() []string
- func UserDirectiveNames() []string
- func UserOperatorNames() []string
- type CRSSettings
- type Config
- type Directive
- type Evaluator
- func (e *Evaluator) Evaluate(_ context.Context, r *request.Request) (rules.Result, error)
- func (e *Evaluator) EvaluateExchange(_ context.Context, r *request.Request) (rules.Result, rules.Exchange, error)
- func (e *Evaluator) EvaluateExchangeDetecting(_ context.Context, r *request.Request) (rules.Result, rules.Exchange, error)
- func (e *Evaluator) WithCRS(s CRSSettings) (*Evaluator, error)
- func (e *Evaluator) WithExclusions(list []Exclusion) (*Evaluator, error)
- type Exclusion
- type RuleError
Constants ¶
const ( DefaultParanoiaLevel = 1 DefaultInboundAnomalyThreshold = 5 // DefaultMaxArgs matches Coraza's own default argument limit. DefaultMaxArgs = 1000 )
Defaults follow CRS recommendations for a first deployment.
const MaxCRSListItems = 64
MaxCRSListItems bounds AllowedMethods and AllowedRequestContentTypes.
Variables ¶
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.
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 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 ¶
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. The error is a *RuleError naming the line of the first problem.
func ExclusionsCompiledIn ¶ added in v0.4.5
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).
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 ¶
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 (*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
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.