killer 2.0.1

A Rust security platform: static analysis, the .klr test language, a parallel test framework, project intelligence, code review, and a CI gate.
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
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
//! The `.klr` interpreter: executes [`Attack`]s against a target and evaluates
//! their expectations into [`AttackOutcome`]s.
//!
//! Semantics: a `.klr` attack describes how a *secure* system should behave.
//! When every expectation holds, the system defended itself and the verdict is
//! `Secure` (`PASSED`). When an expectation fails, a vulnerability is indicated
//! and the verdict is `Vulnerable` (`FAILED`) — matching the "attack report"
//! framing of the language. When an expectation names something this engine has
//! no implementation for, the verdict is `Inconclusive`: the attack was not
//! actually performed, so it is not evidence of either outcome.

use crate::attacks::http::{HttpClient, HttpRequest, Url};
use crate::attacks::{database, filesystem};
use crate::klr::ast::{Attack, Expectation, Value};
use crate::results::{AttackOutcome, CheckResult, Verdict};

/// Runtime configuration for the interpreter.
#[derive(Debug, Clone)]
pub struct RunConfig {
    /// Base URL that relative targets resolve against.
    pub base_url: String,
    /// Hard cap on how many requests a `repeat` will actually send.
    pub max_requests: usize,
}

impl Default for RunConfig {
    fn default() -> Self {
        RunConfig {
            base_url: "http://127.0.0.1:8080".to_string(),
            max_requests: 100,
        }
    }
}

/// Status codes that count as "rate limited / blocked".
const BLOCKED_STATUSES: &[u16] = &[403, 429, 503];

pub struct Interpreter<'a> {
    client: &'a dyn HttpClient,
    config: RunConfig,
}

impl<'a> Interpreter<'a> {
    pub fn new(client: &'a dyn HttpClient, config: RunConfig) -> Self {
        Interpreter { client, config }
    }

    /// Execute every attack in order.
    pub fn run(&self, attacks: &[Attack]) -> Vec<AttackOutcome> {
        attacks.iter().map(|a| self.run_attack(a)).collect()
    }

    fn run_attack(&self, attack: &Attack) -> AttackOutcome {
        let issue_id = classify(attack);
        if is_session_flow(attack) {
            return self.run_session_flow(attack, issue_id);
        }
        self.run_request_attack(attack, issue_id)
    }

    // --- request-based attacks --------------------------------------------

    fn run_request_attack(&self, attack: &Attack, issue_id: Option<String>) -> AttackOutcome {
        let Some(target) = attack.target.clone() else {
            return errored(
                attack,
                "attack has no `target`/`endpoint` to request",
                issue_id,
            );
        };

        let url = match Url::resolve(&self.config.base_url, &target) {
            Ok(u) => u,
            Err(e) => return errored(attack, &format!("invalid target: {e}"), issue_id),
        };
        let method = attack
            .method
            .clone()
            .unwrap_or_else(|| default_method(attack));
        let (body, mut headers) = build_body(attack);
        for (k, v) in &attack.headers {
            headers.push((k.clone(), v.as_string()));
        }

        let req = HttpRequest {
            method: method.clone(),
            url: url.to_absolute(),
            headers,
            body,
        };

        let repeat = attack.repeat.unwrap_or(1).max(1);
        let effective = repeat.min(self.config.max_requests);

        let mut statuses: Vec<u16> = Vec::new();
        let mut first_blocked: Option<usize> = None;
        let mut last_body = String::new();

        for n in 1..=effective {
            match self.client.execute(&req) {
                Ok(resp) => {
                    if first_blocked.is_none() && BLOCKED_STATUSES.contains(&resp.status) {
                        first_blocked = Some(n);
                    }
                    statuses.push(resp.status);
                    last_body = resp.body;
                    // Once blocked, no need to keep hammering for rate-limit tests.
                    if first_blocked.is_some()
                        && attack
                            .expectations
                            .iter()
                            .any(|e| matches!(e, Expectation::BlockedAfter(_)))
                    {
                        break;
                    }
                }
                Err(e) => {
                    if n == 1 {
                        return errored(attack, &format!("request failed: {e}"), issue_id);
                    }
                    // Later failure: stop and evaluate what we have.
                    break;
                }
            }
        }

        let last_status = *statuses.last().unwrap_or(&0);
        let target_line = format!("{} {}", method, url.to_absolute());

        let mut checks = Vec::new();
        for exp in &attack.expectations {
            checks.push(self.eval_expectation(
                exp,
                last_status,
                &last_body,
                &statuses,
                first_blocked,
            ));
        }

        // Automatic bonus check: a leaked SQL error is always a failure when we
        // sent a body (i.e. this looks like an injection probe).
        if (!attack.send.is_empty() || attack.payload.is_some())
            && database::response_indicates_sqli(&last_body)
        {
            checks.push(CheckResult {
                description: "no SQL error leaked in response".to_string(),
                passed: false,
                evaluated: true,
                detail: "response body contains a database error signature".to_string(),
            });
        }

        let verdict = verdict_from_checks(&checks);
        AttackOutcome {
            name: attack.name.clone(),
            suite: attack.suite.clone(),
            severity: attack.severity.label().to_string(),
            target: target_line,
            verdict,
            message: attack.message.clone(),
            checks,
            error: None,
            issue_id,
        }
    }

