waf

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: BSD-3-Clause, GPL-3.0 Imports: 35 Imported by: 0 modules, 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 waf implements a bounded HTTP reverse-proxy inspection boundary.

Package waf spools and inspects complete HTTP requests before opening an upstream request. MaxConcurrent bounds admitted requests, including long-lived responses and upgraded connections. MaxBodyBytes bounds wire and expanded request bytes; MaxResponseBytes applies only with InspectResponse. Limits are 1..64 MiB per wire and expanded representation. Spools spill above 64 KiB to private temporary files; reference-counted views retain files until both inspection and forwarding finish. NativeBodyBytes reserves metadata headroom within policy.MaxEventBytes (2 MiB). Body-dependent policies reject larger bodies, never truncated projections. Compiled RequiresBody(phase string) bool metadata permits larger body-independent traffic; without that capability every phase conservatively requires Body. JSON, XML and URL-encoded bodies additionally enforce NativeBodyBytes to bound scalar allocation. Multipart files and opaque bodies can use the complete configured spool limit. BodyCapabilities reports these bounds. Coraza owns additional internal buffers; its response buffer is memory-backed up to MaxResponseBytes, not a shared spool. MaxBufferedBytes defaults to 64 MiB and cannot exceed 1 GiB. One runtime budget covers HTTP spool contents/scratch, native projections, Coraza reservations and both message directions. Exhaustion rejects locally with 503 or terminates a message stream before releasing its frame. Shared views retain their quota until the final close; failed partial spools remove their files. This is retained-byte accounting, not an operating-system RSS limit; library/allocator overhead remains. Inspection headers are bounded to 32 KiB, 128 names and 1024 values; each routing field is bounded to 65536 bytes. Oversized request metadata receives 414/431; oversized upstream headers receive 502 before any origin response is forwarded. JSON/XML nesting is capped at 64 and parsed argument/part entries at 1000. Structural validation runs before disruptive rules, including in monitor mode.

The caller owns listeners and http.Server configuration. Set ReadHeaderTimeout, MaxHeaderBytes, IdleTimeout and shutdown deadlines there. BodyTimeout bounds the incoming body, upstream exchange through response headers, and opted-in response buffering. A blanket server WriteTimeout also terminates streaming responses. Bind AdminHandler to a private/authenticated listener. Run WriteAudit separately with an owned context and writer; slow audit consumers cause counted drops.

Default response coverage is status and headers only, before forwarding final headers. Bodies and trailers are streamed without inspection; WebSocket frames are tunneled after an inspected handshake. Request bodies must finish before forwarding in the base handler. MessageHandler explicitly enables independent WebSocket and HTTP/2 gRPC message gates instead, with a 1 MiB wire/expanded message limit, no WebSocket compression, and identity/gzip gRPC encoding. Native and Coraza inspection finish before any message frame header is released. InspectResponse spools and bounds complete responses and rejects upgrades; it is incompatible with unbounded response streams. Native evaluation errors fail closed: HTTP 503 in the base handler, or stream termination in message mode.

SetPolicy atomically replaces policy for subsequent inspection snapshots. Each admitted request uses one snapshot for both phases. Config is immutable after New. SetEvaluator installs one bootstrap-only hook and receives that same compiled snapshot for every native phase/message/trailer. Default evaluation is Compiled.Evaluate. The shared guard's default request unit counts initial request headers once; message unit counts request messages. Trailer and response events still reach the hook for native evaluation. Message payloads are borrowed as bytes, with a native Body string created only for body-dependent phases. SetDraining rejects new requests and makes readiness fail. Close also cancels active proxy exchanges, closes upgraded clients and evicts idle upstream connections. Callers still own Server.Shutdown and accepted idle client sockets. SetReadinessCheck installs one bootstrap-only, concurrency-safe cached dependency predicate. Readiness ANDs it with policy availability, draining and lifetime state; resuming a drained listener cannot clear an unhealthy dependency. Admin probes also freeze bootstrap hooks. A readiness predicate must not initiate network I/O.

