coraza

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2022 License: Apache-2.0 Imports: 23 Imported by: 7

README

  Coraza - Web Application Firewall

Regression Tests Coreruleset Compatibility CodeQL Coverage OWASP Lab Project GoDoc

Coraza is an open source, enterprise-grade, high performance Web Application Firewall (WAF) ready to protect your beloved applications. It written in Go, supports ModSecurity SecLang rulesets and is 100% compatible with the OWASP Core Rule Set.


Key Features:

  • Drop-in - Coraza is a drop-in alternative to replace the soon to be abandoned Trustwave ModSecurity Engine and supports industry standard SecLang rule sets.

  • 🔥 Security - Coraza runs the OWASP Core Rule Set (CRS) to protect your web applications from a wide range of attacks, including the OWASP Top Ten, with a minimum of false alerts. CRS protects from many common attack categories including: SQL Injection (SQLi), Cross Site Scripting (XSS), PHP & Java Code Injection, HTTPoxy, Shellshock, Scripting/Scanner/Bot Detection & Metadata & Error Leakages.

  • 🔌 Extensible - Coraza is a library at its core, with many integrations to deploy on-premise Web Application Firewall instances. Audit Loggers, persistence engines, operators, actions, create your own functionalities to extend Coraza as much as you want.

  • 🚀 Performance - From huge websites to small blogs, Coraza can handle the load with minimal performance impact. Check our Benchmarks

  • Simplicity - Anyone is able to understand and modify the Coraza source code. It is easy to extend Coraza with new functionality.

  • 💬 Community - Coraza is a community project, contributions are accepted and all ideas will be considered. Find contributor guidance in the CONTRIBUTION document.


Integrations

The Coraza Project maintains implementations and plugins for the following servers:

Plugins

Roadmap

  • WASM scripts support
  • New rule language
  • GraphQL body processor
  • TinyGo support
  • libcoraza C exports

Prerequisites

  • Golang compiler v1.16+
  • Linux distribution (Debian or Centos recommended, Windows not supported yet)

Coraza Core Usage

Coraza can be used as a library for your Go program to implement a security middleware or integrate it with existing application & webservers.

package main

import(
	"fmt"
	"github.com/corazawaf/coraza/v2"
	"github.com/corazawaf/coraza/v2/seclang"
)

func main() {
	// First we initialize our waf and our seclang parser
	waf := coraza.NewWaf()
	parser, _ := seclang.NewParser(waf)

	// Now we parse our rules
	if err := parser.FromString(`SecRule REMOTE_ADDR "@rx .*" "id:1,phase:1,deny,status:403"`); err != nil {
		fmt.Println(err)
	}

	// Then we create a transaction and assign some variables
	tx := waf.NewTransaction()
	defer func(){
		tx.ProcessLogging()
		tx.Clean()
	}()
	tx.ProcessConnection("127.0.0.1", 8080, "127.0.0.1", 12345)

	// Finally we process the request headers phase, which may return an interruption
	if it := tx.ProcessRequestHeaders(); it != nil {
		fmt.Printf("Transaction was interrupted with status %d\n", it.Status)
	}
}

Tools

Troubleshooting

Dependency issues:

go get: github.com/jptosso/coraza-waf/v2@v2.0.0-rc.3: parsing go.mod:
	module declares its path as: github.com/corazawaf/coraza/v2
	        but was required as: github.com/jptosso/coraza-waf/v2

Coraza was migrated from github.com/jptosso/coraza-waf to github.com/corazawaf/coraza. Most dependencies has already been updated to use the new repo, but you must make sure they all use v2.0.0-rc.3+. You may use the following command to fix the error:

go get -u github.com/corazawaf/coraza/v2@v2.0.0-rc.3

Contribute

Contributions are welcome! Please refer to CONTRIBUTING.md for guidance.

Thanks

  • Modsecurity team for creating ModSecurity
  • OWASP Coreruleset team for the CRS and their help

Companies using Coraza

Author on Twitter

Donations

For donations, see Donations site

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BodyBuffer

type BodyBuffer struct {
	io.Writer
	// contains filtered or unexported fields
}

