noctis 0.4.0

Open-source black-box vulnerability scanner: readable YAML checks that prove each bug on the live service, QoD-graded findings, REST API.
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
use std::collections::HashMap;

use rhai::{Dynamic, Engine, Scope};

use crate::error::{NoctisError, Result};

pub fn eval_condition(expr: &str, vars: &HashMap<String, serde_json::Value>) -> Result<bool> {
    let engine = build_engine();
    let mut scope = Scope::new();

    for (key, val) in vars {
        scope.push_dynamic(key.replace('.', "_"), json_to_dynamic(val));
    }

    let result: Dynamic = engine
        .eval_expression_with_scope::<Dynamic>(&mut scope, expr)
        .map_err(|e| NoctisError::ExprError {
            step: "<condition>".to_string(),
            message: e.to_string(),
        })?;

    Ok(result.as_bool().unwrap_or(false))
}

pub fn eval_script(
    code: &str,
    vars: &mut HashMap<String, serde_json::Value>,
    step_id: &str,
) -> Result<serde_json::Value> {
    let engine = build_engine();
    let mut scope = Scope::new();

    for (key, val) in vars.iter() {
        scope.push_dynamic(key.replace('.', "_"), json_to_dynamic(val));
    }

    let result: Dynamic = engine
        .eval_with_scope::<Dynamic>(&mut scope, code)
        .map_err(|e| NoctisError::ExprError {
            step: step_id.to_string(),
            message: e.to_string(),
        })?;

    // Write back only the variables the script actually changed. An untouched
    // var keeps its original JSON value, so nested stored results (e.g. a
    // `store_as` object read later as `{{vnc.response_hex}}`) survive (#393).
    for (key, val) in vars.iter_mut() {
        let rhai_name = key.replace('.', "_");
        if let Some(dyn_val) = scope.get_value::<Dynamic>(&rhai_name) {
            let new_val = dynamic_to_json(dyn_val);
            if new_val != dynamic_to_json(json_to_dynamic(val)) {
                *val = new_val;
            }
        }
    }

    Ok(dynamic_to_json(result))
}

fn build_engine() -> Engine {
    let mut engine = Engine::new();
    engine.set_max_operations(100_000);
    engine.set_max_string_size(1024 * 1024);
    super::builtins::register(&mut engine);
    super::crypto::register(&mut engine);
    super::binpack::register(&mut engine);
    engine
}

pub(crate) fn json_to_dynamic(v: &serde_json::Value) -> Dynamic {
    match v {
        serde_json::Value::Null => Dynamic::UNIT,
        serde_json::Value::Bool(b) => Dynamic::from(*b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Dynamic::from(i)
            } else if let Some(f) = n.as_f64() {
                Dynamic::from(f)
            } else {
                Dynamic::UNIT
            }
        }
        serde_json::Value::String(s) => Dynamic::from(s.clone()),
        serde_json::Value::Array(arr) => {
            let v: rhai::Array = arr.iter().map(json_to_dynamic).collect();
            Dynamic::from(v)
        }
        serde_json::Value::Object(map) => {
            let mut m = rhai::Map::new();
            for (k, v) in map {
                m.insert(k.clone().into(), json_to_dynamic(v));
            }
            Dynamic::from(m)
        }
    }
}