    fn eval_expectation(
        &self,
        exp: &Expectation,
        last_status: u16,
        last_body: &str,
        statuses: &[u16],
        first_blocked: Option<usize>,
    ) -> CheckResult {
        match exp {
            Expectation::Status { op, value } => {
                let passed = op.apply(last_status as i64, *value);
                CheckResult {
                    description: format!("status {} {}", op.symbol(), value),
                    passed,
                    evaluated: true,
                    detail: format!("observed status {last_status}"),
                }
            }
            Expectation::ResponseContains(s) => {
                let passed = last_body.contains(s);
                CheckResult {
                    description: format!("response contains \"{s}\""),
                    passed,
                    evaluated: true,
                    detail: if passed {
                        "found in response".to_string()
                    } else {
                        "not found in response".to_string()
                    },
                }
            }
            Expectation::ResponseNotContains(s) => {
                let passed = !last_body.contains(s);
                CheckResult {
                    description: format!("response does_not_contain \"{s}\""),
                    passed,
                    evaluated: true,
                    detail: if passed {
                        "absent from response".to_string()
                    } else {
                        format!("\"{s}\" leaked in response")
                    },
                }
            }
            Expectation::BlockedAfter(n) => {
                let passed = first_blocked.is_some();
                let detail = match first_blocked {
                    Some(idx) => format!("blocked at request #{idx} (limit {n})"),
                    None => format!("no rate limiting after {} requests", statuses.len()),
                };
                CheckResult {
                    description: format!("blocked_after {n}"),
                    passed,
                    evaluated: true,
                    detail,
                }
            }
            Expectation::Named { name, expected } => {
                self.eval_named(name, *expected, last_status, last_body)
            }
        }
    }

    fn eval_named(
        &self,
        name: &str,
        expected: bool,
        last_status: u16,
        last_body: &str,
    ) -> CheckResult {
        match name {
            "file_not_exposed" => {
                let exposed = filesystem::response_exposes_file(last_body);
                let held = !exposed; // secure = not exposed
                CheckResult {
                    description: format!("{name} {expected}"),
                    passed: held == expected,
                    evaluated: true,
                    detail: if exposed {
                        "sensitive file contents found in response".to_string()
                    } else {
                        "no sensitive file contents in response".to_string()
                    },
                }
            }
            "session_invalidated" => {
                let invalidated = matches!(last_status, 401 | 403);
                CheckResult {
                    description: format!("{name} {expected}"),
                    passed: invalidated == expected,
                    evaluated: true,
                    detail: format!("reuse returned status {last_status}"),
                }
            }
            // `check authentication` — the endpoint should reject unauthenticated
            // access (401/403) rather than serve it (200).
            "requires_auth" => {
                let denied = matches!(last_status, 401 | 403 | 302);
                CheckResult {
                    description: "requires authentication".to_string(),
                    passed: denied == expected,
                    evaluated: true,
                    detail: format!("unauthenticated request returned status {last_status}"),
                }
            }
            // `check injection` — no database error should leak.
            "no_sql_error" => {
                let leaked = database::response_indicates_sqli(last_body);
                CheckResult {
                    description: "no SQL error leaked".to_string(),
                    passed: !leaked == expected,
                    evaluated: true,
                    detail: if leaked {
                        "database error signature found in response".to_string()
                    } else {
                        "no database error in response".to_string()
                    },
                }
            }
            // No implementation for this name. Say so instead of passing it:
            // a green tick here would claim the target defended something the
            // engine never looked at.
            _ => CheckResult {
                description: format!("{name} {expected}"),
                passed: false,
                evaluated: false,
                detail: format!("no `{name}` check is implemented by this engine"),
            },
        }
    }

