-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathmetrics.rs
More file actions
373 lines (329 loc) · 12.6 KB
/
Copy pathmetrics.rs
File metadata and controls
373 lines (329 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use std::{borrow::Cow, collections::HashMap, time::Duration};
use crate::telemetry;
#[derive(Default, Debug)]
pub struct CollectingMetricsSubmitter {
meta: HashMap<Cow<'static, str>, String>,
metrics: HashMap<Cow<'static, str>, f64>,
}
impl CollectingMetricsSubmitter {
pub fn take_metrics(&mut self) -> HashMap<Cow<'static, str>, f64> {
std::mem::take(&mut self.metrics)
}
pub fn take_meta(&mut self) -> HashMap<Cow<'static, str>, String> {
std::mem::take(&mut self.meta)
}
}
impl telemetry::SpanMetricsSubmitter for CollectingMetricsSubmitter {
fn submit_metric(&mut self, key: telemetry::SpanMetricName, value: f64) {
self.metrics.insert(key.0.into(), value);
}
fn submit_meta(&mut self, key: telemetry::SpanMetaName, value: String) {
self.meta.insert(key.0.into(), value);
}
fn submit_meta_dyn_key(&mut self, key: String, value: String) {
self.meta.insert(key.into(), value);
}
fn submit_metric_dyn_key(&mut self, key: String, value: f64) {
self.metrics.insert(key.into(), value);
}
}
#[derive(Default, Debug)]
pub struct WafMetrics {
// Ruleset version (context for tag generation)
rules_version: Option<String>,
/// The error code of the last non-RASP evaluation that hit an error, if any
waf_error_code: Option<i32>,
/// The RASP evaluation that hit an error, if any. RASP errors are reported
/// separately from non-RASP ones (appsec.rasp.error vs appsec.waf.error)
rasp_error: Option<RaspError>,
/// Total WAF execution time in milliseconds (non-RASP calls only)
waf_duration: Duration,
/// Whether the WAF hit a timeout during non-RASP calls
waf_hit_timeout: bool,
/// Total RASP execution time in milliseconds
rasp_duration: Duration,
/// Count of RASP rule evaluations
rasp_rule_evals: u32,
/// Count of RASP timeouts
rasp_timeouts: u32,
/// Per-(rule_type, rule_variant) RASP metrics for telemetry
rasp_per_rule: HashMap<(String, String), RaspRuleMetrics>,
/// Whether the WAF triggered any rules
had_triggers: bool,
/// Whether the request was blocked
request_blocked: bool,
/// Whether the input was truncated by the extension.
/// Used as a tag on waf.requests. The separate appsec.waf.input_truncated
/// metric was deprecated by RFC-1089, as was appsec.waf.truncated_value_size.
/// Neither is implemented.
input_truncated: bool,
/// Whether the trace was rate-limited by the appsec event rate limiter
/// (i.e. the limiter prevented force-keeping a trace that would otherwise
/// have been force-kept).
rate_limited: bool,
}
#[derive(Debug)]
struct RaspError {
/// The numeric error returned by ddwaf_run, or -127 if from the bindings.
code: i32,
rule_type: String,
rule_variant: String,
}
#[derive(Default, Debug, Clone)]
pub struct RaspRuleMetrics {
/// Total number of RASP rule evaluations, whether they matched or not
pub evals: u32,
/// Matches whose RASP rule did not request a block (on_match had no block action,
/// or the rule was monitor-only). Emitted as rasp.rule.match with `block:irrelevant`.
pub matches_irrelevant: u32,
/// Matches whose RASP rule requested a block. PHP cannot fail to block once it
/// decides to, so every such match counts as `block:success` (no `block:failure`).
pub matches_blocked: u32,
/// Total number of RASP rule timeouts
pub timeouts: u32,
/// Duration of each individual libddwaf call, for the rasp.rule.duration
/// distribution. Unlike rasp.duration, which is the per-request cumulative
/// sum, this metric records one observation per call.
pub durations: Vec<Duration>,
}
impl WafMetrics {
pub fn new(rules_version: Option<String>) -> Self {
Self {
rules_version,
waf_error_code: None,
rasp_error: None,
waf_duration: Duration::ZERO,
waf_hit_timeout: false,
rasp_duration: Duration::ZERO,
rasp_rule_evals: 0,
rasp_timeouts: 0,
rasp_per_rule: HashMap::new(),
had_triggers: false,
request_blocked: false,
input_truncated: false,
rate_limited: false,
}
}
pub fn set_input_truncated(&mut self, input_truncated: bool) {
self.input_truncated = input_truncated;
}
pub fn set_rate_limited(&mut self, rate_limited: bool) {
self.rate_limited = rate_limited;
}
pub fn record_non_rasp_error_eval(&mut self, error_code: i32) {
self.waf_error_code = Some(error_code);
}
pub fn record_rasp_error_eval(&mut self, error_code: i32, rule_type: &str, rule_variant: &str) {
self.rasp_error = Some(RaspError {
code: error_code,
rule_type: rule_type.to_string(),
rule_variant: rule_variant.to_string(),
});
// questionable but we still count towards these metrics even with error
self.rasp_rule_evals += 1;
self.rasp_per_rule
.entry((rule_type.to_string(), rule_variant.to_string()))
.or_default()
.evals += 1;
}
pub fn record_non_rasp_eval(&mut self, run_output: &libddwaf::RunOutput) {
self.waf_duration += run_output.duration();
if run_output.timeout() {
self.waf_hit_timeout = true;
}
if run_output.has_events() {
self.had_triggers = true;
}
if run_output.is_blocking() {
self.request_blocked = true;
}
}
pub fn record_rasp_eval(
&mut self,
rule_type: &str,
rule_variant: &str,
run_output: &libddwaf::RunOutput,
) {
self.rasp_duration += run_output.duration();
self.rasp_rule_evals += 1;
if run_output.timeout() {
self.rasp_timeouts += 1;
}
let entry = self
.rasp_per_rule
.entry((rule_type.to_string(), rule_variant.to_string()))
.or_default();
entry.evals += 1;
entry.durations.push(run_output.duration());
if run_output.has_events() {
if run_output.is_blocking() {
entry.matches_blocked += 1;
} else {
entry.matches_irrelevant += 1;
}
}
if run_output.timeout() {
entry.timeouts += 1;
}
if run_output.is_blocking() {
self.request_blocked = true;
}
}
}
trait RunOutputExt {
fn has_events(&self) -> bool;
fn is_blocking(&self) -> bool;
}
impl RunOutputExt for libddwaf::RunOutput {
fn has_events(&self) -> bool {
self.events()
.is_some_and(|events| !events.value().is_empty())
}
fn is_blocking(&self) -> bool {
self.actions().is_some_and(|actions| {
actions.value().iter().any(|action| {
matches!(
action.key().to_str(),
Some("block_request") | Some("redirect_request")
)
})
})
}
}
impl telemetry::TelemetryMetricsGenerator for WafMetrics {
fn generate_telemetry_metrics(
&'_ self,
submitter: &mut dyn telemetry::TelemetryMetricSubmitter,
) {
let base_tags = {
let mut tags = telemetry::TelemetryTags::new();
tags.add("waf_version", crate::service::Service::waf_version());
tags.add(
"event_rules_version",
self.rules_version.as_deref().unwrap_or("unknown"),
);
tags
};
// waf.requests metrics
// RFC-1012: all boolean tags must be emitted regardless of value.
let mut tags = base_tags.clone();
tags.add("rule_triggered", bool_tag(self.had_triggers));
// The PHP layer is assumed to always succeed at blocking.
// Therefore request_blocked == "WAF requested a block" == "block succeeded".
if self.request_blocked {
tags.add("block_failure", "false");
}
// request_excluded is not tracked: libddwaf applies exclusion filters internally and
// does not expose whether a request was excluded in RunOutput.
tags.add("request_blocked", bool_tag(self.request_blocked));
tags.add("waf_error", bool_tag(self.waf_error_code.is_some()));
tags.add("waf_timeout", bool_tag(self.waf_hit_timeout));
tags.add("input_truncated", bool_tag(self.input_truncated));
tags.add("rate_limited", bool_tag(self.rate_limited));
submitter.submit_metric(telemetry::WAF_REQUESTS, 1.0, tags);
// waf.error
if let Some(error_code) = self.waf_error_code {
let mut err_tags = base_tags.clone();
err_tags.add("waf_error", error_code.to_string());
submitter.submit_metric(telemetry::WAF_ERROR, 1.0, err_tags);
}
// waf.duration distribution: one observation per request, value in microseconds
if !self.waf_duration.is_zero() {
submitter.submit_metric(
telemetry::WAF_DURATION_DIST,
self.waf_duration.as_micros() as f64,
base_tags.clone(),
);
}
// rasp.duration distribution: cumulative internal libddwaf runtime per request, in microseconds
if !self.rasp_duration.is_zero() {
submitter.submit_metric(
telemetry::RASP_DURATION_DIST,
self.rasp_duration.as_micros() as f64,
base_tags.clone(),
);
}
// Rasp rule metrics
for ((rule_type, rule_variant), metrics) in &self.rasp_per_rule {
let mut tags = base_tags.clone();
tags.add("rule_type", rule_type);
if !rule_variant.is_empty() {
tags.add("rule_variant", rule_variant);
}
if metrics.evals > 0 {
submitter.submit_metric(
telemetry::RASP_RULE_EVAL,
metrics.evals as f64,
tags.clone(),
);
}
if metrics.matches_irrelevant > 0 {
let mut match_tags = tags.clone();
match_tags.add("block", "irrelevant");
submitter.submit_metric(
telemetry::RASP_RULE_MATCH,
metrics.matches_irrelevant as f64,
match_tags,
);
}
if metrics.matches_blocked > 0 {
let mut match_tags = tags.clone();
match_tags.add("block", "success");
submitter.submit_metric(
telemetry::RASP_RULE_MATCH,
metrics.matches_blocked as f64,
match_tags,
);
}
// rasp.rule.duration distribution: one observation per libddwaf call, in microseconds
for duration in &metrics.durations {
submitter.submit_metric(
telemetry::RASP_RULE_DURATION_DIST,
duration.as_micros() as f64,
tags.clone(),
);
}
// tests expect this to always be sent, even if 0
submitter.submit_metric(telemetry::RASP_TIMEOUT, metrics.timeouts as f64, tags);
}
// rasp.error
if let Some(ref err) = self.rasp_error {
let mut err_tags = base_tags.clone();
err_tags.add("rule_type", &err.rule_type);
if !err.rule_variant.is_empty() {
err_tags.add("rule_variant", &err.rule_variant);
}
err_tags.add("waf_error", err.code.to_string());
submitter.submit_metric(telemetry::RASP_ERROR, 1.0, err_tags);
}
}
}
impl telemetry::SpanMetricsGenerator for WafMetrics {
fn generate_span_metrics(&'_ self, submitter: &mut dyn telemetry::SpanMetricsSubmitter) {
if !self.waf_duration.is_zero() {
submitter.submit_metric(
telemetry::WAF_DURATION,
self.waf_duration.as_micros() as f64,
);
}
if !self.rasp_duration.is_zero() {
submitter.submit_metric(
telemetry::RAST_DURATION,
self.rasp_duration.as_micros() as f64,
);
}
if self.rasp_rule_evals > 0 {
submitter.submit_metric(telemetry::RAST_RULE_EVALS, self.rasp_rule_evals as f64);
}
if self.rasp_timeouts > 0 {
submitter.submit_metric(telemetry::RAST_TIMEOUTS, self.rasp_timeouts as f64);
}
}
}
fn bool_tag(value: bool) -> &'static str {
if value {
"true"
} else {
"false"
}
}