BodyBuffer is used to read RequestBody and ResponseBody objects It will handle memory usage for buffering and processing It implements io.Copy(bodyBuffer, someReader) by inherit io.Writer

func NewBodyBuffer

func NewBodyBuffer(options types.BodyBufferOptions) *BodyBuffer

NewBodyBuffer Initializes a body reader After writing memLimit bytes to the memory buffer, data will be written to a temporary file Temporary files will be written to tmpDir

func (*BodyBuffer) Close

func (br *BodyBuffer) Close() error

Close will close all readers and delete temporary files

func (*BodyBuffer) Reader

func (br *BodyBuffer) Reader() (io.Reader, error)

Reader Returns a working reader for the body buffer in memory or file

func (*BodyBuffer) Size

func (br *BodyBuffer) Size() int64

Size returns the current size of the body buffer

func (*BodyBuffer) Write

func (br *BodyBuffer) Write(data []byte) (n int, err error)

Write appends data to the body buffer by chunks You may dump io.Readers using io.Copy(br, reader)

type Collection

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

Collection are used to store VARIABLE data for transactions, this data structured is designed to store slices of data for keys Important: Collections ARE NOT concurrent safe

func NewCollection

func NewCollection(variable variables.RuleVariable) *Collection

NewCollection Creates a new collection

func (*Collection) Add

func (c *Collection) Add(key string, value string)

Add a value to some key

func (*Collection) AddCS added in v2.0.1

func (c *Collection) AddCS(key string, vKey string, vVal string)

AddCS a value to some key with case sensitive vKey

func (*Collection) AddUnique

func (c *Collection) AddUnique(key string, value string)

AddUnique will add a value to a key if it is not already there

func (*Collection) AddUniqueCS added in v2.0.1

func (c *Collection) AddUniqueCS(key string, vKey string, vVal string)

AddUniqueCS will add a value to a key if it is not already there with case sensitive vKey

func (*Collection) Data

func (c *Collection) Data() map[string][]string

Data returns the stored data

func (*Collection) FindRegex

func (c *Collection) FindRegex(key *regexp.Regexp) []MatchData

FindRegex returns a slice of MatchData for the regex

func (*Collection) FindString

func (c *Collection) FindString(key string) []MatchData

FindString returns a slice of MatchData for the string

func (*Collection) Get

func (c *Collection) Get(key string) []string

Get returns a slice of strings for a key

func (*Collection) GetFirstInt

func (c *Collection) GetFirstInt(key string) int

GetFirstInt returns the first int occurrence of a key

func (*Collection) GetFirstInt64

func (c *Collection) GetFirstInt64(key string) int64

GetFirstInt64 returns the first int64 occurrence of a key

func (*Collection) GetFirstString

func (c *Collection) GetFirstString(key string) string

GetFirstString returns the first string occurrence of a key

func (*Collection) Name

func (c *Collection) Name() string

Name returns the name for the current collection

func (*Collection) Remove

func (c *Collection) Remove(key string)

Remove deletes the key from the collection

func (*Collection) Reset

func (c *Collection) Reset()

Reset the current collection

func (*Collection) Set

func (c *Collection) Set(key string, values []string)

Set will replace the key's value with this slice internally converts [] string to []types.AnchoredVar

func (*Collection) SetCS added in v2.0.1

func (c *Collection) SetCS(key string, vKey string, values []string)

SetCS will replace the key's value with this slice internally converts [] string to []types.AnchoredVar with case sensitive vKey

func (*Collection) SetData deprecated

func (c *Collection) SetData(data map[string][]string)

Deprecated: performance-consuming function SetData replaces the data map with something else Useful for persistent collections

func (*Collection) SetIndex

func (c *Collection) SetIndex(key string, index int, value string)

SetIndex will place the value under the index If the index is higher than the current size of the collection it will be appended

func (*Collection) SetIndexCS added in v2.0.1

func (c *Collection) SetIndexCS(key string, index int, vKey string, value string)

SetIndexCS will place the value under the index If the index is higher than the current size of the collection it will be appended with case sensitive vKey

type ErrorLogCallback

type ErrorLogCallback = func(rule MatchedRule)

ErrorLogCallback is used to set a callback function to log errors It is triggered when an error is raised by the WAF It contains the severity so the cb can decide to log it or not

