-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
974 lines (880 loc) · 35.7 KB
/
Copy pathlib.rs
File metadata and controls
974 lines (880 loc) · 35.7 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
//! Zentinel ZentinelSec Agent Library
//!
//! A pure Rust ModSecurity-compatible WAF agent for Zentinel proxy.
//! Provides full OWASP Core Rule Set (CRS) support without any C dependencies.
//!
//! # Example
//!
//! ```ignore
//! use zentinel_agent_zentinelsec::{ZentinelSecAgent, ZentinelSecConfig};
//! use zentinel_agent_protocol::v2::GrpcAgentServerV2;
//!
//! let config = ZentinelSecConfig {
//! rules_paths: vec!["/etc/modsecurity/crs/rules/*.conf".to_string()],
//! ..Default::default()
//! };
//! let agent = ZentinelSecAgent::new(config)?;
//! let server = GrpcAgentServerV2::new("zentinelsec", Box::new(agent));
//! server.run("0.0.0.0:50051".parse().unwrap()).await?;
//! ```
use anyhow::Result;
use base64::Engine;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};
use zentinel_agent_protocol::v2::{
AgentCapabilities, AgentFeatures, AgentHandlerV2, AgentLimits, DrainReason, HealthStatus,
MetricsReport, ShutdownReason,
};
use zentinel_agent_protocol::{
AgentResponse, AuditMetadata, EventType, HeaderOp, RequestBodyChunkEvent, RequestHeadersEvent,
ResponseBodyChunkEvent, ResponseHeadersEvent,
};
use zentinel_modsec::ModSecurity;
/// ZentinelSec configuration
#[derive(Debug, Clone)]
pub struct ZentinelSecConfig {
/// Paths to ModSecurity rule files (glob patterns supported)
pub rules_paths: Vec<String>,
/// Block mode (true) or detect-only mode (false)
pub block_mode: bool,
/// Paths to exclude from inspection
pub exclude_paths: Vec<String>,
/// Enable request body inspection
pub body_inspection_enabled: bool,
/// Maximum body size to inspect in bytes
pub max_body_size: usize,
/// Enable response body inspection
pub response_inspection_enabled: bool,
}
impl Default for ZentinelSecConfig {
fn default() -> Self {
Self {
rules_paths: vec![],
block_mode: true,
exclude_paths: vec![],
body_inspection_enabled: true,
max_body_size: 1048576, // 1MB
response_inspection_enabled: false,
}
}
}
/// JSON-serializable configuration for ZentinelSec agent
///
/// Used for parsing configuration from the proxy's agent config.
/// Field names use kebab-case to match YAML/JSON config conventions.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct ZentinelSecConfigJson {
/// Paths to ModSecurity rule files (glob patterns supported)
#[serde(default)]
pub rules_paths: Vec<String>,
/// Block mode (true) or detect-only mode (false)
#[serde(default = "default_block_mode")]
pub block_mode: bool,
/// Paths to exclude from inspection
#[serde(default)]
pub exclude_paths: Vec<String>,
/// Enable request body inspection
#[serde(default = "default_body_inspection")]
pub body_inspection_enabled: bool,
/// Maximum body size to inspect in bytes
#[serde(default = "default_max_body_size")]
pub max_body_size: usize,
/// Enable response body inspection
#[serde(default)]
pub response_inspection_enabled: bool,
}
fn default_block_mode() -> bool {
true
}
fn default_body_inspection() -> bool {
true
}
fn default_max_body_size() -> usize {
1048576 // 1MB
}
impl From<ZentinelSecConfigJson> for ZentinelSecConfig {
fn from(json: ZentinelSecConfigJson) -> Self {
Self {
rules_paths: json.rules_paths,
block_mode: json.block_mode,
exclude_paths: json.exclude_paths,
body_inspection_enabled: json.body_inspection_enabled,
max_body_size: json.max_body_size,
response_inspection_enabled: json.response_inspection_enabled,
}
}
}
/// Detection result from ZentinelSec
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Detection {
/// Rule ID that triggered the detection
pub rule_id: String,
/// Detection message
pub message: String,
/// Severity level
pub severity: Option<String>,
}
/// ZentinelSec engine wrapper
pub struct ZentinelSecEngine {
modsec: ModSecurity,
/// Agent configuration
pub config: ZentinelSecConfig,
}
impl ZentinelSecEngine {
/// Create a new ZentinelSec engine with the given configuration
pub fn new(config: ZentinelSecConfig) -> Result<Self> {
// Hand the engine `Include` directives rather than the text of each
// rule file.
//
// Splicing file contents together loses the one thing the engine needs
// to resolve `@pmFromFile`/`@ipMatchFromFile` data paths and nested
// `Include`s: which file a directive came from. Those paths are
// relative to their own rule file, so a concatenated string sent them
// to the process's working directory instead. Stock CRS references
// `scanners-user-agents.data` and many others, which meant the
// documented deployment only started if it happened to be run from
// /etc/modsecurity/crs/rules.
let mut rules_content = String::new();
// Always enable the rule engine
rules_content.push_str("SecRuleEngine On\n");
// Resolve the configured patterns ourselves so a path that cannot be
// read is reported against the pattern that produced it, and so the
// file count is available for logging.
let mut loaded_count = 0;
for path_pattern in &config.rules_paths {
// Handle glob patterns
let paths = glob::glob(path_pattern)
.map_err(|e| anyhow::anyhow!("Invalid glob pattern '{}': {}", path_pattern, e))?;
for entry in paths {
match entry {
Ok(path) => {
if path.is_file() {
// An absolute path keeps the include independent of
// the working directory; quoting keeps a path with
// spaces in one argument.
let absolute = fs::canonicalize(&path).map_err(|e| {
anyhow::anyhow!("Failed to resolve rule file {:?}: {}", path, e)
})?;
rules_content
.push_str(&format!("Include \"{}\"\n", absolute.display()));
loaded_count += 1;
debug!(path = ?absolute, "Including rule file");
}
}
Err(e) => {
warn!(error = %e, "Error reading glob entry");
}
}
}
}
// Create the ModSecurity engine
let modsec = if loaded_count == 0 {
// No rules loaded, create with just SecRuleEngine On
ModSecurity::from_string("SecRuleEngine On")
.map_err(|e| anyhow::anyhow!("Failed to initialize ZentinelSec engine: {}", e))?
} else {
ModSecurity::from_string(&rules_content)
.map_err(|e| anyhow::anyhow!("Failed to parse rules: {}", e))?
};
info!(
rules_files = loaded_count,
rule_count = modsec.rule_count(),
"ZentinelSec engine initialized"
);
Ok(Self { modsec, config })
}
/// Number of rules the engine loaded.
pub fn rule_count(&self) -> usize {
self.modsec.rule_count()
}
/// The underlying ModSecurity engine.
///
/// Exposed so tests can drive transactions through the rules this agent
/// actually loaded, rather than through a separately built engine that
/// might load them differently.
pub fn modsec(&self) -> &ModSecurity {
&self.modsec
}
/// Check if path should be excluded
pub fn is_excluded(&self, path: &str) -> bool {
self.config
.exclude_paths
.iter()
.any(|p| path.starts_with(p))
}
}
/// Body accumulator for tracking in-progress bodies
#[derive(Debug, Default)]
struct BodyAccumulator {
data: Vec<u8>,
}
/// Pending transaction for body accumulation
struct PendingTransaction {
body: BodyAccumulator,
method: String,
uri: String,
headers: HashMap<String, Vec<String>>,
#[allow(dead_code)]
client_ip: String,
}
/// ZentinelSec agent
pub struct ZentinelSecAgent {
engine: Arc<RwLock<ZentinelSecEngine>>,
pending_requests: Arc<RwLock<HashMap<String, PendingTransaction>>>,
/// Metrics tracking
requests_total: AtomicU64,
requests_blocked: AtomicU64,
requests_allowed: AtomicU64,
/// Draining state
draining: AtomicU64, // 0 = not draining, >0 = drain end timestamp ms
}
impl ZentinelSecAgent {
/// Create a new ZentinelSec agent with the given configuration
pub fn new(config: ZentinelSecConfig) -> Result<Self> {
let engine = ZentinelSecEngine::new(config)?;
Ok(Self {
engine: Arc::new(RwLock::new(engine)),
pending_requests: Arc::new(RwLock::new(HashMap::new())),
requests_total: AtomicU64::new(0),
requests_blocked: AtomicU64::new(0),
requests_allowed: AtomicU64::new(0),
draining: AtomicU64::new(0),
})
}
/// Check if the agent is currently draining
fn is_draining(&self) -> bool {
let drain_end = self.draining.load(Ordering::Relaxed);
if drain_end == 0 {
return false;
}
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
now < drain_end
}
/// Reconfigure the agent with new settings
///
/// This rebuilds the ZentinelSec engine with the new configuration.
/// In-flight requests using the old engine will complete normally.
pub async fn reconfigure(&self, config: ZentinelSecConfig) -> Result<()> {
info!("Reconfiguring ZentinelSec engine");
let new_engine = ZentinelSecEngine::new(config)?;
let mut engine = self.engine.write().await;
*engine = new_engine;
// Clear pending requests since rules may have changed
let mut pending = self.pending_requests.write().await;
pending.clear();
info!("ZentinelSec engine reconfigured successfully");
Ok(())
}
/// Process a complete request through ZentinelSec
async fn process_request(
&self,
correlation_id: &str,
method: &str,
uri: &str,
headers: &HashMap<String, Vec<String>>,
body: Option<&[u8]>,
) -> Result<Option<(u16, String, Vec<String>)>> {
let engine = self.engine.read().await;
// Create a new transaction
let mut tx = engine.modsec.new_transaction();
// Process URI
tx.process_uri(uri, method, "HTTP/1.1")
.map_err(|e| anyhow::anyhow!("process_uri failed: {}", e))?;
// Add headers
for (name, values) in headers {
for value in values {
tx.add_request_header(name, value)
.map_err(|e| anyhow::anyhow!("add_request_header failed: {}", e))?;
}
}
// Process request headers (phase 1)
tx.process_request_headers()
.map_err(|e| anyhow::anyhow!("process_request_headers failed: {}", e))?;
// Check for intervention after headers
if let Some(intervention) = tx.intervention() {
let status = intervention.status;
if status != 0 && status != 200 {
debug!(
correlation_id = correlation_id,
status = status,
"ZentinelSec intervention (headers)"
);
// The rules that caused the intervention, not every rule that
// matched: `matched_rules()` also lists CRS setup actions and
// chain starters whose chain never completed, so its first
// entry under stock CRS is a setup rule such as 900990 rather
// than the rule that blocked.
let rule_ids = intervention.rule_ids.clone();
let message = intervention
.log
.clone()
.unwrap_or_else(|| "Blocked by ZentinelSec".to_string());
return Ok(Some((status, message, rule_ids)));
}
}
// Process body if provided (phase 2)
if let Some(body_data) = body {
if !body_data.is_empty() {
tx.append_request_body(body_data)
.map_err(|e| anyhow::anyhow!("append_request_body failed: {}", e))?;
tx.process_request_body()
.map_err(|e| anyhow::anyhow!("process_request_body failed: {}", e))?;
// Check for intervention after body
if let Some(intervention) = tx.intervention() {
let status = intervention.status;
if status != 0 && status != 200 {
debug!(
correlation_id = correlation_id,
status = status,
"ZentinelSec intervention (body)"
);
let rule_ids = intervention.rule_ids.clone();
let message = intervention
.log
.clone()
.unwrap_or_else(|| "Blocked by ZentinelSec".to_string());
return Ok(Some((status, message, rule_ids)));
}
}
}
}
Ok(None)
}
}
#[async_trait::async_trait]
impl AgentHandlerV2 for ZentinelSecAgent {
/// Return agent capabilities for v2 protocol negotiation
fn capabilities(&self) -> AgentCapabilities {
AgentCapabilities::new(
"zentinel-zentinelsec",
"ZentinelSec WAF Agent",
env!("CARGO_PKG_VERSION"),
)
.with_event(EventType::RequestHeaders)
.with_event(EventType::RequestBodyChunk)
.with_event(EventType::ResponseHeaders)
.with_event(EventType::ResponseBodyChunk)
.with_features(AgentFeatures {
streaming_body: true,
websocket: false,
guardrails: false,
config_push: true,
metrics_export: true,
concurrent_requests: 100,
cancellation: true,
flow_control: false,
health_reporting: true,
})
.with_limits(AgentLimits {
max_body_size: 10 * 1024 * 1024, // 10MB
max_concurrency: 100,
preferred_chunk_size: 64 * 1024, // 64KB
max_memory: None,
max_processing_time_ms: Some(5000),
})
}
/// Handle configuration updates from the proxy
async fn on_configure(&self, config: serde_json::Value, version: Option<String>) -> bool {
debug!(config_version = ?version, "Received configure event");
// Parse the JSON config into ZentinelSecConfigJson
let config_json: ZentinelSecConfigJson = match serde_json::from_value(config) {
Ok(config) => config,
Err(e) => {
warn!(error = %e, "Failed to parse ZentinelSec configuration");
return false;
}
};
// Convert to internal config and reconfigure the engine
let config: ZentinelSecConfig = config_json.into();
if let Err(e) = self.reconfigure(config).await {
warn!(error = %e, "Failed to reconfigure ZentinelSec engine");
return false;
}
info!(config_version = ?version, "ZentinelSec agent configured successfully");
true
}
/// Return current health status
fn health_status(&self) -> HealthStatus {
if self.is_draining() {
let drain_end = self.draining.load(Ordering::Relaxed);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let eta_ms = if drain_end > now {
Some(drain_end - now)
} else {
None
};
HealthStatus {
agent_id: "zentinel-zentinelsec".to_string(),
state: zentinel_agent_protocol::v2::HealthState::Draining { eta_ms },
message: Some("Agent is draining".to_string()),
load: None,
resources: None,
valid_until_ms: None,
timestamp_ms: now,
}
} else {
HealthStatus::healthy("zentinel-zentinelsec")
}
}
/// Return metrics report for v2 protocol
fn metrics_report(&self) -> Option<MetricsReport> {
use zentinel_agent_protocol::v2::{CounterMetric, GaugeMetric};
let mut report = MetricsReport::new("zentinel-zentinelsec", 10_000);
report.counters.push(CounterMetric::new(
"zentinelsec_requests_total",
self.requests_total.load(Ordering::Relaxed),
));
report.counters.push(CounterMetric::new(
"zentinelsec_requests_blocked",
self.requests_blocked.load(Ordering::Relaxed),
));
report.counters.push(CounterMetric::new(
"zentinelsec_requests_allowed",
self.requests_allowed.load(Ordering::Relaxed),
));
// Add gauge for pending requests
let pending_count = {
// Use try_read to avoid blocking if lock is held
self.pending_requests
.try_read()
.map(|p| p.len() as f64)
.unwrap_or(0.0)
};
report.gauges.push(GaugeMetric::new(
"zentinelsec_pending_requests",
pending_count,
));
Some(report)
}
/// Handle shutdown request
async fn on_shutdown(&self, reason: ShutdownReason, grace_period_ms: u64) {
info!(
reason = ?reason,
grace_period_ms = grace_period_ms,
"Received shutdown request"
);
// Clear pending requests on shutdown
let mut pending = self.pending_requests.write().await;
pending.clear();
}
/// Handle drain request
async fn on_drain(&self, duration_ms: u64, reason: DrainReason) {
info!(
duration_ms = duration_ms,
reason = ?reason,
"Received drain request"
);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
self.draining.store(now + duration_ms, Ordering::Relaxed);
}
async fn on_request_headers(&self, event: RequestHeadersEvent) -> AgentResponse {
self.requests_total.fetch_add(1, Ordering::Relaxed);
let path = &event.uri;
let correlation_id = &event.metadata.correlation_id;
// Check exclusions
{
let engine = self.engine.read().await;
if engine.is_excluded(path) {
debug!(path = path, "Path excluded from ZentinelSec");
return AgentResponse::default_allow();
}
}
// Always process headers immediately (phase 1)
// This detects attacks in URI, query string, and headers
match self
.process_request(
correlation_id,
&event.method,
&event.uri,
&event.headers,
None,
)
.await
{
Ok(Some((status, message, rule_ids))) => {
let engine = self.engine.read().await;
if engine.config.block_mode {
self.requests_blocked.fetch_add(1, Ordering::Relaxed);
info!(
correlation_id = correlation_id,
status = status,
rules = ?rule_ids,
"Request blocked by ZentinelSec"
);
let rule_id = rule_ids.first().cloned().unwrap_or_default();
AgentResponse::block(status, Some("Forbidden".to_string()))
.add_response_header(HeaderOp::Set {
name: "X-WAF-Blocked".to_string(),
value: "true".to_string(),
})
.add_response_header(HeaderOp::Set {
name: "X-WAF-Rule".to_string(),
value: rule_id,
})
.add_response_header(HeaderOp::Set {
name: "X-WAF-Message".to_string(),
value: message.clone(),
})
.with_audit(AuditMetadata {
tags: vec!["zentinelsec".to_string(), "blocked".to_string()],
rule_ids,
reason_codes: vec![message],
..Default::default()
})
} else {
self.requests_allowed.fetch_add(1, Ordering::Relaxed);
info!(
correlation_id = correlation_id,
rules = ?rule_ids,
"ZentinelSec detection (detect-only mode)"
);
AgentResponse::default_allow()
.add_request_header(HeaderOp::Set {
name: "X-WAF-Detected".to_string(),
value: message.clone(),
})
.with_audit(AuditMetadata {
tags: vec!["zentinelsec".to_string(), "detected".to_string()],
rule_ids,
reason_codes: vec![message],
..Default::default()
})
}
}
Ok(None) => {
self.requests_allowed.fetch_add(1, Ordering::Relaxed);
// Headers passed - if body inspection enabled, store for body processing
let engine = self.engine.read().await;
if engine.config.body_inspection_enabled {
let mut pending = self.pending_requests.write().await;
pending.insert(
correlation_id.clone(),
PendingTransaction {
body: BodyAccumulator::default(),
method: event.method.clone(),
uri: event.uri.clone(),
headers: event.headers.clone(),
client_ip: event.metadata.client_ip.clone(),
},
);
}
AgentResponse::default_allow()
}
Err(e) => {
self.requests_allowed.fetch_add(1, Ordering::Relaxed);
warn!(error = %e, "ZentinelSec processing error");
AgentResponse::default_allow()
}
}
}
async fn on_response_headers(&self, _event: ResponseHeadersEvent) -> AgentResponse {
AgentResponse::default_allow()
}
async fn on_request_body_chunk(&self, event: RequestBodyChunkEvent) -> AgentResponse {
let correlation_id = &event.correlation_id;
// Check if we have a pending request
let pending_exists = {
let pending = self.pending_requests.read().await;
pending.contains_key(correlation_id)
};
if !pending_exists {
// No pending request - body inspection might be disabled
return AgentResponse::default_allow();
}
// Decode base64 chunk
let chunk = match base64::engine::general_purpose::STANDARD.decode(&event.data) {
Ok(data) => data,
Err(e) => {
warn!(error = %e, "Failed to decode body chunk");
return AgentResponse::default_allow();
}
};
// Accumulate chunk
let should_process = {
let mut pending = self.pending_requests.write().await;
if let Some(tx) = pending.get_mut(correlation_id) {
let engine = self.engine.read().await;
// Check size limit
if tx.body.data.len() + chunk.len() > engine.config.max_body_size {
debug!(
correlation_id = correlation_id,
"Body exceeds max size, skipping inspection"
);
pending.remove(correlation_id);
return AgentResponse::default_allow();
}
tx.body.data.extend(chunk);
event.is_last
} else {
false
}
};
// If this is the last chunk, process the complete request
if should_process {
let pending_tx = {
let mut pending = self.pending_requests.write().await;
pending.remove(correlation_id)
};
if let Some(tx) = pending_tx {
match self
.process_request(
correlation_id,
&tx.method,
&tx.uri,
&tx.headers,
Some(&tx.body.data),
)
.await
{
Ok(Some((status, message, rule_ids))) => {
let engine = self.engine.read().await;
if engine.config.block_mode {
self.requests_blocked.fetch_add(1, Ordering::Relaxed);
// Decrement allowed since we counted it in headers phase
self.requests_allowed.fetch_sub(1, Ordering::Relaxed);
info!(
correlation_id = correlation_id,
status = status,
rules = ?rule_ids,
"Request blocked by ZentinelSec (body inspection)"
);
let rule_id = rule_ids.first().cloned().unwrap_or_default();
return AgentResponse::block(status, Some("Forbidden".to_string()))
.add_response_header(HeaderOp::Set {
name: "X-WAF-Blocked".to_string(),
value: "true".to_string(),
})
.add_response_header(HeaderOp::Set {
name: "X-WAF-Rule".to_string(),
value: rule_id,
})
.add_response_header(HeaderOp::Set {
name: "X-WAF-Message".to_string(),
value: message.clone(),
})
.with_audit(AuditMetadata {
tags: vec![
"zentinelsec".to_string(),
"blocked".to_string(),
"body".to_string(),
],
rule_ids,
reason_codes: vec![message],
..Default::default()
});
} else {
info!(
correlation_id = correlation_id,
rules = ?rule_ids,
"ZentinelSec detection in body (detect-only mode)"
);
return AgentResponse::default_allow()
.add_request_header(HeaderOp::Set {
name: "X-WAF-Detected".to_string(),
value: message.clone(),
})
.with_audit(AuditMetadata {
tags: vec![
"zentinelsec".to_string(),
"detected".to_string(),
"body".to_string(),
],
rule_ids,
reason_codes: vec![message],
..Default::default()
});
}
}
Ok(None) => {}
Err(e) => {
warn!(error = %e, "ZentinelSec body processing error");
}
}
}
}
AgentResponse::default_allow()
}
async fn on_response_body_chunk(&self, event: ResponseBodyChunkEvent) -> AgentResponse {
// Response body inspection not yet implemented
let _ = event;
AgentResponse::default_allow()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config() {
let config = ZentinelSecConfig::default();
assert!(config.rules_paths.is_empty());
assert!(config.block_mode);
assert!(config.body_inspection_enabled);
assert!(!config.response_inspection_enabled);
assert_eq!(config.max_body_size, 1048576);
}
#[test]
fn test_engine_initialization() {
let config = ZentinelSecConfig::default();
let engine = ZentinelSecEngine::new(config);
assert!(engine.is_ok());
}
#[test]
fn test_engine_with_inline_rule() {
// Test with a simple inline rule
let config = ZentinelSecConfig::default();
let engine = ZentinelSecEngine::new(config).unwrap();
// Verify engine is working
let mut tx = engine.modsec.new_transaction();
tx.process_uri("/test", "GET", "HTTP/1.1").unwrap();
tx.process_request_headers().unwrap();
// Should not block clean requests
assert!(tx.intervention().is_none());
}
#[test]
fn test_path_exclusion() {
let config = ZentinelSecConfig {
exclude_paths: vec!["/health".to_string(), "/metrics".to_string()],
..Default::default()
};
let engine = ZentinelSecEngine::new(config).unwrap();
assert!(engine.is_excluded("/health"));
assert!(engine.is_excluded("/health/live"));
assert!(engine.is_excluded("/metrics"));
assert!(!engine.is_excluded("/api/users"));
}
#[test]
fn test_sql_injection_blocked() {
// Create a ModSecurity engine with a SQL injection detection rule
let rules = r#"
SecRuleEngine On
SecRule ARGS "@detectSQLi" "id:942100,phase:2,deny,status:403,msg:'SQL Injection Attack Detected'"
SecRule QUERY_STRING "@detectSQLi" "id:942101,phase:1,deny,status:403,msg:'SQL Injection in Query String'"
SecRule REQUEST_URI "@contains union select" "id:942102,phase:1,deny,status:403,msg:'UNION SELECT detected'"
"#;
let modsec = zentinel_modsec::ModSecurity::from_string(rules).unwrap();
// Test 1: Classic SQL injection in query string
let mut tx = modsec.new_transaction();
tx.process_uri("/api/users?id=1' OR '1'='1", "GET", "HTTP/1.1")
.unwrap();
tx.process_request_headers().unwrap();
let intervention = tx.intervention();
assert!(
intervention.is_some(),
"Expected SQL injection to be blocked: 1' OR '1'='1"
);
if let Some(i) = intervention {
assert_eq!(i.status, 403);
println!("Blocked with status {}: {:?}", i.status, i.rule_ids);
}
// Test 2: UNION-based SQL injection
let mut tx2 = modsec.new_transaction();
tx2.process_uri(
"/api/users?id=1 union select * from users--",
"GET",
"HTTP/1.1",
)
.unwrap();
tx2.process_request_headers().unwrap();
let intervention2 = tx2.intervention();
assert!(
intervention2.is_some(),
"Expected UNION SELECT injection to be blocked"
);
// Test 3: Clean request should pass
let mut tx3 = modsec.new_transaction();
tx3.process_uri("/api/users?id=123", "GET", "HTTP/1.1")
.unwrap();
tx3.process_request_headers().unwrap();
assert!(
tx3.intervention().is_none(),
"Clean request should not be blocked"
);
}
#[test]
fn test_xss_blocked() {
// Create a ModSecurity engine with XSS detection rule
let rules = r#"
SecRuleEngine On
SecRule ARGS "@detectXSS" "id:941100,phase:2,deny,status:403,msg:'XSS Attack Detected'"
SecRule QUERY_STRING "@detectXSS" "id:941101,phase:1,deny,status:403,msg:'XSS in Query String'"
SecRule REQUEST_URI "@contains <script" "id:941102,phase:1,deny,status:403,msg:'Script tag detected'"
"#;
let modsec = zentinel_modsec::ModSecurity::from_string(rules).unwrap();
// Test 1: Script tag injection
let mut tx = modsec.new_transaction();
tx.process_uri("/search?q=<script>alert(1)</script>", "GET", "HTTP/1.1")
.unwrap();
tx.process_request_headers().unwrap();
let intervention = tx.intervention();
assert!(
intervention.is_some(),
"Expected XSS to be blocked: <script>alert(1)</script>"
);
if let Some(i) = intervention {
assert_eq!(i.status, 403);
println!("XSS blocked with status {}: {:?}", i.status, i.rule_ids);
}
// Test 2: Event handler injection
let mut tx2 = modsec.new_transaction();
tx2.process_uri("/search?q=<img src=x onerror=alert(1)>", "GET", "HTTP/1.1")
.unwrap();
tx2.process_request_headers().unwrap();
let intervention2 = tx2.intervention();
assert!(
intervention2.is_some(),
"Expected event handler XSS to be blocked"
);
// Test 3: Clean request should pass
let mut tx3 = modsec.new_transaction();
tx3.process_uri("/search?q=hello+world", "GET", "HTTP/1.1")
.unwrap();
tx3.process_request_headers().unwrap();
assert!(
tx3.intervention().is_none(),
"Clean request should not be blocked"
);
}
#[test]
fn test_request_body_sql_injection() {
// Test SQL injection in POST body
let rules = r#"
SecRuleEngine On
SecRequestBodyAccess On
SecRule ARGS "@detectSQLi" "id:942200,phase:2,deny,status:403,msg:'SQL Injection in Body'"
"#;
let modsec = zentinel_modsec::ModSecurity::from_string(rules).unwrap();
let mut tx = modsec.new_transaction();
tx.process_uri("/api/login", "POST", "HTTP/1.1").unwrap();
tx.add_request_header("Content-Type", "application/x-www-form-urlencoded")
.unwrap();
tx.process_request_headers().unwrap();
// Add malicious body
let body = b"username=admin&password=' OR '1'='1";
tx.append_request_body(body).unwrap();
tx.process_request_body().unwrap();
let intervention = tx.intervention();
assert!(
intervention.is_some(),
"Expected SQL injection in POST body to be blocked"
);
if let Some(i) = intervention {
assert_eq!(i.status, 403);
println!("Body SQLi blocked: {:?}", i.rule_ids);
}
}
}