    // --- session flow -----------------------------------------------------

    fn run_session_flow(&self, attack: &Attack, issue_id: Option<String>) -> AttackOutcome {
        let login_path = attack
            .target
            .clone()
            .unwrap_or_else(|| "/login".to_string());
        let url = match Url::resolve(&self.config.base_url, &login_path) {
            Ok(u) => u,
            Err(e) => return errored(attack, &format!("invalid login target: {e}"), issue_id),
        };

        // Build login body from the `login user "..."` action (plus any `send`).
        let mut fields: Vec<(String, Value)> = attack.send.clone();
        if let Some(login) = attack.actions.iter().find(|a| a.verb == "login") {
            if let Some(Value::Str(user)) = login.args.iter().find(|v| matches!(v, Value::Str(_))) {
                fields.push(("username".to_string(), Value::Str(user.clone())));
            }
        }
        let body = json_object(&fields);

        let login_req = HttpRequest {
            method: "POST".to_string(),
            url: url.to_absolute(),
            headers: vec![],
            body: Some(body),
        };

        let login_resp = match self.client.execute(&login_req) {
            Ok(r) => r,
            Err(e) => return errored(attack, &format!("login request failed: {e}"), issue_id),
        };
        let cookie = login_resp
            .header("set-cookie")
            .map(|c| c.split(';').next().unwrap_or(c).to_string());

        // Reuse the (possibly stolen) cookie against the same endpoint.
        let mut reuse_headers = Vec::new();
        if let Some(c) = &cookie {
            reuse_headers.push(("Cookie".to_string(), c.clone()));
        }
        let reuse_req = HttpRequest {
            method: "GET".to_string(),
            url: url.to_absolute(),
            headers: reuse_headers,
            body: None,
        };
        let reuse_resp = match self.client.execute(&reuse_req) {
            Ok(r) => r,
            Err(e) => return errored(attack, &format!("reuse request failed: {e}"), issue_id),
        };

        let mut checks = Vec::new();
        checks.push(CheckResult {
            description: "captured session cookie".to_string(),
            passed: true,
            evaluated: true,
            detail: match &cookie {
                Some(c) => format!("stole cookie `{c}`"),
                None => "no Set-Cookie returned by login".to_string(),
            },
        });
        for exp in &attack.expectations {
            checks.push(self.eval_expectation(exp, reuse_resp.status, &reuse_resp.body, &[], None));
        }

        let verdict = verdict_from_checks(&checks);
        AttackOutcome {
            name: attack.name.clone(),
            suite: attack.suite.clone(),
            severity: attack.severity.label().to_string(),
            target: format!("session flow via {}", url.to_absolute()),
            verdict,
            message: attack.message.clone(),
            checks,
            error: None,
            issue_id,
        }
    }
}

// --- helpers --------------------------------------------------------------

fn verdict_from_checks(checks: &[CheckResult]) -> Verdict {
    if checks.iter().any(|c| c.evaluated && !c.passed) {
        // A confirmed failure outranks missing coverage: it is actionable.
        Verdict::Vulnerable
    } else if checks.iter().any(|c| !c.evaluated) {
        Verdict::Inconclusive
    } else {
        Verdict::Secure
    }
}

fn errored(attack: &Attack, message: &str, issue_id: Option<String>) -> AttackOutcome {
    AttackOutcome {
        name: attack.name.clone(),
        suite: attack.suite.clone(),
        severity: attack.severity.label().to_string(),
        target: attack.target.clone().unwrap_or_default(),
        verdict: Verdict::Errored,
        message: attack.message.clone(),
        checks: Vec::new(),
        error: Some(message.to_string()),
        issue_id,
    }
}

fn default_method(attack: &Attack) -> String {
    if !attack.send.is_empty() || attack.payload.is_some() {
        "POST".to_string()
    } else {
        "GET".to_string()
    }
}