type Macro

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

Macro is used to create tokenized strings that can be "expanded" at high speed and concurrent-safe. A Macro contains tokens for strings and expansions For example: some string %{tx.var} some string The previous example would create 3 tokens: String token: some string Variable token: Variable: TX, key: var String token: some string

func NewMacro

func NewMacro(data string) (*Macro, error)

NewMacro creates a new macro

func (*Macro) Compile

func (m *Macro) Compile(input string) error

Compile is used to parse the input and generate the corresponding token Example input: %{var.foo} and %{var.bar} expected result: [0] macroToken{text: "%{var.foo}", variable: &variables.Var, key: "foo"}, [1] macroToken{text: " and ", variable: nil, key: ""} [2] macroToken{text: "%{var.bar}", variable: &variables.Var, key: "bar"}

func (*Macro) Expand

func (m *Macro) Expand(tx *Transaction) string

Expand the pre-compiled macro expression into a string

func (*Macro) IsExpandable

func (m *Macro) IsExpandable() bool

IsExpandable return true if there are macro expanadable tokens

func (*Macro) String

func (m *Macro) String() string

String returns the original string

type MatchData

type MatchData struct {
	// variable name stored for cache
	VariableName string
	// Variable
	Variable variables.RuleVariable
	// Key of the variable, blank if no key is required
	Key string
	// Value of the current VARIABLE:KEY
	Value string
	// Macro expanded message
	Message string
	// Macro expanded logdata
	Data string
}

MatchData works like VariableKey but is used for logging, so it contains the collection as a string, and it's value

type MatchedRule

type MatchedRule struct {
	// Macro expanded message
	Message string
	// Macro expanded logdata
	Data string
	// Full request uri unparsed
	URI string
	// Transaction id
	ID string
	// Is disruptive
	Disruptive bool
	// Server IP address
	ServerIPAddress string
	// Client IP address
	ClientIPAddress string
	// A slice of matched variables
	MatchedDatas []MatchData
	// Deprecated
	MatchedData MatchData
	// A reference to the triggered rule
	Rule *Rule
}

MatchedRule contains a list of macro expanded messages, matched variables and a pointer to the rule

func (MatchedRule) AuditLog

func (mr MatchedRule) AuditLog(code int) string

AuditLog transforms the matched rule into an error log using the legacy Modsecurity syntax

func (MatchedRule) ErrorLog

func (mr MatchedRule) ErrorLog(code int) string

ErrorLog returns the same as audit log but without matchData

type Rule

type Rule struct {

	// Contains the Id of the parent rule if you are inside
	// a chain. Otherwise, it will be 0
	ParentID int

	// Capture is used by the transaction to tell the operator
	// to capture variables on TX:0-9
	Capture bool

	// Used to mark a rule as a secmarker and alter flows
	SecMark string

	// Contains the raw rule code
	Raw string

	// Contains the child rule to chain, nil if there are no chains
	Chain *Rule

	// DisruptiveStatus is the status that will be set to interruptions
	// by disruptive rules
	DisruptiveStatus int

	// Where is this rule stored
	File string

	// Line of the file where this rule was found
	Line int

	// METADATA
	// Rule unique identifier, can be a an int
	ID int

	// Rule tag list
	Tags []string

	// Rule execution phase 1-5
	Phase types.RulePhase

	// Message text to be macro expanded and logged
	// In future versions we might use a special type of string that
	// supports cached macro expansions. For performance
	Msg Macro

	// Rule revision value
	Rev string

	// Rule maturity index
	Maturity int

	// RuleSet Version
	Version string

	// Rule accuracy
	Accuracy int

	// Rule severity
	Severity types.RuleSeverity

	// Rule logdata
	LogData Macro

	// If true, triggering this rule write to the error log
	Log bool

	// If true, triggering this rule write to the audit log
	Audit bool

	// If true, the transformations will be multi matched
	MultiMatch bool

	// Used for error logging
	Disruptive bool

	HasChain bool
	// contains filtered or unexported fields
}

Rule is used to test a Transaction against certain operators and execute actions

func NewRule

func NewRule() *Rule

NewRule returns a new initialized rule

func (*Rule) AddAction