CorazaCRS additionally requires the coraza build tag, coraza/v3 v3.8.1 and coraza-coreruleset/v4 v4.25.0. Without that tag enabling it fails startup. Its audit/debug sinks are disabled; only outer redacted decisions are queued.

Routes optionally replaces single-origin forwarding with at most 128 immutable bindings. Exact host authorities (case-insensitive, ports significant), explicit methods and segment-bounded PathPrefix match in descending Priority order. Overlapping equal-priority matches fail compilation. Unknown hosts receive 421; unmatched paths/methods receive 404. Noncanonical/encoded paths fail closed. Each binding requires its own PolicyFile, expected PolicyID, origin and limits. All files, TLS and inspection engines compile before publication; the global SetPolicy target never changes a route. RouteTarget grants an in-process identity-checked, expected-revision activation capability for one bootstrap ID. ReloadRoutePolicies atomically replaces the complete table from bound files; requests pin their binding through response inspection. Retired generations close after their last request. Listener concurrency and retained-byte quotas cover all bindings. MessageHandler builds WS/compression and gRPC/H3 adapters on each same bound origin, transport, policy and contract, including after file reloads. The CLI requires --route-id for management, fleet, effects, shared-rate and native state; one immutable bootstrap attachment owns that route. Private dispatch context supplies its route ID; duplicate bundle IDs and client headers cannot select remote counters or effects. Other routes evaluate locally. Root readiness ANDs bound dependencies; attachment drain/unavailability rejects that route only. Fleet checks target policy identity before cache persistence and acknowledgment. Effects compile only on the selected route with explicit broker admission.

DescriptorPath, DescriptorSHA256 and APIValidateResponse belong to each route; only trusted BootstrapDir is inherited. An absent contract never falls back to another route or the global descriptor. Complete HTTP bodies and decompressed gRPC messages pass their contract before forwarding. WS needs explicit API passthrough because an HTTP operation is not a WebSocket message schema.

CRSProfile requires CorazaCRS, paranoia 1..4 and anomaly thresholds 1..100. Up to 64 exclusions name recognized request attack detectors, optionally one ARGS parameter, with owner/reason and expiry no more than 90 days ahead. Generated phase-1 controls expire on transaction time before CRS executes; no raw SecRule or include path is admitted. Optional Path/Method narrow an exclusion to an exact request; Parameter uses Coraza ARGS names (json.text for a JSON text field). Legacy CRSTargetExclusions map into this same registry as exact Path/Method, Argument-to-Parameter exclusions with no expiry; migrating to CRSProfile adds owner/reason/expiry. Both forms check real pinned attack rule IDs. Native denies, API contracts and structural validation still run.

ClientCA enables listener mTLS. UpstreamCert/UpstreamKey enable upstream mTLS; HTTPS routes require explicit UpstreamServerName and always verify certificates. TLSConfig provides per-handshake listener snapshots. ReloadTLS validates complete identity pairs and client trust before publication; failures retain live state. CLI SIGHUP reloads TLS and atomically reloads local route policy files, retaining the selected attachment's externally owned policy pointer. Inflight requests keep their admitted revision and API contract. Route/upstream configuration changes require restart. Existing TLS connections retain their handshake identity.

Index

Constants

View Source
const MaxInspectionBodyBytes int64 = 64 << 20

MaxInspectionBodyBytes bounds each wire and expanded disk-spooled representation.

View Source
const NativeBodyBytes = policy.MaxEventBytes - 5*maxInspectionFieldBytes - maxInspectionHeaderBytes - 1024

NativeBodyBytes reserves space for every bounded HTTP metadata field.

Variables

This section is empty.

Functions

func BoundRouteID

func BoundRouteID(ctx context.Context) string

BoundRouteID is supplied by the selected immutable binding, never by headers.

func ValidateConfig

func ValidateConfig(c Config) error

Types

type AuditRecord

type AuditRecord struct {
	Phase    string `json:"phase"`
	Verdict  string `json:"verdict"`
	Status   int    `json:"status"`
	RuleID   string `json:"rule_id,omitempty"`
	Revision string `json:"revision,omitempty"`
	Monitor  bool   `json:"monitor"`
}

