Documentation
¶
Overview ¶
Package adapt holds the sensor's adaptive controllers and the one table of their bounds (RFC-074 in openctemio/openctem api/docs/rfcs, RFC-074-adaptive-sensor-control.md).
A controller moves a value from a measured signal, inside a floor and a ceiling. The ceiling is always the lowest of the limits a human or a policy set: a controller may go below it, never above. Every number a controller uses is in this file; code elsewhere refers to the table, never to a literal.
Stability: Experimental (docs/STABILITY.md).
Index ¶
- Constants
- Variables
- func Ceiling(limits ...float64) float64
- func FailureReason(err error) string
- func ParseRetryAfter(v string, now time.Time) time.Duration
- type Change
- type Event
- type Gap
- type HostRate
- func (c *HostRate) Acquire(ctx context.Context, host string) error
- func (c *HostRate) Ceiling() float64
- func (c *HostRate) Gaps() ([]Gap, int)
- func (c *HostRate) MarkGap(host, reason, detail string)
- func (c *HostRate) Rate(host string) float64
- func (c *HostRate) Report(host string, e Event)
- func (c *HostRate) ReportDial(host string, port int, err error)
- func (c *HostRate) ReportHTTP(host string, status int, retryAfter string)
- func (c *HostRate) ReportResponse(host string, status int, retryAfter string, v edgeprotect.Verdict)
- func (c *HostRate) Share(s *SensorRate, tenant string)
- func (c *HostRate) Summary() Summary
- type SensorRate
- type SharedRateBounds
- type Signal
- type SourceChange
- type SourcePaceBounds
- type SourcePacer
- type SourceSignal
- type Summary
- type TargetRateBounds
Constants ¶
const ( ReasonTimeout = "timeout" ReasonReset = "reset" ReasonRefused = "refused" ReasonTLS = "tls_handshake" ReasonHTTP429 = "http_429" ReasonHTTP503 = "http_503" ReasonBlocked = "blocked" ReasonCleanRun = "clean_window" ReasonSlowStart = "slow_start" ReasonOpened = "breaker_open" ReasonHalfOpen = "breaker_half_open" ReasonClosed = "breaker_closed" ReasonGaveUp = "breaker_gave_up" ReasonRetryAfter = "retry_after" )
Reasons of an Event and of a Change.
const ( // GapBreakerOpen: the host stopped answering and the breaker refused // connections to it (or gave it up). GapBreakerOpen = "breaker_open" // GapRateFloor: the host kept pushing back at the lowest rate, or asked // to wait longer than a connection can be held. GapRateFloor = "rate_floor" // GapBlocked: the host answered with a block (a run of 403s). GapBlocked = "blocked" // connection toward the host (every endpoint down or refusing our // credentials, or the proxy's rules refused the destination), so part // of the host was never scanned. It says nothing about the host. GapProxyUnavailable = "proxy_unavailable" )
Gap reasons: why a host's coverage is incomplete.
const ( // GapCauseHTTPReset: the host accepts the connection (and completes the // TLS handshake) but resets or closes it on every HTTP request. The // host is up; it refuses the scanner's requests (it may block the // scanner's address, or its backend is down). GapCauseHTTPReset = "http_reset" // GapCauseReset: the host accepts connections, then resets them; which // layer (the TLS handshake or the HTTP request) was not seen. GapCauseReset = "reset" // GapCauseTLSFailed: the host accepts the connection but the TLS // handshake fails. GapCauseTLSFailed = "tls_failed" // GapCauseRefused: the host refuses the connection (the port is closed). GapCauseRefused = "refused" // GapCauseNoAnswer: no answer at all (filtered, down, or no path). GapCauseNoAnswer = "no_answer" // GapCauseAnswered: the host answered the recheck; it failed the tool's // requests only for a while. GapCauseAnswered = "answered" )
Gap causes: what a recheck of a host the breaker gave up found.
const ( GapCertExpired = "expired" GapCertNotYetValid = "not_yet_valid" GapCertNameMismatch = "name_mismatch" GapCertSelfSigned = "self_signed" )
Certificate problems a recheck saw (Gap.Cert).
const ( ReasonSlow = "slow_answers" ReasonBusy = "busy" ReasonFailed = "failed" )
Reasons of a SourceChange (with ReasonCleanRun and ReasonRetryAfter).
Variables ¶
ErrHostUnavailable is the error of a connection the breaker refused.
CooldownBase: 15 * time.Minute, CooldownMax: 6 * time.Hour, ShareIdle: 30 * time.Second, HostIdle: 10 * time.Minute, MaxHosts: 65536, MaxTenantsPerHost: 64, }
SharedRate is the table of sensor-wide bounds. Why each value:
- CooldownBase 15m doubling to CooldownMax 6h: an edge that blocked the scanner's address keeps blocking it for a while; asking again at once only deepens the block. Six hours bounds what a hostile target can withhold from a tenant's scans (each cooldown is reported as a coverage gap with its reason, never as "no findings").
- ShareIdle 30s: a few windows; a tenant whose tool pauses between phases keeps its share.
- HostIdle 10m: long enough to carry what one task learned to the next one on the same host.
- MaxHosts 65536, MaxTenantsPerHost 64: the per-task MaxHosts, and more tenants on one target at once than a shared sensor runs.
var SourcePace = SourcePaceBounds{ Floor: 0.2, DefaultCeiling: 5, StartFraction: 0.5, Window: 10 * time.Second, MinSamples: 3, IncreaseFraction: 0.1, DecreaseFactor: 0.5, LatencyFactor: 3, LatencyFloor: 250 * time.Millisecond, BaselineDrift: 0.1, MaxSamples: 64, RetryAfterMax: 5 * time.Minute, }
SourcePace is the table of source-pace bounds. Why each value:
- Floor 0.2/s: one request every five seconds still finishes a paged inventory of ten thousand objects in minutes, and leaves a struggling server essentially alone.
- DefaultCeiling 5/s: what an operator would accept from one read-only account against a production vCenter or domain controller.
- StartFraction 0.5: a new source is read at half the ceiling until its answers show it is healthy.
- Window 10s, MinSamples 3: at a few requests per second a window holds enough answers for a median; one slow answer does not move the rate.
- IncreaseFraction 0.1, DecreaseFactor 0.5: additive increase, halving on push-back (429, 503, a busy fault, a timeout, a reset, or the latency signal), once per window.
- LatencyFactor 3, LatencyFloor 250ms: a server that answers three times slower than its own normal is under load (a vpxd or DC at full CPU slows down before it errors); answers under 250ms are fast whatever their ratio.
- BaselineDrift 0.1: about twenty windows (a few minutes) for a source that stays slower to become the new normal.
- RetryAfterMax 5m: the same cap HostRate and the control client honor.
var TargetRate = TargetRateBounds{ Floor: 1, DefaultCeiling: 100, StartFraction: 0.25, Window: 2 * time.Second, IncreaseFraction: 0.10, DecreaseFactor: 0.5, BreakerFailures: 5, BreakerOpen: 15 * time.Second, BreakerOpenMax: 2 * time.Minute, BreakerJitter: 0.2, BreakerMaxTrips: 3, ProbeTimeout: 30 * time.Second, RetryAfterMax: 5 * time.Minute, HoldMax: 10 * time.Second, FloorStrikes: 3, BlockRun: 20, MaxHosts: 65536, MaxOpenPorts: 64, MaxGaps: 100, MaxChanges: 20, ToolHostErrors: 30, }
TargetRate is the table of target-rate bounds. Why each value:
- Floor 1/s: the slowest pace still useful for a scan in a job's time; slower than that the result is reported as a gap, not stretched.
- DefaultCeiling 100/s: the forwarder's default before this controller.
- StartFraction 0.25: a new host is probed at a quarter of the ceiling; doubling per clean window reaches the ceiling in two windows.
- Window 2s: several round trips to a distant host, and at least two requests at the floor, so a window has evidence before it moves.
- IncreaseFraction 0.10, DecreaseFactor 0.5: additive increase of a tenth of the ceiling per clean window, halving on push-back; one decrease per window so the replies to a burst already in flight do not collapse the rate.
- BreakerFailures 5, BreakerOpen 15s doubling to 2m, ±20 % jitter, 3 trips: a host that stops answering is left alone for a while and probed once; after three trips (about 1.5 minutes of silence) it is a coverage gap for the task.
- RetryAfterMax 5m: the same cap the control client honors.
- HoldMax 10s: within a tool's usual connect timeout; longer waits are refused instead of hanging the tool.
- FloorStrikes 3, BlockRun 20: enough repetitions that one refusal or a handful of forbidden paths do not count as a block.
- ToolHostErrors 30: a tool's own breaker counts every failed request of every concurrent check (not consecutive failures), so it needs a larger budget than BreakerFailures × BreakerMaxTrips (15); 30 lets a few slow checks fail without dropping a live host.
Functions ¶
func Ceiling ¶
Ceiling is the lowest of the positive limits (a scan's rate_limit, a scan window's, a program rule's, the local policy's rate.max_rps, the sensor's own setting): the rate a controller never exceeds. Limits of zero or less are "not set"; with none set it is TargetRate.DefaultCeiling.
func FailureReason ¶
FailureReason classifies a network error toward a target as a failure signal (ReasonTimeout, ReasonRefused, ReasonReset), or "" when it says nothing about the target (the task was canceled, or the error is not a network one).
Types ¶
type Change ¶
type Change struct {
Host string `json:"host"`
From float64 `json:"from"`
To float64 `json:"to"`
Reason string `json:"reason"`
}
Change is one move of a host's rate or breaker.
type Event ¶
type Event struct {
Signal Signal
Reason string
RetryAfter time.Duration
// Edge is the edge protection verdict of the answer (zero: none was
// made). On a Forbidden event whose verdict stops the request (a
// vendor challenge or block page) the host is a block from its first
// answer: the vendor marker is evidence a bare 403 is not.
Edge edgeprotect.Verdict
}
Event is one signal about a host.
type Gap ¶
type Gap struct {
Host string `json:"host"`
Reason string `json:"reason"`
Detail string `json:"detail,omitempty"`
// Edge and Vendor say that an edge protection (a WAF or CDN) stopped the
// task: Edge is "challenged" or "blocked" (edgeprotect.State), Vendor the
// vendor. Additive: older receivers ignore them and still see Reason
// "blocked".
Edge string `json:"edge,omitempty"`
Vendor string `json:"vendor,omitempty"`
// Cause and Cert say what a recheck of a breaker_open host found
// (pkg/tlsprobe): Cause is one of the GapCause values, Cert a problem of
// the certificate the host served (GapCert values, "" when it is fine or
// none was seen). Additive: older receivers ignore them and still see
// Reason "breaker_open".
Cause string `json:"cause,omitempty"`
Cert string `json:"cert,omitempty"`
}
Gap is one host whose coverage is incomplete, and why.
type HostRate ¶
type HostRate struct {
// OnChange, when set, receives every rate or breaker change (called
// without the controller's lock held).
OnChange func(Change)
// contains filtered or unexported fields
}
HostRate is one task's per-host rate controller: additive increase, multiplicative decrease (AIMD) on each destination host, with a breaker per host. Its state belongs to one task: a forwarder creates it and drops it with the task. A task that joins the sensor-wide SensorRate (Share) also shares the host's rate with the sensor's other tasks, and the Retry-After and edge-block cooldowns with its own tenant's tasks only: nothing a host taught one tenant's task reaches another tenant's.
Signals: a connection or an answer is health; 429 and 503 (with their Retry-After) are congestion; a timeout, a refused connection on a port that answered before, a failed TLS handshake and a reset from a host that never accepted a connection are failures; a reset on a connection the host accepted refuses that request (resetRefusal); a run of 403 answers after other answers, or of such resets, is a block. The rate never goes above the ceiling the caller gives (Ceiling of every limit) and never below TargetRate.Floor (or the ceiling, when that is lower).
A host the controller cannot cover (the breaker refused connections to it, it kept pushing back at the floor, or it blocked the scan) is a coverage gap: the task completes and reports it (Gaps), it is not read as "no findings".
func NewHostRate ¶
NewHostRate returns the controller of one task with the given ceiling (Ceiling of every limit that applies; zero or less: the default).
func (*HostRate) Acquire ¶
Acquire waits until a connection (or a request) to host may start, bounded by ctx. It returns ErrHostUnavailable when the host's breaker is open or the host asked to wait longer than TargetRate.HoldMax.
func (*HostRate) Gaps ¶
Gaps are the hosts whose coverage is incomplete (at most TargetRate.MaxGaps) and how many there are in all.
func (*HostRate) MarkGap ¶ added in v0.38.0
MarkGap records that part of host's coverage is missing for a reason the controller did not see itself (GapProxyUnavailable: the path failed, not the host). The host keeps its strongest gap; its rate and breaker do not move.
func (*HostRate) ReportDial ¶
ReportDial feeds the outcome of a connection attempt to host:port. A failure counts only on a port that accepted a connection before in this task: a closed or filtered port of a host is not push-back (a port scan meets thousands of them). Cancellation is not a signal.
func (*HostRate) ReportHTTP ¶
ReportHTTP feeds one HTTP answer of host (status and its Retry-After header value).
func (*HostRate) ReportResponse ¶ added in v0.38.0
func (c *HostRate) ReportResponse(host string, status int, retryAfter string, v edgeprotect.Verdict)
ReportResponse is ReportHTTP with the edge verdict of the answer: a challenge or block page of a vendor's edge (verdict.State.Stops) is a block whatever its status (a challenge is sometimes a 503), and from the first answer; a vendor's rate-limit page is push-back whatever its status. Without such a verdict it behaves as ReportHTTP.
func (*HostRate) Share ¶ added in v0.46.0
func (c *HostRate) Share(s *SensorRate, tenant string)
Share makes the task share target state with every other task of the sensor (SensorRate): the host's rate (fair share per tenant), the tenant's Retry-After and cooldowns. tenant is the organization of the task's job ("" on a sensor of one organization). Call it before the first Acquire.
type SensorRate ¶ added in v0.46.0
type SensorRate struct {
// contains filtered or unexported fields
}
SensorRate is what every task of one sensor shares about a target host (one per process: Process). A task's HostRate joins it with Share; the task then still paces itself (its ceiling, slow start, breaker and gaps are its own) and, on top of that:
- takes its connections from the host's sensor-wide rate: all tasks toward one host share one rate, so two tools scanning the same host do not add up. The rate is AIMD like a task's (halved on 429 and 503 and on a block, raised on clean windows), never above the highest ceiling of the tasks using the host, never below TargetRate.Floor. Inside a host the rate is split evenly between the tenants asking for it (fair share on a shared sensor): one tenant's scans cannot take another's share of a target;
- honors a Retry-After any task of the same tenant got from the host;
- leaves a host alone after an edge block (a vendor block or challenge page, or a run of 403 answers): SharedRate.CooldownBase, doubling on each further block up to CooldownMax. During the cooldown every connection of the tenant toward the host is refused before it is dialed (so no other proxy endpoint is ever tried for it) and the host is a coverage gap with the edge's reason, never "no findings".
Retry-After and cooldowns are kept per (tenant, host): what a target told one tenant's scans never reaches another tenant's task. Only the pace of the host is shared between tenants (fair share).
The zero value is not usable; create it with NewSensorRate.
func NewSensorRate ¶ added in v0.46.0
func NewSensorRate() *SensorRate
NewSensorRate returns an empty sensor-wide state.
func Process ¶ added in v0.46.0
func Process() *SensorRate
Process is the process's SensorRate: the one every task forwarder of the sensor shares.
type SharedRateBounds ¶ added in v0.46.0
type SharedRateBounds struct {
// CooldownBase is how long a target is left alone after the first
// edge block (a WAF or CDN block or challenge page, or a run of 403
// answers); each further block of the same target doubles it, up to
// CooldownMax.
// counts for the host's fair share.
ShareIdle time.Duration
// the cooldowns and Retry-After it set, once they passed).
HostIdle time.Duration
// MaxHosts bounds the hosts the sensor tracks; MaxTenantsPerHost the
// tenants sharing one host. A task whose host or tenant does not fit
// paces itself alone (as it did before the sensor-wide state): state is
// never shared between hosts or tenants to make room.
}
SharedRateBounds bound the sensor-wide state of SensorRate: what every task of the sensor shares about a target host.
type Signal ¶
type Signal int
Signal is what one connection or answer said about its host.
const ( // Connected: a connection was established. Connected Signal = iota + 1 // Answered: the host answered (an HTTP response other than 403, 429 // or 503, or a tunnel that ended cleanly after the host sent data). Answered // Congested: 429 or 503 (Event.RetryAfter set when the host sent one). Congested // Forbidden: a 403 answer. Forbidden // Failed: a reset, a timeout, a refused connection on a port that // answered before, or a failed TLS handshake (Event.Reason says which). Failed )
type SourceChange ¶ added in v0.46.0
type SourceChange struct {
From, To float64
// Reason is ReasonCleanRun, ReasonSlow, ReasonBusy, ReasonFailed or
// ReasonRetryAfter.
Reason string
}
SourceChange is one move of a source's rate.
type SourcePaceBounds ¶ added in v0.46.0
type SourcePaceBounds struct {
// Floor is the slowest pace. A source still slow or busy at the floor
// keeps being read at the floor; the caller's breaker and run budget
// decide when to stop.
Floor float64
// DefaultCeiling is the ceiling when no limit was given.
DefaultCeiling float64
// StartFraction of the ceiling is where a new source starts.
StartFraction float64
// Window is how often the rate is re-evaluated, MinSamples the answers
// a window needs before its latency counts.
Window time.Duration
MinSamples int
// IncreaseFraction of the ceiling is added per clean window;
// DecreaseFactor multiplies the rate on push-back (at most once per
// window).
IncreaseFraction float64
DecreaseFactor float64
// LatencyFactor: a window whose median latency is above this multiple
// of the source's baseline (and above LatencyFloor) is push-back.
LatencyFactor float64
LatencyFloor time.Duration
// BaselineDrift is the fraction by which the baseline moves toward each
// window's median when that median is higher: a source that became
// slower for good becomes the new normal instead of being held at the
// floor forever. A lower median replaces the baseline at once.
BaselineDrift float64
// MaxSamples bounds the latencies one window keeps.
MaxSamples int
// RetryAfterMax caps a source's Retry-After.
RetryAfterMax time.Duration
}
SourcePaceBounds bound the request rate toward a system of record a collector or importer reads (an inventory API such as vCenter, a directory, a monitoring server): SourcePacer.
type SourcePacer ¶ added in v0.46.0
type SourcePacer struct {
// OnChange, when set, receives every rate change (called without the
// pacer's lock held).
OnChange func(SourceChange)
// contains filtered or unexported fields
}
SourcePacer paces the requests to one system of record a collector or an importer reads: a production inventory API (vCenter), a directory (a domain controller), a monitoring or log server. Unlike a scan target, such a source is shared infrastructure the organization depends on, so the pacer slows down on the first sign of load, not only on errors:
- every request waits for the pacer's token bucket (Wait);
- each answer is reported with its latency (Observe): 429, 503 and busy answers (with their Retry-After) and failures (timeouts, resets, 5xx) halve the rate at once, at most once per window;
- once per window the median latency is compared with the source's baseline (its fastest normal): a median above SourcePace.LatencyFactor times the baseline halves the rate, a clean window adds a tenth of the ceiling (additive increase, multiplicative decrease);
- a Retry-After holds every request until it passes (capped at SourcePace.RetryAfterMax).
The rate never goes above the ceiling the caller gives (the lowest of the limits a human or a policy set; Ceiling) and never below SourcePace.Floor (or the ceiling, when that is lower). One pacer serves every caller that reads the same source: it is safe for concurrent use.
func NewSourcePacer ¶ added in v0.46.0
func NewSourcePacer(ceiling float64) *SourcePacer
NewSourcePacer returns the pacer of one source with the given ceiling (requests per second; 0 or less: SourcePace.DefaultCeiling).
func (*SourcePacer) Ceiling ¶ added in v0.46.0
func (p *SourcePacer) Ceiling() float64
Ceiling is the rate the pacer never exceeds.
func (*SourcePacer) Observe ¶ added in v0.46.0
func (p *SourcePacer) Observe(sig SourceSignal, latency, retryAfter time.Duration)
Observe reports one answer: its signal, how long it took, and the Retry-After the source sent (0: none).
func (*SourcePacer) Rate ¶ added in v0.46.0
func (p *SourcePacer) Rate() float64
Rate is the current rate.
type SourceSignal ¶ added in v0.46.0
type SourceSignal int
SourceSignal is what one answer said about the source.
const ( // SourceAnswered: the source answered (an application error such as // "no permission" included: it says nothing about load). SourceAnswered SourceSignal = iota + 1 // SourceBusy: 429, 503 or a busy fault; RetryAfter when the source // sent one. SourceBusy // SourceFailed: a timeout, a reset or a server error. SourceFailed )
type Summary ¶
type Summary struct {
Ceiling float64 `json:"ceiling"`
Floor float64 `json:"floor"`
Start float64 `json:"start"`
// Min is the lowest rate any host reached; Final the lowest rate a
// host ended at.
Min float64 `json:"min"`
Final float64 `json:"final"`
Hosts int `json:"hosts"`
// Throttled hosts were slowed at least once; Unreachable hosts were
// given up by their breaker.
Throttled int `json:"hosts_throttled"`
Unreachable int `json:"hosts_unreachable"`
// Gaps lists at most TargetRate.MaxGaps hosts; GapsTotal counts all.
Gaps []Gap `json:"gaps,omitempty"`
GapsTotal int `json:"gaps_total,omitempty"`
}
Summary is a task's target-rate outcome, for its result and its log.
type TargetRateBounds ¶
type TargetRateBounds struct {
// Floor is the lowest rate the controller paces a host at. A host that
// still pushes back at the floor is reported as a coverage gap
// (GapRateFloor) instead of being slowed further.
Floor float64
// DefaultCeiling is the ceiling when no limit was given at all (the
// forwarder's historical default; never "unlimited").
DefaultCeiling float64
// StartFraction of the ceiling is where a host starts (slow start).
StartFraction float64
// Window is how often a host's rate is re-evaluated: a window with
// answers and no push-back raises the rate.
Window time.Duration
// IncreaseFraction of the ceiling is added per clean window once slow
// start ended (additive increase).
IncreaseFraction float64
// DecreaseFactor multiplies the rate on push-back (multiplicative
// decrease), at most once per window.
DecreaseFactor float64
// BreakerFailures consecutive failures open a host's breaker.
BreakerFailures int
// BreakerOpen is how long a breaker stays open the first time; it
// doubles on each further trip up to BreakerOpenMax.
BreakerOpen time.Duration
BreakerOpenMax time.Duration
// BreakerJitter spreads the open time by ± this fraction.
BreakerJitter float64
// BreakerMaxTrips trips give a host up for the rest of the task.
BreakerMaxTrips int
// ProbeTimeout is how long a half-open probe may stay unanswered before
// another one is allowed.
ProbeTimeout time.Duration
// RetryAfterMax caps a target's Retry-After.
RetryAfterMax time.Duration
// HoldMax is the longest a connection is held to honor a Retry-After;
// a longer one refuses connections to the host until it passes.
HoldMax time.Duration
// FloorStrikes push-backs while at the floor make a host a coverage gap
// (GapRateFloor).
FloorStrikes int
// BlockRun consecutive 403 answers, from a host that answered otherwise
// before, read as a block.
BlockRun int
// MaxHosts bounds the hosts one task tracks; further hosts share one
// conservative state.
MaxHosts int
// MaxOpenPorts bounds the reachable ports remembered per host.
MaxOpenPorts int
// MaxGaps bounds the coverage gaps one result lists (the total is
// still counted).
MaxGaps int
// MaxChanges bounds the rate changes one task logs.
MaxChanges int
// ToolHostErrors is the per-host error budget handed to a tool that
// keeps its own host breaker (nuclei -max-host-error): errors on one
// host, over all its requests, before the tool skips the host.
ToolHostErrors int
}
TargetRateBounds bound the per-host request rate toward scan targets (HostRate). Rates are requests (connections, and requests on a connection the forwarder reads) per second.