func (r *Rule) AddAction(name string, action RuleAction) error

AddAction adds an action to the rule

func (*Rule) AddTransformation

func (r *Rule) AddTransformation(name string, t RuleTransformation) error

AddTransformation adds a transformation to the rule it fails if the transformation cannot be found

func (*Rule) AddVariable

func (r *Rule) AddVariable(v variables.RuleVariable, key string, iscount bool) error

AddVariable adds a variable to the rule The key can be a regexp.Regexp, a string or nil, in case of regexp it will be used to match the variable, in case of string it will be a fixed match, in case of nil it will match everything

func (*Rule) AddVariableNegation

func (r *Rule) AddVariableNegation(v variables.RuleVariable, key string) error

AddVariableNegation adds an exception to a variable It passes through if the variable is not used It returns an error if the selector is empty, or applied on an undefined rule for example: OK: SecRule ARGS|!ARGS:id "..." OK: SecRule !ARGS:id "..." ERROR: SecRule !ARGS: "..."

func (*Rule) ClearTransformations

func (r *Rule) ClearTransformations()

ClearTransformations clears all the transformations it is mostly used by the "none" transformation

func (*Rule) Evaluate

func (r *Rule) Evaluate(tx *Transaction) []MatchData

Evaluate will evaluate the current rule for the indicated transaction If the operator matches, actions will be evaluated, and it will return the matched variables, keys and values (MatchData)

func (*Rule) SetOperator

func (r *Rule) SetOperator(operator RuleOperator, functionName string, params string)

SetOperator sets the operator of the rule There can be only one operator per rule functionName and params are used for logging

type RuleAction

type RuleAction interface {
	// Init an action, will be done during compilation
	Init(*Rule, string) error
	// Evaluate will be done during rule evaluation
	Evaluate(*Rule, *Transaction)
	// Type will return the rule type, it's used by Evaluate
	// to choose when to evaluate each action
	Type() types.RuleActionType
}

RuleAction is used to create Action plugins See the documentation: https://www.coraza.io/docs/waf/actions

type RuleGroup

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

RuleGroup is a collection of rules It contains all helpers required to manage the rules It is not concurrent safe, so it's not recommended to use it after compilation

func NewRuleGroup

func NewRuleGroup() RuleGroup

NewRuleGroup creates an empty RuleGroup that can be attached to a WAF instance You might use this function to replace the rules and "reload" the WAF

func (*RuleGroup) Add

func (rg *RuleGroup) Add(rule *Rule) error

Add a rule to the collection Will return an error if the ID is already used

func (*RuleGroup) Clear

func (rg *RuleGroup) Clear()

Clear will remove each and every rule stored

func (*RuleGroup) Count

func (rg *RuleGroup) Count() int

Count returns the count of rules

func (*RuleGroup) DeleteByID

func (rg *RuleGroup) DeleteByID(id int)

DeleteByID removes a rule by it's Id

func (*RuleGroup) Eval

func (rg *RuleGroup) Eval(phase types.RulePhase, tx *Transaction) bool

Eval rules for the specified phase, between 1 and 5 Returns true if transaction is disrupted

func (*RuleGroup) FindByID

func (rg *RuleGroup) FindByID(id int) *Rule

FindByID return a Rule with the requested Id

func (*RuleGroup) FindByMsg

func (rg *RuleGroup) FindByMsg(msg string) []*Rule

FindByMsg returns a slice of rules that matches the msg

func (*RuleGroup) FindByTag

func (rg *RuleGroup) FindByTag(tag string) []*Rule

FindByTag returns a slice of rules that matches the tag

func (*RuleGroup) GetRules

func (rg *RuleGroup) GetRules() []*Rule

GetRules returns the slice of rules, it's concurrent safe.

type RuleOperator

type RuleOperator interface {
	// Init is used during compilation to setup and cache
	// the operator
	Init(string) error
	// Evaluate is used during the rule evaluation,
	// it returns true if the operator succeeded against
	// the input data for the transaction
	Evaluate(*Transaction, string) bool
}

RuleOperator interface is used to define rule @operators

type RuleTransformation

type RuleTransformation = func(input string) (string, error)