AuditRecord deliberately excludes URLs, addresses, headers and bodies.

type BodyCapabilities

type BodyCapabilities struct {
	MaxRequestBytes           int64
	MaxResponseBytes          int64
	MaxNativeBodyBytes        int
	MemorySpoolBytes          int
	RequestRequiresBody       bool
	ResponseRequiresBody      bool
	MaxStructuredBytes        int
	CorazaResponseMemoryBytes int64
	EffectiveRequestBytes     int64
	EffectiveResponseBytes    int64
	MaxBufferedBytes          int64
	BufferedBytes             int64
	InspectResponseBody       bool
}

type CRSExclusion

type CRSExclusion struct {
	Path      string    `json:"path,omitempty" yaml:"path,omitempty"`
	Method    string    `json:"method,omitempty" yaml:"method,omitempty"`
	RuleID    int       `json:"ruleID" yaml:"ruleID"`
	Parameter string    `json:"parameter,omitempty" yaml:"parameter,omitempty"`
	Owner     string    `json:"owner" yaml:"owner"`
	Reason    string    `json:"reason" yaml:"reason"`
	ExpiresAt time.Time `json:"expiresAt" yaml:"expiresAt"`
}

Exclusions affect one CRS detector on this binding only, never native policies or parsers.

type CRSProfile

type CRSProfile struct {
	ParanoiaLevel     int            `json:"paranoiaLevel" yaml:"paranoiaLevel"`
	InboundThreshold  int            `json:"inboundThreshold" yaml:"inboundThreshold"`
	OutboundThreshold int            `json:"outboundThreshold" yaml:"outboundThreshold"`
	Exclusions        []CRSExclusion `json:"exclusions,omitempty" yaml:"exclusions,omitempty"`
}

type CRSTargetExclusion

type CRSTargetExclusion struct {
	Path     string `json:"path" yaml:"path"`
	Method   string `json:"method" yaml:"method"`
	Argument string `json:"argument" yaml:"argument"`
	RuleID   int    `json:"ruleID" yaml:"ruleID"`
}

CRSTargetExclusion narrows one application-attack rule to an exact route, method and argument. Structural validation and all other targets remain active.

type Config

type Config struct {
	Routes             []RouteConfig `json:"routes,omitempty" yaml:"routes,omitempty"`
	CRSProfile         *CRSProfile   `json:"crsProfile,omitempty" yaml:"crsProfile,omitempty"`
	ClientCA           string        `json:"clientCA,omitempty" yaml:"clientCA,omitempty"`
	UpstreamCert       string        `json:"upstreamCert,omitempty" yaml:"upstreamCert,omitempty"`
	UpstreamKey        string        `json:"upstreamKey,omitempty" yaml:"upstreamKey,omitempty"`
	Version            string        `json:"version" yaml:"version"`
	Listen             string        `json:"listen" yaml:"listen"`
	AdminListen        string        `json:"adminListen" yaml:"adminListen"`
	Upstream           string        `json:"upstream" yaml:"upstream"`
	PolicyFile         string        `json:"policyFile" yaml:"policyFile"`
	MaxBodyBytes       int64         `json:"maxBodyBytes" yaml:"maxBodyBytes"`
	MaxResponseBytes   int64         `json:"maxResponseBytes" yaml:"maxResponseBytes"`
	MaxBufferedBytes   int64         `json:"maxBufferedBytes,omitempty" yaml:"maxBufferedBytes,omitempty"`
	MaxConcurrent      int           `json:"maxConcurrent" yaml:"maxConcurrent"`
	BodyTimeout        string        `json:"bodyTimeout" yaml:"bodyTimeout"`
	TLSCert            string        `json:"tlsCert,omitempty" yaml:"tlsCert,omitempty"`
	TLSKey             string        `json:"tlsKey,omitempty" yaml:"tlsKey,omitempty"`
	UpstreamCA         string        `json:"upstreamCA,omitempty" yaml:"upstreamCA,omitempty"`
	UpstreamServerName string        `json:"upstreamServerName,omitempty" yaml:"upstreamServerName,omitempty"`
	TrustedProxyCIDRs  []string      `json:"trustedProxyCIDRs,omitempty" yaml:"trustedProxyCIDRs,omitempty"`
	InspectResponse    bool          `json:"inspectResponse" yaml:"inspectResponse"`
	AllowedHosts       []string      `json:"allowedHosts,omitempty" yaml:"allowedHosts,omitempty"`
	CorazaCRS          bool          `json:"corazaCRS,omitempty" yaml:"corazaCRS,omitempty"`
	// API artifacts are trusted bootstrap inputs, independent of policy reloads.
	DescriptorPath      string               `json:"descriptorPath,omitempty" yaml:"descriptorPath,omitempty"`
	DescriptorSHA256    string               `json:"descriptorSHA256,omitempty" yaml:"descriptorSHA256,omitempty"`
	BootstrapDir        string               `json:"bootstrapDir,omitempty" yaml:"bootstrapDir,omitempty"`
	APIValidateResponse bool                 `json:"apiValidateResponse,omitempty" yaml:"apiValidateResponse,omitempty"`
	CRSTargetExclusions []CRSTargetExclusion `json:"crsTargetExclusions,omitempty" yaml:"crsTargetExclusions,omitempty"`
}

