coraza

package module
v3.0.0-...-6323aa8 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2022 License: Apache-2.0 Imports: 23 Imported by: 0

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/v3"
	"github.com/corazawaf/coraza/v3/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(context.Background())
	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

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 DebugLogger

type DebugLogger struct {
	Level LogLevel
	// contains filtered or unexported fields
}

DebugLogger is a logger that logs to the standard logger

func (*DebugLogger) Close

func (l *DebugLogger) Close() error

Close closes the logger

func (*DebugLogger) Debug

func (l *DebugLogger) Debug(message string, args ...interface{})

Debug logs a debug message

func (*DebugLogger) Error

func (l *DebugLogger) Error(message string, args ...interface{})

Error logs an error message

func (*DebugLogger) Info

func (l *DebugLogger) Info(message string, args ...interface{})

Info logs an info message

func (*DebugLogger) SetLevel

func (l *DebugLogger) SetLevel(level LogLevel)

SetLevel sets the log level

func (*DebugLogger) SetOutput

func (l *DebugLogger) SetOutput(w io.Writer)

SetOutput sets the output for the logger

func (*DebugLogger) Trace

func (l *DebugLogger) Trace(message string, args ...interface{})

Trace logs a trace message

func (*DebugLogger) Warn

func (l *DebugLogger) Warn(message string, args ...interface{})

Warn logs a warning message

type ErrorLogCallback

type ErrorLogCallback = func(rule types.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 LogLevel

type LogLevel int

LogLevel is the type of log level

const (
	// LogLevelUnknown is a default value for unknown log level
	LogLevelUnknown LogLevel = iota
	// LogLevelInfo is the lowest level of logging
	LogLevelInfo
	// LogLevelWarn is the level of logging for warnings
	LogLevelWarn
	// LogLevelError is the level of logging for errors
	LogLevelError
	// LogLevelDebug is the level of logging for debug messages
	LogLevelDebug
	// LogLevelTrace is the highest level of logging
	LogLevelTrace
)

func (LogLevel) Invalid

func (level LogLevel) Invalid() bool

Invalid returns true if the log level is invalid

func (LogLevel) String

func (level LogLevel) String() string

String returns the string representation of the log level

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 Rule

type Rule struct {
	types.RuleMetadata

	// 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

	// 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

	// 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 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) []types.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(RuleOperatorOptions) 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 RuleOperatorOptions

type RuleOperatorOptions struct {
	// Arguments is used to store the operator args
	Arguments string

	// Path is used to store a list of possible data paths
	Path []string
}

RuleOperatorOptions is used to store the options for a rule operator

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 []types.MatchedRule

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

	// Contains all Collections, including persistent
	Collections [types.VariablesCount]collection.Collection

	// 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

	Variables TransactionVariables
	// 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) Debug

func (tx *Transaction) Debug() string

Debug will return a string with the transaction debug information

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) GetField

func (tx *Transaction) GetField(rv ruleVariableParams) []types.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 []types.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) 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) 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 TransactionVariables

type TransactionVariables struct {
	// Simple Variables
	Userid                        *collection.Simple
	UrlencodedError               *collection.Simple
	ResponseContentType           *collection.Simple
	UniqueID                      *collection.Simple
	ArgsCombinedSize              *collection.SizeProxy
	AuthType                      *collection.Simple
	FilesCombinedSize             *collection.Simple
	FullRequest                   *collection.Simple
	FullRequestLength             *collection.Simple
	InboundDataError              *collection.Simple
	MatchedVar                    *collection.Simple
	MatchedVarName                *collection.Simple
	MultipartBoundaryQuoted       *collection.Simple
	MultipartBoundaryWhitespace   *collection.Simple
	MultipartCrlfLfLines          *collection.Simple
	MultipartDataAfter            *collection.Simple
	MultipartDataBefore           *collection.Simple
	MultipartFileLimitExceeded    *collection.Simple
	MultipartHeaderFolding        *collection.Simple
	MultipartInvalidHeaderFolding *collection.Simple
	MultipartInvalidPart          *collection.Simple
	MultipartInvalidQuoting       *collection.Simple
	MultipartLfLine               *collection.Simple
	MultipartMissingSemicolon     *collection.Simple
	MultipartStrictError          *collection.Simple
	MultipartUnmatchedBoundary    *collection.Simple
	OutboundDataError             *collection.Simple
	PathInfo                      *collection.Simple
	QueryString                   *collection.Simple
	RemoteAddr                    *collection.Simple
	RemoteHost                    *collection.Simple
	RemotePort                    *collection.Simple
	ReqbodyError                  *collection.Simple
	ReqbodyErrorMsg               *collection.Simple
	ReqbodyProcessorError         *collection.Simple
	ReqbodyProcessorErrorMsg      *collection.Simple
	ReqbodyProcessor              *collection.Simple
	RequestBasename               *collection.Simple
	RequestBody                   *collection.Simple
	RequestBodyLength             *collection.Simple
	RequestFilename               *collection.Simple
	RequestLine                   *collection.Simple
	RequestMethod                 *collection.Simple
	RequestProtocol               *collection.Simple
	RequestURI                    *collection.Simple
	RequestURIRaw                 *collection.Simple
	ResponseBody                  *collection.Simple
	ResponseContentLength         *collection.Simple
	ResponseProtocol              *collection.Simple
	ResponseStatus                *collection.Simple
	ServerAddr                    *collection.Simple
	ServerName                    *collection.Simple
	ServerPort                    *collection.Simple
	Sessionid                     *collection.Simple
	HighestSeverity               *collection.Simple
	StatusLine                    *collection.Simple
	InboundErrorData              *collection.Simple
	// Custom
	Env      *collection.Map
	TX       *collection.Map
	Rule     *collection.Map
	Duration *collection.Simple
	// Proxy Variables
	Args *collection.Proxy
	// Maps Variables
	ArgsGet              *collection.Map
	ArgsPost             *collection.Map
	ArgsPath             *collection.Map
	FilesTmpNames        *collection.Map
	Geo                  *collection.Map
	Files                *collection.Map
	RequestCookies       *collection.Map
	RequestHeaders       *collection.Map
	ResponseHeaders      *collection.Map
	MultipartName        *collection.Map
	MatchedVarsNames     *collection.Map
	MultipartFilename    *collection.Map
	MatchedVars          *collection.Map
	FilesSizes           *collection.Map
	FilesNames           *collection.Map
	FilesTmpContent      *collection.Map
	ResponseHeadersNames *collection.Map
	RequestHeadersNames  *collection.Map
	RequestCookiesNames  *collection.Map
	XML                  *collection.Map
	RequestXML           *collection.Map
	ResponseXML          *collection.Map
	// Persistent variables
	IP *collection.Map
	// Translation Proxy Variables
	ArgsNames     *collection.TranslationProxy
	ArgsGetNames  *collection.TranslationProxy
	ArgsPostNames *collection.TranslationProxy
}

TransactionVariables has pointers to all the variables of the transaction

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 *DebugLogger

	// 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(ctx context.Context) *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
internal
io
url
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

Jump to

Keyboard shortcuts

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