/// Build the request body and any implied headers for an attack's `send` /
/// `payload` fields. Exposed to the crate so `killer fuzz` fires requests that
/// are byte-for-byte identical to a `.klr` `mutate`.
pub(crate) fn build_body(attack: &Attack) -> (Option<String>, Vec<(String, String)>) {
    if !attack.send.is_empty() {
        (Some(json_object(&attack.send)), Vec::new())
    } else if let Some(p) = &attack.payload {
        (
            Some(p.clone()),
            vec![("Content-Type".to_string(), "text/plain".to_string())],
        )
    } else {
        (None, Vec::new())
    }
}

/// Serialize key/value pairs into a compact JSON object string.
fn json_object(fields: &[(String, Value)]) -> String {
    let mut out = String::from("{");
    for (i, (k, v)) in fields.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push_str(&format!("\"{}\":", json_escape(k)));
        match v {
            Value::Num(n) => out.push_str(&n.to_string()),
            Value::Bool(b) => out.push_str(&b.to_string()),
            other => out.push_str(&format!("\"{}\"", json_escape(&other.as_string()))),
        }
    }
    out.push('}');
    out
}

fn json_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            _ => out.push(c),
        }
    }
    out
}

fn is_session_flow(attack: &Attack) -> bool {
    attack.actions.iter().any(|a| a.verb == "login")
        || attack
            .expectations
            .iter()
            .any(|e| matches!(e, Expectation::Named { name, .. } if name == "session_invalidated"))
}

/// Assign a stable issue id (used by `killer explain`) based on the attack's shape.
fn classify(attack: &Attack) -> Option<String> {
    if attack
        .payload
        .as_ref()
        .is_some_and(|p| filesystem::is_path_traversal(p))
    {
        return Some("KLR-PATH-TRAVERSAL".to_string());
    }
    if attack
        .expectations
        .iter()
        .any(|e| matches!(e, Expectation::BlockedAfter(_)))
    {
        return Some("KLR-RATE-LIMIT".to_string());
    }
    if is_session_flow(attack) {
        return Some("KLR-SESSION".to_string());
    }
    if looks_like_sqli(attack) {
        return Some("KLR-SQLI".to_string());
    }
    Some("KLR-GENERIC".to_string())
}