func LoadConfig

func LoadConfig(data []byte) (Config, error)

type Firewall

type Firewall struct {
	Operations *runtimeobs.Monitor
	// contains filtered or unexported fields
}

func New

func New(c Config, p *policy.Compiled) (*Firewall, error)

func NewWithOptions

func NewWithOptions(c Config, p *policy.Compiled, options Options) (*Firewall, error)

func (*Firewall) AdminHandler

func (f *Firewall) AdminHandler() http.Handler

func (*Firewall) BodyCapabilities

func (f *Firewall) BodyCapabilities() BodyCapabilities

JSON, XML and URL-encoded parsers additionally bound scalar allocations.

func (*Firewall) Close

func (f *Firewall) Close() error

func (*Firewall) MessageHandler

func (f *Firewall) MessageHandler(websocket, grpc bool) (http.Handler, error)

MessageHandler explicitly bypasses full-body buffering only for enabled modes. Each connection/RPC pins one policy revision and is canceled by Firewall.Close.

func (*Firewall) Policy

func (f *Firewall) Policy() *policy.Compiled

func (*Firewall) ReloadRoutePolicies

func (f *Firewall) ReloadRoutePolicies() error

ReloadRoutePolicies reloads only operator-bound files and publishes all revisions together. Existing requests retain their selected binding until the response completes.

func (*Firewall) ReloadTLS

func (f *Firewall) ReloadTLS() error

ReloadTLS reads complete pairs before publication. A failed reload preserves live TLS and policy.

func (*Firewall) RouteTarget

func (f *Firewall) RouteTarget(id string) (*RoutePolicyTarget, error)

RouteTarget grants activation for one bootstrap ID, with no path or upstream mutation.

func (*Firewall) ServeHTTP

func (f *Firewall) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Firewall) SetDraining

func (f *Firewall) SetDraining(v bool)

func (*Firewall) SetEvaluator

func (f *Firewall) SetEvaluator(evaluate func(context.Context, *policy.Compiled, policy.Event) (policy.Decision, error)) error

SetEvaluator installs a bootstrap-only hook. The hook must preserve the supplied revision and keep broker delivery errors separate from policy evaluation errors. It receives every native event, including message metadata and trailers. An enforcing deny keeps its status even if the hook also returns an error.

func (*Firewall) SetPolicy

func (f *Firewall) SetPolicy(p *policy.Compiled)

func (*Firewall) SetReadinessCheck

func (f *Firewall) SetReadinessCheck(check func() bool) error

SetReadinessCheck installs one bootstrap-only cached dependency check. The callback must be concurrency-safe and must not perform network health probes. It is ANDed with policy availability, draining and lifetime state.

