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
use crate::{
config::Config,
evasion,
extractor::DataExtractor,
fingerprints::{DetectionResponse, WafDetector},
http::{build_client, send_request},
payloads::PayloadManager,
types::{Finding, ScanResults, ScanSummary},
};
use std::collections::HashSet;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::Semaphore;
use tokio::time::{sleep, Duration};
/// WAF scanner
pub struct Scanner {
config: Config,
client: reqwest::Client,
payload_manager: PayloadManager,
waf_detector: WafDetector,
data_extractor: DataExtractor,
}
impl Scanner {
/// Create a new scanner
pub async fn new(config: Config) -> crate::error::Result<Self> {
config.validate()?;
let client = build_client(&config)?;
let payload_manager = if let Some(ref payload_file) = config.payload_file {
tracing::info!("Loading custom payloads from: {}", payload_file);
PayloadManager::from_file(payload_file).await?
} else {
tracing::info!("Loading default embedded payloads");
PayloadManager::with_defaults()?
};
let waf_detector = WafDetector::new()?;
let data_extractor = DataExtractor::new();
Ok(Self {
config,
client,
payload_manager,
waf_detector,
data_extractor,
})
}
/// Perform the WAF bypass scan
#[tracing::instrument(skip(self), fields(target = %self.config.target))]
pub async fn scan(&self) -> crate::error::Result<ScanResults> {
let start_time = Instant::now();
tracing::info!("Starting WAF scan on {}", self.config.target);
// Step 1: Detect WAF
let waf_detected = self.detect_waf().await?;
if let Some(ref waf_name) = waf_detected {
tracing::info!("Detected WAF: {}", waf_name);
} else {
tracing::info!("No WAF detected");
}
// Step 2: Run payload tests
let mut results = ScanResults::new(self.config.target.clone(), waf_detected);
let findings = self.test_payloads().await?;
for finding in findings {
results.add_finding(finding);
}
// Step 3: Calculate summary
results.sort_by_severity();
let techniques_used: HashSet<_> = results
.findings
.iter()
.filter_map(|f| f.technique_used.as_ref())
.collect();
results.summary = ScanSummary {
total_payloads: self.payload_manager.payloads().len(),
successful_bypasses: results.findings.len(),
techniques_effective: techniques_used.len(),
duration_secs: start_time.elapsed().as_secs_f64(),
};
tracing::info!(
"Scan complete. Found {} successful bypasses in {:.2}s",
results.summary.successful_bypasses,
results.summary.duration_secs
);
Ok(results)
}
/// Detect WAF by sending a baseline request
async fn detect_waf(&self) -> crate::error::Result<Option<String>> {
tracing::debug!("Sending baseline request for WAF detection");
let response = send_request(&self.client, &self.config.target, None)
.await
.map_err(|e| {
tracing::error!("Connection failed: {}", e);
e // Just pass through the reqwest::Error
})?;
// Log HTTP version information
tracing::info!(
"Target {} is using HTTP version: {}",
self.config.target,
response.http_version
);
if response.http_version.contains("HTTP/2") {
tracing::info!("✓ HTTP/2 protocol detected - production-ready configuration active");
} else {
tracing::warn!("âš HTTP/1.x detected - some HTTP/2 tests may not apply");
}
let detection_response = DetectionResponse::new(
response.status_code,
response.headers,
response.body,
response.cookies,
);
Ok(self.waf_detector.detect(&detection_response))
}
/// Test all payloads with evasion techniques
async fn test_payloads(&self) -> crate::error::Result<Vec<Finding>> {
let payloads = self.payload_manager.payloads();
let semaphore = Arc::new(Semaphore::new(self.config.concurrency));
let mut tasks = Vec::new();
tracing::info!("Testing {} payloads", payloads.len());
for payload in payloads {
for payload_test in &payload.payloads {
// Apply all evasion techniques
let technique_variants = evasion::apply_all_techniques(
&payload_test.value,
self.config.enabled_techniques.as_deref(),
);
for (technique_name, transformed_payload) in technique_variants {
let sem = semaphore.clone();
let client = self.client.clone();
let target = self.config.target.clone();
let delay_ms = self.config.delay_ms;
let payload_id = payload.id.clone();
let severity = payload.info.severity;
let category = payload.info.category.clone();
let description = payload.info.description.clone();
let matchers = payload.matchers.clone();
let extractor = self.data_extractor.clone();
let task = tokio::spawn(async move {
let _permit = sem.acquire().await.unwrap();
// Rate limiting delay
if delay_ms > 0 {
sleep(Duration::from_millis(delay_ms)).await;
}
// Send request with payload as query parameter
let response =
send_request(&client, &target, Some(("test", &transformed_payload)))
.await;
match response {
Ok(resp) => {
// Check if payload matched
let matched = check_matchers(&resp, &matchers);
if matched {
tracing::debug!(
"Payload {} matched with technique: {} (HTTP version: {})",
payload_id,
technique_name,
resp.http_version
);
// Extract sensitive data from response
let extracted_data = extractor.extract(
&resp.body,
&resp.headers,
&resp.cookies,
);
Some(Finding {
payload_id: payload_id.clone(),
severity,
category: category.clone(),
owasp_category: crate::types::OwaspCategory::from_attack_type(&category),
payload_value: transformed_payload,
technique_used: if technique_name == "Original" {
None
} else {
Some(technique_name)
},
response_status: resp.status_code,
description,
http_version: Some(resp.http_version),
extracted_data: if extracted_data.has_data() {
Some(extracted_data)
} else {
None
},
})
} else {
None
}
}
Err(e) => {
tracing::warn!("Request failed for payload {}: {}", payload_id, e);
None
}
}
});
tasks.push(task);
}
}
}
// Wait for all tasks to complete
let results = futures::future::join_all(tasks).await;
// Collect findings
let findings: Vec<Finding> = results
.into_iter()
.filter_map(|r| r.ok())
.flatten()
.collect();
Ok(findings)
}
}
/// Check if response matches any of the matchers
fn check_matchers(
response: &crate::http::HttpResponse,
matchers: &[crate::payloads::Matcher],
) -> bool {
for matcher in matchers {
match matcher.matcher_type.as_str() {
"response_body" => {
if matcher.condition == "contains" {
for pattern in &matcher.patterns {
if response.body.contains(pattern) {
return true;
}
}
} else if matcher.condition == "not_contains" {
let mut all_not_found = true;
for pattern in &matcher.patterns {
if response.body.contains(pattern) {
all_not_found = false;
break;
}
}
if all_not_found {
return true;
}
}
}
"response_time" => {
if matcher.condition == "greater_than" {
if let Some(threshold) = matcher.patterns.first() {
if let Ok(threshold_ms) = threshold.parse::<u64>() {
if response.response_time_ms > threshold_ms {
return true;
}
}
}
}
}
"response_status" => {
if matcher.condition == "equals" {
for pattern in &matcher.patterns {
if let Ok(expected_status) = pattern.parse::<u16>() {
if response.status_code == expected_status {
return true;
}
}
}
} else if matcher.condition == "not_equals" {
let mut all_different = true;
for pattern in &matcher.patterns {
if let Ok(expected_status) = pattern.parse::<u16>() {
if response.status_code == expected_status {
all_different = false;
break;
}
}
}
if all_different {
return true;
}
}
}
"response_header" => {
if matcher.condition == "contains" {
for pattern in &matcher.patterns {
for (_, header_value) in &response.headers {
if header_value.contains(pattern) {
return true;
}
}
}
} else if matcher.condition == "not_contains" {
let mut found = false;
for pattern in &matcher.patterns {
for (_, header_value) in &response.headers {
if header_value.contains(pattern) {
found = true;
break;
}
}
if found {
break;
}
}
if !found {
return true;
}
}
}
"ai_refusal_bypass" => {
// Check for absence of AI refusal patterns (indicates successful jailbreak)
if matcher.condition == "not_contains" {
let mut all_not_found = true;
for pattern in &matcher.patterns {
if response.body.to_lowercase().contains(&pattern.to_lowercase()) {
all_not_found = false;
break;
}
}
if all_not_found {
return true;
}
}
}
"system_prompt_leak" => {
// Detect system prompt leakage indicators
if matcher.condition == "contains" {
for pattern in &matcher.patterns {
if response.body.contains(pattern) {
return true;
}
}
}
}
"jailbreak_success" => {
// Detect jailbreak success indicators (e.g., compliance with malicious request)
if matcher.condition == "contains" {
for pattern in &matcher.patterns {
if response.body.to_lowercase().contains(&pattern.to_lowercase()) {
return true;
}
}
}
}
"response_json" => {
// Validate JSON structure for improper output handling
if matcher.condition == "valid" {
// Check if response body is valid JSON
if serde_json::from_str::<serde_json::Value>(&response.body).is_ok() {
return true;
}
} else if matcher.condition == "contains_field" {
// Check if JSON contains specific fields
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&response.body) {
for pattern in &matcher.patterns {
if json.get(pattern).is_some() {
return true;
}
}
}
}
}
_ => {
tracing::warn!("Unknown matcher type: {}", matcher.matcher_type);
}
}
}
false
}