fn looks_like_sqli(attack: &Attack) -> bool {
    let needles = ["'", " or ", "1=1", "--", "union select", "\" or"];
    let in_send = attack.send.iter().any(|(_, v)| {
        let s = v.as_string().to_ascii_lowercase();
        needles.iter().any(|n| s.contains(n))
    });
    let in_msg = attack
        .message
        .as_ref()
        .map(|m| {
            let m = m.to_ascii_lowercase();
            m.contains("sql") || m.contains("injection")
        })
        .unwrap_or(false);
    in_send || in_msg
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::attacks::http::{HttpError, HttpResponse};
    use std::cell::RefCell;

    /// A scripted client that returns queued responses in order.
    struct MockClient {
        responses: RefCell<Vec<HttpResponse>>,
        default: HttpResponse,
    }

    impl MockClient {
        fn new(responses: Vec<HttpResponse>, default: HttpResponse) -> Self {
            MockClient {
                responses: RefCell::new(responses),
                default,
            }
        }
    }

    impl HttpClient for MockClient {
        fn execute(&self, _req: &HttpRequest) -> Result<HttpResponse, HttpError> {
            let mut q = self.responses.borrow_mut();
            if q.is_empty() {
                Ok(self.default.clone())
            } else {
                Ok(q.remove(0))
            }
        }
    }

    fn resp(status: u16, body: &str) -> HttpResponse {
        HttpResponse {
            status,
            headers: vec![],
            body: body.to_string(),
        }
    }

    fn run_one(src: &str, client: &dyn HttpClient) -> AttackOutcome {
        let program = crate::klr::parser::parse(src).unwrap();
        let interp = Interpreter::new(client, RunConfig::default());
        interp.run(&program.attacks).remove(0)
    }

    #[test]
    fn sqli_vulnerable_when_login_succeeds() {
        // Server wrongly returns 200 with a token -> both expectations fail.
        let client = MockClient::new(vec![], resp(200, "{\"token\":\"abc\"}"));
        let src = r#"
attack authentication {
    target "/api/login"
    send { username = "' OR 1=1" password = "x" }
    expect {
        status != 200
        response does_not_contain "token"
    }
    severity critical
    message: "SQL injection vulnerability detected"
}
"#;
        let out = run_one(src, &client);
        assert_eq!(out.verdict, Verdict::Vulnerable);
        assert_eq!(out.issue_id.as_deref(), Some("KLR-SQLI"));
    }

    #[test]
    fn sqli_secure_when_login_rejected() {
        let client = MockClient::new(vec![], resp(401, "invalid credentials"));
        let src = r#"
attack authentication {
    target "/api/login"
    send { username = "' OR 1=1" }
    expect {
        status != 200
        response does_not_contain "token"
    }
}
"#;
        let out = run_one(src, &client);
        assert_eq!(out.verdict, Verdict::Secure);
    }

    #[test]
    fn rate_limit_secure_when_blocked() {
        // First two 200s then a 429.
        let client = MockClient::new(
            vec![resp(200, "ok"), resp(200, "ok"), resp(429, "slow down")],
            resp(200, "ok"),
        );
        let src = r#"
attack rl {
    request: POST "/login"
    repeat: 100 times
    expect: blocked_after 10
}
"#;
        let out = run_one(src, &client);
        assert_eq!(out.verdict, Verdict::Secure);
        assert_eq!(out.issue_id.as_deref(), Some("KLR-RATE-LIMIT"));
    }

    #[test]
    fn rate_limit_vulnerable_when_never_blocked() {
        let client = MockClient::new(vec![], resp(200, "ok"));
        let src = r#"
attack rl {
    request: POST "/login"
    repeat: 20 times
    expect: blocked_after 10
}
"#;
        let out = run_one(src, &client);
        assert_eq!(out.verdict, Verdict::Vulnerable);
    }

    #[test]
    fn upload_vulnerable_when_file_exposed() {
        let client = MockClient::new(vec![], resp(200, "root:x:0:0:root:/root:/bin/bash"));
        let src = r#"
attack upload {
    endpoint "/upload"
    payload: "../../etc/passwd"
    expect { file_not_exposed true }
}
"#;
        let out = run_one(src, &client);
        assert_eq!(out.verdict, Verdict::Vulnerable);
        assert_eq!(out.issue_id.as_deref(), Some("KLR-PATH-TRAVERSAL"));
    }

    #[test]
    fn unimplemented_check_is_inconclusive_never_secure() {
        // The target 404s everything, so it defended nothing. `csrf` has no
        // implementation, so the engine must refuse to call this a pass.
        let client = MockClient::new(vec![], resp(404, "404 Not Found"));
        let src = r#"
attack csrf_protection {
    target "/transfer"
    expect { csrf true }
}
"#;
        let out = run_one(src, &client);
        assert_eq!(out.verdict, Verdict::Inconclusive);
        let check = &out.checks[0];
        assert!(!check.evaluated);
        assert!(
            !check.passed,
            "an unevaluated check must never be recorded as passing"
        );
    }

    #[test]
    fn unimplemented_check_taints_an_otherwise_passing_attack() {
        // Every implemented expectation holds; the unknown one still denies the
        // attack a clean verdict.
        let client = MockClient::new(vec![], resp(401, "denied"));
        let src = r#"
attack mixed {
    target "/admin"
    expect {
        status != 200
        clickjacking true
    }
}
"#;
        let out = run_one(src, &client);
        assert_eq!(out.verdict, Verdict::Inconclusive);
    }

    #[test]
    fn confirmed_failure_outranks_an_unevaluated_check() {
        let client = MockClient::new(vec![], resp(200, "ok"));
        let src = r#"
attack mixed {
    target "/admin"
    expect {
        status != 200
        clickjacking true
    }
}
"#;
        let out = run_one(src, &client);
        assert_eq!(out.verdict, Verdict::Vulnerable);
    }

    #[test]
    fn errored_when_connection_fails() {
        struct FailClient;
        impl HttpClient for FailClient {
            fn execute(&self, _: &HttpRequest) -> Result<HttpResponse, HttpError> {
                Err(HttpError {
                    message: "connection refused".to_string(),
                })
            }
        }
        let src = r#"
attack a {
    target "/x"
    expect { status != 200 }
}
"#;
        let out = run_one(src, &FailClient);
        assert_eq!(out.verdict, Verdict::Errored);
        assert!(out.error.is_some());
    }
}