func (*Firewall) TLSConfig

func (f *Firewall) TLSConfig() *tls.Config

TLSConfig snapshots listener identity and client trust together at each handshake.

func (*Firewall) TLSConfigForProtocols

func (f *Firewall) TLSConfigForProtocols(protocols ...string) *tls.Config

TLSConfigForProtocols preserves the listener's ALPN contract across identity reloads.

func (*Firewall) WriteAudit

func (f *Firewall) WriteAudit(ctx context.Context, w io.Writer) error

WriteAudit runs separately from decisions. The caller owns cancellation and writer lifetime. Pass os.Stdout for JSON-line audit output; a blocked writer cannot block request processing.

type Options

type Options struct {
	RuntimeRouteID string
	AllowEffects   bool
	OwnRoutePolicy bool
}

Options are trusted process bootstrap admission, never runtime configuration.

type RouteConfig

type RouteConfig struct {
	DescriptorPath      string      `json:"descriptorPath,omitempty" yaml:"descriptorPath,omitempty"`
	DescriptorSHA256    string      `json:"descriptorSHA256,omitempty" yaml:"descriptorSHA256,omitempty"`
	APIValidateResponse bool        `json:"apiValidateResponse,omitempty" yaml:"apiValidateResponse,omitempty"`
	ID                  string      `json:"id" yaml:"id"`
	Priority            int         `json:"priority" yaml:"priority"`
	Hosts               []string    `json:"hosts" yaml:"hosts"`
	Methods             []string    `json:"methods" yaml:"methods"`
	PathPrefix          string      `json:"pathPrefix" yaml:"pathPrefix"`
	Upstream            string      `json:"upstream" yaml:"upstream"`
	PolicyFile          string      `json:"policyFile" yaml:"policyFile"`
	PolicyID            string      `json:"policyID" yaml:"policyID"`
	MaxBodyBytes        int64       `json:"maxBodyBytes" yaml:"maxBodyBytes"`
	MaxResponseBytes    int64       `json:"maxResponseBytes" yaml:"maxResponseBytes"`
	MaxConcurrent       int         `json:"maxConcurrent" yaml:"maxConcurrent"`
	CRSProfile          *CRSProfile `json:"crsProfile,omitempty" yaml:"crsProfile,omitempty"`
	UpstreamCA          string      `json:"upstreamCA,omitempty" yaml:"upstreamCA,omitempty"`
	UpstreamServerName  string      `json:"upstreamServerName,omitempty" yaml:"upstreamServerName,omitempty"`
	UpstreamCert        string      `json:"upstreamCert,omitempty" yaml:"upstreamCert,omitempty"`
	UpstreamKey         string      `json:"upstreamKey,omitempty" yaml:"upstreamKey,omitempty"`
}

RouteConfig is an operator bootstrap capability. PolicyFile is never supplied by a request. Higher priorities win; overlapping equal-priority matches are rejected.

type RoutePolicyTarget

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

func (*RoutePolicyTarget) ActivatePolicy

func (t *RoutePolicyTarget) ActivatePolicy(p *policy.Compiled, expectedRevision string) error

func (*RoutePolicyTarget) Policy

func (t *RoutePolicyTarget) Policy() *policy.Compiled

func (*RoutePolicyTarget) Ready

func (t *RoutePolicyTarget) Ready() bool

func (*RoutePolicyTarget) SetDraining

func (t *RoutePolicyTarget) SetDraining(v bool)

func (*RoutePolicyTarget) SetPolicy

func (t *RoutePolicyTarget) SetPolicy(p *policy.Compiled)

SetPolicy is reserved for an owning policycontrol service after ValidatePolicy.

func (*RoutePolicyTarget) SetReadinessCheck

func (t *RoutePolicyTarget) SetReadinessCheck(check func() bool) error

func (*RoutePolicyTarget) ValidatePolicy

func (t *RoutePolicyTarget) ValidatePolicy(p *policy.Compiled) error

Jump to

Keyboard shortcuts

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