RuleTransformation is used to create transformation plugins See the documentation for more information If a transformation fails to run it will return the same string and an error, errors are only used for logging, it won't stop the execution of the rule

type Transaction

type Transaction struct {
	// Transaction ID
	ID string

	// Contains the list of matched rules and associated match information
	MatchedRules []MatchedRule

	// True if the transaction has been disrupted by any rule
	Interruption *types.Interruption

	// This is used to store log messages
	Logdata string

	// Rules will be skipped after a rule with this SecMarker is found
	SkipAfter string

	// Copies from the WafInstance that may be overwritten by the ctl action
	AuditEngine              types.AuditEngineStatus
	AuditLogParts            types.AuditLogParts
	ForceRequestBodyVariable bool
	RequestBodyAccess        bool
	RequestBodyLimit         int64
	ResponseBodyAccess       bool
	ResponseBodyLimit        int64
	RuleEngine               types.RuleEngineStatus
	HashEngine               bool
	HashEnforcement          bool

	// Stores the last phase that was evaluated
	// Used by allow to skip phases
	LastPhase types.RulePhase

	// Handles request body buffers
	RequestBodyBuffer *BodyBuffer

	// Handles response body buffers
	ResponseBodyBuffer *BodyBuffer

	// Will skip this number of rules, this value will be decreased on each skip
	Skip int

	// Actions with capture features will read the capture state from this field
	// We have currently removed this feature as Capture will always run
	// We must reuse it in the future
	Capture bool

	// Contains a Waf instance for the current transaction
	Waf *Waf

	// Timestamp of the request
	Timestamp int64
	// contains filtered or unexported fields
}

Transaction is created from a WAF instance to handle web requests and responses, it contains a copy of most WAF configurations that can be safely changed. Transactions are used to store all data like URLs, request and response headers. Transactions are used to evaluate rules by phase and generate disruptive actions. Disruptive actions can be read from *tx.Interruption. It is safe to manage multiple transactions but transactions themself are not thread safe

func (*Transaction) AddArgument

func (tx *Transaction) AddArgument(orig string, key string, value string)

AddArgument Add arguments GET or POST This will set ARGS_(GET|POST), ARGS, ARGS_NAMES, ARGS_COMBINED_SIZE and ARGS_(GET|POST)_NAMES

func (*Transaction) AddRequestHeader

func (tx *Transaction) AddRequestHeader(key string, value string)

AddRequestHeader Adds a request header

With this method it is possible to feed Coraza with a request header. Note: Golang's *http.Request object will not contain a "Host" header, and you might have to force it

func (*Transaction) AddResponseHeader

func (tx *Transaction) AddResponseHeader(key string, value string)

AddResponseHeader Adds a response header variable

With this method it is possible to feed Coraza with a response header.

func (*Transaction) AuditLog

func (tx *Transaction) AuditLog() *loggers.AuditLog

AuditLog returns an AuditLog struct, used to write audit logs

func (*Transaction) CaptureField

func (tx *Transaction) CaptureField(index int, value string)

CaptureField is used to set the TX:[index] variables by operators that supports capture, like @rx

func (*Transaction) Clean

func (tx *Transaction) Clean() error

Clean the transaction after phase 5 This method helps the GC to clean up the transaction faster and release resources It also allows caches the transaction back into the sync.Pool

func (*Transaction) ExtractArguments

func (tx *Transaction) ExtractArguments(orig string, uri string)

ExtractArguments transforms an url encoded string to a map and creates ARGS_POST|GET

func (*Transaction) GetCollection

func (tx *Transaction) GetCollection(variable variables.RuleVariable) *Collection

GetCollection transforms a VARIABLE_ constant into a *Collection used to get VARIABLES data

func (*Transaction) GetField

func (tx *Transaction) GetField(rv ruleVariableParams) []MatchData

GetField Retrieve data from collections applying exceptions In future releases we may remove de exceptions slice and make it easier to use

func (*Transaction) GetStopWatch

func (tx *Transaction) GetStopWatch() string

GetStopWatch is used to debug phase durations Normally it should be named StopWatch() but it would be confusing

func (*Transaction) Interrupted

func (tx *Transaction) Interrupted() bool

Interrupted will return true if the transaction was interrupted

func (*Transaction) IsProcessableResponseBody