pub(crate) fn dynamic_to_json(d: Dynamic) -> serde_json::Value {
    if d.is_unit() {
        serde_json::Value::Null
    } else if let Some(b) = d.clone().try_cast::<bool>() {
        serde_json::Value::Bool(b)
    } else if let Some(i) = d.clone().try_cast::<i64>() {
        serde_json::Value::Number(i.into())
    } else if let Some(f) = d.clone().try_cast::<f64>() {
        serde_json::json!(f)
    } else if let Some(s) = d.clone().try_cast::<String>() {
        serde_json::Value::String(s)
    } else if let Some(arr) = d.clone().try_cast::<rhai::Array>() {
        serde_json::Value::Array(arr.into_iter().map(dynamic_to_json).collect())
    } else if let Some(map) = d.clone().try_cast::<rhai::Map>() {
        serde_json::Value::Object(
            map.into_iter()
                .map(|(k, v)| (k.to_string(), dynamic_to_json(v)))
                .collect(),
        )
    } else {
        serde_json::Value::String(d.to_string())
    }
}

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

    fn v(pairs: &[(&str, serde_json::Value)]) -> HashMap<String, serde_json::Value> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.clone()))
            .collect()
    }

    // ── eval_condition ────────────────────────────────────────────────────

    #[test]
    fn condition_literal_true() {
        assert!(eval_condition("true", &HashMap::new()).unwrap());
    }

    #[test]
    fn condition_literal_false() {
        assert!(!eval_condition("false", &HashMap::new()).unwrap());
    }

    #[test]
    fn condition_integer_var_eq() {
        let vars = v(&[("status", json!(200i64))]);
        assert!(eval_condition("status == 200", &vars).unwrap());
        assert!(!eval_condition("status == 404", &vars).unwrap());
    }

    #[test]
    fn condition_bool_var() {
        let vars = v(&[("oob_enabled", json!(true))]);
        assert!(eval_condition("oob_enabled", &vars).unwrap());
    }

    #[test]
    fn condition_bool_var_false() {
        let vars = v(&[("oob_enabled", json!(false))]);
        assert!(!eval_condition("oob_enabled", &vars).unwrap());
    }

    #[test]
    fn condition_non_bool_result_coerces_false() {
        // Expression returns integer — as_bool() returns None → false
        assert!(!eval_condition("42", &HashMap::new()).unwrap());
    }

    #[test]
    fn condition_dot_key_flattened_to_underscore() {
        let vars = v(&[("resp.status", json!(200i64))]);
        assert!(eval_condition("resp_status == 200", &vars).unwrap());
    }

    #[test]
    fn condition_stored_result_dot_notation() {
        // A `store_as` result is pushed as one map under its own name: fields are
        // reached with dot notation, never through a flattened `resp_status` (#1103).
        let vars = v(&[(
            "resp",
            json!({"status": 200i64, "headers": {"content-type": "text/html"}}),
        )]);
        assert!(eval_condition("resp.status == 200", &vars).unwrap());
        assert!(eval_condition(r#"resp.headers["content-type"] == "text/html""#, &vars).unwrap());
        // `resp_status` is undefined: eval errors, which the runner treats as false.
        assert!(eval_condition("resp_status == 200", &vars).is_err());
    }

    #[test]
    fn condition_syntax_error() {
        assert!(eval_condition("@!@#$", &HashMap::new()).is_err());
    }

    // ── eval_script ───────────────────────────────────────────────────────

    #[test]
    fn script_returns_last_expression() {
        let mut vars = HashMap::new();
        assert_eq!(eval_script("1 + 1", &mut vars, "s").unwrap(), json!(2i64));
    }

    #[test]
    fn script_mutates_existing_var() {
        let mut vars = v(&[("x", json!(10i64))]);
        eval_script("x = x * 2", &mut vars, "s").unwrap();
        assert_eq!(vars["x"], json!(20i64));
    }

    #[test]
    fn script_string_result() {
        let mut vars = HashMap::new();
        assert_eq!(
            eval_script(r#""hello""#, &mut vars, "s").unwrap(),
            json!("hello")
        );
    }

    #[test]
    fn script_syntax_error() {
        let mut vars = HashMap::new();
        assert!(eval_script("let @@@ = 1;", &mut vars, "s").is_err());
    }

    #[test]
    fn script_reads_nested_result_map_property() {
        // A stored step result is a nested object; the script reaches into it as
        // a Rhai map property (how feeds consume `tcp_send`/`http_request` output).
        let mut vars = v(&[("resp", json!({"response_hex": "0102030405"}))]);
        let out = eval_script("substr(resp.response_hex, 2, 5)", &mut vars, "s").unwrap();
        assert_eq!(out, json!("0203"));
    }

    #[test]
    fn script_cve_2022_24706_challenge_digest() {
        // Regression for the CVE-2022-24706 feed: parse the big-endian u32
        // challenge at byte offset 9 (hex offset 18) of the Erlang 'n' reply,
        // then build the challenge-reply frame from MD5("monster"+challenge).
        let reply_hex = "00166e000500000000010203046e6f63746973406d6f636b";
        let mut vars = v(&[("name_reply", json!({"response_hex": reply_hex}))]);
        let code = r#"
            let challenge = u32be(substr(name_reply.response_hex, 18, 25));
            let digest = md5("monster" + challenge.to_string());
            "00157200000000" + digest
        "#;
        let out = eval_script(code, &mut vars, "s").unwrap();
        // challenge 0x01020304 = 16909060; MD5("monster16909060") is fixed.
        assert_eq!(out, json!("00157200000000b4ae6978053f3042dd26b037a0851ba4"));
    }

    /// Run the shipped `general/smb-signing-not-required` feed's parse script
    /// against a canned SMB2 NEGOTIATE reply (hex) — the feed's own code, so a
    /// broken offset in the YAML fails here, not only end-to-end.
    fn smb2_parse(reply_hex: serde_json::Value) -> serde_json::Value {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/vulnerabilities/general/smb-signing-not-required.yaml");
        let def = crate::loader::load(&path).unwrap();
        let step = def
            .steps
            .iter()
            .find(|s| s.id == "parse-negotiate")
            .expect("parse-negotiate step");
        let mut vars = v(&[("smb", json!({"connected": true, "response_hex": reply_hex}))]);
        eval_script(step.code.as_deref().unwrap(), &mut vars, "s").unwrap()
    }

    // SMB2 NEGOTIATE response prefix: NBSS + 64-byte SMB2 header (status 0,
    // command NEGOTIATE) + StructureSize 65; then SecurityMode + DialectRevision.
    const SMB2_HDR: &str = "000000aefe534d42400000000000000000000100010000000000000000000000\
                            0000000000000000000000000000000000000000000000000000000000000000\
                            000000004100";

    #[test]
    fn script_smb2_negotiate_signing_not_required() {
        let out = smb2_parse(json!(format!("{SMB2_HDR}0100110301006e6f6374")));
        assert_eq!(out["smb2"], json!(true));
        assert_eq!(out["dialect"], json!("3.1.1"));
        assert_eq!(out["dialect_hex"], json!("0311"));
        assert_eq!(out["security_mode"], json!(1));
        assert_eq!(out["signing_required"], json!(false));
        assert_eq!(out["legacy_only"], json!(false));
    }

    #[test]
    fn script_smb2_negotiate_signing_required() {
        let out = smb2_parse(json!(format!("{SMB2_HDR}0300020300006e6f6374")));
        assert_eq!(out["smb2"], json!(true));
        assert_eq!(out["dialect"], json!("3.0.2"));
        assert_eq!(out["signing_required"], json!(true));
    }

    #[test]
    fn script_smb2_negotiate_legacy_only_dialect() {
        let out = smb2_parse(json!(format!("{SMB2_HDR}0100100200006e6f6374")));
        assert_eq!(out["dialect"], json!("2.1"));
        assert_eq!(out["legacy_only"], json!(true));
        assert_eq!(out["signing_required"], json!(false));
    }

    #[test]
    fn script_smb2_negotiate_rejects_non_smb2_replies() {
        // SMB1 reply, short reply, error status, and no reply at all.
        let smb1 = "00000023ff534d4272000000009853c800000000000000000000000000002f4b00000000010000";
        let err_status = SMB2_HDR.replacen("4000000000000000", "4000000022000000", 1);
        // Our own NEGOTIATE request echoed back (an echo service on an "smb" port):
        // SMB2 signature, status 0, command 0 — but no SERVER_TO_REDIR flag and a
        // request StructureSize of 36, so it must not count as a response.
        let echo = "0000009efe534d42400000000000000000000100000000000000000000000000\
                    0000000000000000000000000000000000000000000000000000000000000000\
                    000000002400050001000000000000006e6f637469732d736d622d70726f6265\
                    700000000100000002021002000302031103000001002600000000000100200001\
                    006e6f637469732d707265617574682d696e746567726974792d73616c742d3332";
        // A response-shaped reply with an unknown dialect.
        let unknown_dialect = format!("{SMB2_HDR}0100ffff01006e6f6374");
        for reply in [
            json!(smb1),
            json!("0000"),
            json!(format!("{err_status}0100110301006e6f6374")),
            json!(null),
            json!(echo),
            json!(unknown_dialect),
        ] {
            assert_eq!(smb2_parse(reply.clone())["smb2"], json!(false), "{reply}");
        }
    }

    /// Run the shipped `cisco-smart-install/CVE-2018-0171` feed's parse script
    /// against a canned SMI identify reply (hex) — the feed's own code.
    fn smi_parse(reply_hex: serde_json::Value) -> serde_json::Value {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/vulnerabilities/cisco-smart-install/CVE-2018-0171.yaml");
        let def = crate::loader::load(&path).unwrap();
        let step = def
            .steps
            .iter()
            .find(|s| s.id == "parse-smi")
            .expect("parse-smi step");
        let mut vars = v(&[("smi", json!({"connected": true, "response_hex": reply_hex}))]);
        eval_script(step.code.as_deref().unwrap(), &mut vars, "s").unwrap()
    }

    #[test]
    fn script_smi_identify_response_enabled() {
        // The genuine SMI identify response (first word 0x00000004).
        let out = smi_parse(json!("000000040000000000000003000000080000000100000000"));
        assert_eq!(out["smi_enabled"], json!(true));
        assert_eq!(out["word0"], json!(4));
        assert_eq!(out["word2"], json!(3));
    }

    #[test]
    fn script_smi_identify_rejects_non_smi_replies() {
        for reply in [
            // Our own probe echoed back (first word 0x00000001, not 0x00000004).
            json!("000000010000000100000004000000080000000100000000"),
            // Constant / garbage reply of the right length.
            json!("aaaaaaaabbbbbbbbccccccccddddddddeeeeeeeeffffffff"),
            // Right first word but wrong trailing structure.
            json!("000000040000000000000003000000080000000900000000"),
            // Too short.
            json!("00000004"),
            // No reply at all.
            json!(null),
        ] {
            assert_eq!(
                smi_parse(reply.clone())["smi_enabled"],
                json!(false),
                "{reply}"
            );
        }
    }

    /// Run the shipped `general/CVE-2020-0796` (SMBGhost) feed's parse script
    /// against a canned SMB2 NEGOTIATE reply (hex) — the feed's own code, so a
    /// broken negotiate-context offset in the YAML fails here, not only e2e.
    fn smbghost_parse(reply_hex: serde_json::Value) -> serde_json::Value {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/vulnerabilities/general/CVE-2020-0796.yaml");
        let def = crate::loader::load(&path).unwrap();
        let step = def
            .steps
            .iter()
            .find(|s| s.id == "parse-negotiate")
            .expect("parse-negotiate step");
        let mut vars = v(&[("smb", json!({"connected": true, "response_hex": reply_hex}))]);
        eval_script(step.code.as_deref().unwrap(), &mut vars, "s").unwrap()
    }

    // Canned NEGOTIATE responses from the mock (infra/docker/smbghost-mock),
    // generated by its own byte layout. vuln: 3.1.1 + preauth-integrity +
    // compression context; patched: 3.1.1 + preauth-integrity only; legacy: 3.0.2.
    const SMBGHOST_VULN: &str = "000000c2fe534d4240000000000000000000010001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041000100110302006e6f637469732d736d6267686f7374210000000000000100000001000000010000000000000000000000000000000000800000008000000001002600000000000100200001000000000000000000000000000000000000000000000000000000000000000000000003000a000000000001000000000000000300";
    const SMBGHOST_PATCHED: &str = "000000b0fe534d4240000000000000000000010001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041000100110301006e6f637469732d736d6267686f73742100000000000001000000010000000100000000000000000000000000000000008000000080000000010026000000000001002000010000000000000000000000000000000000000000000000000000000000000000000000";
    const SMBGHOST_LEGACY: &str = "00000080fe534d4240000000000000000000010001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000041000100020300006e6f637469732d736d6267686f73742100000000000001000000010000000100000000000000000000000000000000008000000000000000";

    #[test]
    fn script_smbghost_compression_enabled_is_vulnerable() {
        let out = smbghost_parse(json!(SMBGHOST_VULN));
        assert_eq!(out["smb2"], json!(true));
        assert_eq!(out["dialect"], json!("3.1.1"));
        assert_eq!(out["dialect_hex"], json!("0311"));
        assert_eq!(out["compression_supported"], json!(true));
        assert_eq!(out["compression_algo_count"], json!(1));
        assert_eq!(out["vulnerable"], json!(true));
    }

    #[test]
    fn script_smbghost_compression_disabled_is_clean() {
        // 3.1.1 negotiated but no compression context — patched / DisableCompression.
        let out = smbghost_parse(json!(SMBGHOST_PATCHED));
        assert_eq!(out["smb2"], json!(true));
        assert_eq!(out["dialect"], json!("3.1.1"));
        assert_eq!(out["compression_supported"], json!(false));
        assert_eq!(out["vulnerable"], json!(false));
    }

    #[test]
    fn script_smbghost_non_311_dialect_is_clean() {
        // SMB 3.0.2 server cannot be SMBGhost regardless of anything else.
        let out = smbghost_parse(json!(SMBGHOST_LEGACY));
        assert_eq!(out["smb2"], json!(true));
        assert_eq!(out["dialect"], json!("3.0.2"));
        assert_eq!(out["compression_supported"], json!(false));
        assert_eq!(out["vulnerable"], json!(false));
    }

    #[test]
    fn script_smbghost_rejects_non_smb2_replies() {
        let smb1 = "00000023ff534d4272000000009853c800000000000000000000000000002f4b00000000010000";
        for reply in [json!(smb1), json!("0000"), json!(null)] {
            let out = smbghost_parse(reply.clone());
            assert_eq!(out["smb2"], json!(false), "{reply}");
            assert_eq!(out["vulnerable"], json!(false), "{reply}");
        }
    }

    // ── json_to_dynamic / dynamic_to_json ─────────────────────────────────

    #[test]
    fn null_roundtrip() {
        let d = json_to_dynamic(&serde_json::Value::Null);
        assert_eq!(dynamic_to_json(d), serde_json::Value::Null);
    }

    #[test]
    fn bool_roundtrip() {
        let d = json_to_dynamic(&json!(true));
        assert_eq!(dynamic_to_json(d), json!(true));
    }

    #[test]
    fn integer_roundtrip() {
        let d = json_to_dynamic(&json!(42i64));
        assert_eq!(dynamic_to_json(d), json!(42i64));
    }

    #[test]
    fn string_roundtrip() {
        let d = json_to_dynamic(&json!("hello"));
        assert_eq!(dynamic_to_json(d), json!("hello"));
    }

    #[test]
    fn float_dynamic_to_json_is_number() {
        let d = Dynamic::from(2.5f64);
        assert!(dynamic_to_json(d).is_number());
    }

    #[test]
    fn array_roundtrip() {
        let v = json!([1i64, "a", [true, null]]);
        assert_eq!(dynamic_to_json(json_to_dynamic(&v)), v);
    }

    #[test]
    fn object_roundtrip() {
        let v = json!({"connected": true, "responses": ["x"], "nested": {"n": 1i64}});
        assert_eq!(dynamic_to_json(json_to_dynamic(&v)), v);
    }

    // ── #393: script must not clobber stored-result objects ──────────────

    #[test]
    fn script_preserves_untouched_stored_object() {
        let stored = json!({
            "connected": true,
            "response_hex": "524642",
            "responses": ["RFB 003.008"],
            "banner": null,
            "port": 18446744073709551615u64
        });
        let mut vars = v(&[("vnc", stored.clone()), ("x", json!(1i64))]);
        eval_script("let y = 42; y", &mut vars, "s").unwrap();
        assert_eq!(vars["vnc"], stored);
        assert_eq!(
            crate::expr::interpolate("{{vnc.response_hex}}", &vars).unwrap(),
            "524642"
        );
        assert!(eval_condition("vnc.connected == true", &vars).unwrap());
    }

    #[test]
    fn script_mutated_object_written_back_as_object() {
        let mut vars = v(&[("r", json!({"a": 1i64}))]);
        eval_script("r.b = 2; r", &mut vars, "s").unwrap();
        assert_eq!(vars["r"], json!({"a": 1i64, "b": 2i64}));
    }
}