func (tx *Transaction) IsProcessableResponseBody() bool

IsProcessableResponseBody returns true if the response body meets the criteria to be processed, response headers must be set before this. The content-type response header must be in the SecRequestBodyMime This is used by webservers to choose whether tostream response buffers directly to the client or write them to Coraza

func (*Transaction) MatchRule

func (tx *Transaction) MatchRule(r *Rule, mds []MatchData)

MatchRule Matches a rule to be logged

func (*Transaction) ParseRequestReader

func (tx *Transaction) ParseRequestReader(data io.Reader) (*types.Interruption, error)

ParseRequestReader Parses binary request including body, it does only support http/1.1 and http/1.0 This function does not run ProcessConnection This function will store in memory the whole reader, DON't USE IT FOR PRODUCTION yet

func (*Transaction) PrintLog added in v2.0.1

func (tx *Transaction) PrintLog()

PrintLog prints the detection log for detection to stderr

func (*Transaction) ProcessConnection

func (tx *Transaction) ProcessConnection(client string, cPort int, server string, sPort int)

ProcessConnection should be called at very beginning of a request process, it is expected to be executed prior to the virtual host resolution, when the connection arrives on the server. Important: Remember to check for a possible intervention.

func (*Transaction) ProcessLogging

func (tx *Transaction) ProcessLogging()

ProcessLogging Logging all information relative to this transaction. An error log At this point there is not need to hold the connection, the response can be delivered prior to the execution of this method.

func (*Transaction) ProcessRequest

func (tx *Transaction) ProcessRequest(req *http.Request) (*types.Interruption, error)

ProcessRequest fills all transaction variables from an http.Request object Most implementations of Coraza will probably use http.Request objects so this will implement all phase 0, 1 and 2 variables Note: This function will stop after an interruption Note: Do not manually fill any request variables

func (*Transaction) ProcessRequestBody

func (tx *Transaction) ProcessRequestBody() (*types.Interruption, error)

ProcessRequestBody Performs the request body (if any)

This method perform the analysis on the request body. It is optional to call that function. If this API consumer already know that there isn't a body for inspect it is recommended to skip this step.

Remember to check for a possible intervention.

func (*Transaction) ProcessRequestHeaders

func (tx *Transaction) ProcessRequestHeaders() *types.Interruption

ProcessRequestHeaders Performs the analysis on the request readers.

This method perform the analysis on the request headers, notice however that the headers should be added prior to the execution of this function.

note: Remember to check for a possible intervention.

func (*Transaction) ProcessResponseBody

func (tx *Transaction) ProcessResponseBody() (*types.Interruption, error)

ProcessResponseBody Perform the request body (if any)

This method perform the analysis on the request body. It is optional to call that method. If this API consumer already know that there isn't a body for inspect it is recommended to skip this step.

note Remember to check for a possible intervention.

func (*Transaction) ProcessResponseHeaders

func (tx *Transaction) ProcessResponseHeaders(code int, proto string) *types.Interruption

ProcessResponseHeaders Perform the analysis on the response readers.

This method perform the analysis on the response headers, notice however that the headers should be added prior to the execution of this function.

note: Remember to check for a possible intervention.

func (*Transaction) ProcessURI

func (tx *Transaction) ProcessURI(uri string, method string, httpVersion string)

ProcessURI Performs the analysis on the URI and all the query string variables. This method should be called at very beginning of a request process, it is expected to be executed prior to the virtual host resolution, when the connection arrives on the server. note: There is no direct connection between this function and any phase of

the SecLanguages phases. It is something that may occur between the
SecLanguage phase 1 and 2.

note: This function won't add GET arguments, they must be added with AddArgument

func (*Transaction) RemoveRuleByID

func (tx *Transaction) RemoveRuleByID(id int)

RemoveRuleByID Removes a rule from the transaction It does not affect the WAF rules

func (*Transaction) RemoveRuleTargetByID

func (tx *Transaction) RemoveRuleTargetByID(id int, variable variables.RuleVariable, key string)

RemoveRuleTargetByID Removes the VARIABLE:KEY from the rule ID It's mostly used by CTL to dynamically remove targets from rules

type Waf

type Waf struct {
	// ruleGroup object, contains all rules and helpers
	Rules RuleGroup

	// Audit mode status
	AuditEngine types.AuditEngineStatus

	// Array of logging parts to be used
	AuditLogParts types.AuditLogParts

	// Status of the content injection for responses and requests
	ContentInjection bool

	// If true, transactions will have access to the request body
	RequestBodyAccess bool

	// Request body page file limit
	RequestBodyLimit int64

	// Request body in memory limit
	RequestBodyInMemoryLimit int64

	// If true, transactions will have access to the response body
	ResponseBodyAccess bool

	// Response body memory limit
	ResponseBodyLimit int64

	// Defines if rules are going to be evaluated
	RuleEngine types.RuleEngineStatus

	// If true, transaction will fail if response size is bigger than the page limit
	RejectOnResponseBodyLimit bool

	// If true, transaction will fail if request size is bigger than the page limit
	RejectOnRequestBodyLimit bool

	// Responses will only be loaded if mime is listed here
	ResponseBodyMimeTypes []string

	// Web Application id, apps sharing the same id will share persistent collections
	WebAppID string

	// Add significant rule components to audit log
	ComponentNames []string

	// Contains the regular expression for relevant status audit logging
	AuditLogRelevantStatus *regexp.Regexp

	// If true WAF engine will fail when remote rules cannot be loaded
	AbortOnRemoteRulesFail bool

	// Instructs the waf to change the Server response header
	ServerSignature string

	// This directory will be used to store page files
	TmpDir string

	// Sensor ID identifies the sensor in ac cluster
	SensorID string

	// Path to store data files (ex. cache)
	DataDir string

	// If true, the WAF will store the uploaded files in the UploadDir
	// directory
	UploadKeepFiles bool
	// UploadFileMode instructs the waf to set the file mode for uploaded files
	UploadFileMode fs.FileMode
	// UploadFileLimit is the maximum size of the uploaded file to be stored
	UploadFileLimit int
	// UploadDir is the directory where the uploaded files will be stored
	UploadDir string

	RequestBodyNoFilesLimit int64

	RequestBodyLimitAction types.RequestBodyLimitAction

	ArgumentSeparator string

	// ProducerConnector is used by connectors to identify the producer
	// on audit logs, for example, apache-modcoraza
	ProducerConnector string
	// ProducerConnectorVersion is used by connectors to identify the producer
	// version on audit logs
	ProducerConnectorVersion string

	// Used for the debug logger
	Logger *zap.Logger

	// AuditLogWriter is used to write audit logs
	AuditLogWriter loggers.LogWriter
	// contains filtered or unexported fields
}

Waf instance is used to store configurations and rules Every web application should have a different Waf instance, but you can share an instance if you are ok with sharing configurations, rules and logging. Transactions and SecLang parser requires a Waf instance You can use as many Waf instances as you want, and they are concurrent safe All Waf instance fields are immutable, if you update any of them in runtime you might create concurrency issues

func NewWaf

func NewWaf() *Waf

NewWaf creates a new WAF instance with default variables

func (*Waf) NewTransaction

func (w *Waf) NewTransaction() *Transaction

NewTransaction Creates a new initialized transaction for this WAF instance

func (*Waf) SetDebugLogLevel

func (w *Waf) SetDebugLogLevel(lvl int) error

SetDebugLogLevel changes the debug level of the Waf instance

func (*Waf) SetDebugLogPath

func (w *Waf) SetDebugLogPath(path string) error

SetDebugLogPath sets the path for the debug log If the path is empty, the debug log will be disabled note: this is not thread safe

func (*Waf) SetErrorLogCb

func (w *Waf) SetErrorLogCb(cb ErrorLogCallback)

SetErrorLogCb sets the callback function for error logging The error callback receives all the error data and some helpers to write modsecurity style logs

Directories

Path Synopsis
examples
Package loggers implements a set of log formatters and writers for audit logging.
Package loggers implements a set of log formatters and writers for audit logging.
variables
Package variables contains the representation of the variables used in the rules Variables are created as bytes and they have a string representation
Package variables contains the representation of the variables used in the rules Variables are created as bytes and they have a string representation
utils
url

Jump to

Keyboard shortcuts

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