noctis 0.6.0

Open-source black-box vulnerability scanner: readable YAML checks that prove each bug on the live service, QoD-graded findings, REST API.
//! Crypto / encoding builtin functions for the feed engine.
//!
//! Registered into the Rhai engine alongside the string builtins so feeds can
//! compute digests, HMACs and base64 inside `script` steps and `condition:`
//! expressions (e.g. verify a signed token, derive an expected hash, decode a
//! base64 blob from a response). All take/return strings; digests return lowercase
//! hex. Backed by the RustCrypto crates.

use base64::engine::general_purpose::STANDARD;
use base64::Engine as _;
use hmac::{Hmac, KeyInit, Mac};
use rhai::Engine;
use sha2::{Digest, Sha256};

fn to_hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

fn digest_hex<D: Digest>(data: &str) -> String {
    let mut h = D::new();
    h.update(data.as_bytes());
    to_hex(&h.finalize())
}

fn hmac_sha256_hex(key: &str, msg: &str) -> String {
    // new_from_slice accepts any key length for HMAC, so this cannot fail here.
    match Hmac::<Sha256>::new_from_slice(key.as_bytes()) {
        Ok(mut mac) => {
            mac.update(msg.as_bytes());
            to_hex(&mac.finalize().into_bytes())
        }
        Err(_) => String::new(),
    }
}

/// HMAC-SHA1 over RAW bytes: key and message are hex strings (whitespace and
/// `:` ignored), the MAC is returned as lowercase hex. Binary protocols (IPMI
/// RAKP, SNMPv3 …) key and sign byte strings that are not valid UTF-8, which the
/// text-in `hmac_sha256` cannot carry. Malformed hex yields "".
fn hmac_sha1_hex(key_hex: &str, msg_hex: &str) -> String {
    let (Some(key), Some(msg)) = (decode_hex_strict(key_hex), decode_hex_strict(msg_hex)) else {
        return String::new();
    };
    match Hmac::<sha1::Sha1>::new_from_slice(&key) {
        Ok(mut mac) => {
            mac.update(&msg);
            to_hex(&mac.finalize().into_bytes())
        }
        Err(_) => String::new(),
    }
}

/// MD5 / SHA-1 over RAW bytes given as hex; digest as lowercase hex. The text-in
/// `md5` / `sha1` hash the UTF-8 of their argument, which cannot carry binary
/// key material (RDP Standard Security key derivation hashes random bytes).
/// Malformed hex yields "".
fn raw_digest_hex<D: Digest>(data_hex: &str) -> String {
    match decode_hex_strict(data_hex) {
        Some(bytes) => {
            let mut h = D::new();
            h.update(&bytes);
            to_hex(&h.finalize())
        }
        None => String::new(),
    }
}

/// `rc4_hex(key_hex, data_hex, skip)` — RC4 over raw bytes: the keystream of
/// `key` with its first `skip` bytes discarded, XORed with `data`, as hex. RC4
/// is a stream cipher whose state runs across packets, so a feed that encrypts
/// several packets with one key passes the number of bytes it already
/// encrypted as `skip` (RDP Standard Security, MS-RDPBCGR 5.3.6). Malformed
/// hex, an empty key, a key over 256 bytes or a `skip` outside 0..=16 MiB
/// yields "".
fn rc4_hex(key_hex: &str, data_hex: &str, skip: i64) -> String {
    let (Some(key), Some(data)) = (decode_hex_strict(key_hex), decode_hex_strict(data_hex)) else {
        return String::new();
    };
    // `skip` runs natively, outside Rhai's operation budget: cap it (16 MiB).
    if key.is_empty() || key.len() > 256 || !(0..=16 << 20).contains(&skip) {
        return String::new();
    }
    let mut s: [u8; 256] = std::array::from_fn(|i| i as u8);
    let mut j: u8 = 0;
    for i in 0..256 {
        j = j.wrapping_add(s[i]).wrapping_add(key[i % key.len()]);
        s.swap(i, j as usize);
    }
    let (mut i, mut j) = (0u8, 0u8);
    let mut next = || {
        i = i.wrapping_add(1);
        j = j.wrapping_add(s[i as usize]);
        s.swap(i as usize, j as usize);
        s[s[i as usize].wrapping_add(s[j as usize]) as usize]
    };
    for _ in 0..skip {
        next();
    }
    let out: Vec<u8> = data.iter().map(|b| b ^ next()).collect();
    to_hex(&out)
}

/// `rsa_public_le_hex(msg_hex, exp_hex, mod_hex)` — raw (unpadded) RSA public
/// operation msg^exp mod n, every operand and the result as LITTLE-endian hex,
/// the result zero-padded to the modulus length. That is the byte order and
/// padding of the RDP Standard Security client random (MS-RDPBCGR 5.3.4.1):
/// the server's proprietary certificate carries a little-endian modulus and
/// exponent. A zero or malformed modulus, or one over 8192 bits (exponent over
/// 64 bytes), yields "".
fn rsa_public_le_hex(msg_hex: &str, exp_hex: &str, mod_hex: &str) -> String {
    use openssl::bn::{BigNum, BigNumContext};
    let (Some(mut m), Some(mut e), Some(mut n)) = (
        decode_hex_strict(msg_hex),
        decode_hex_strict(exp_hex),
        decode_hex_strict(mod_hex),
    ) else {
        return String::new();
    };
    // Bounded so a hostile server's certificate cannot stall the scan in modexp.
    if n.len() > 1024 || e.len() > 64 || m.len() > 1024 {
        return String::new();
    }
    let width = n.len();
    m.reverse();
    e.reverse();
    n.reverse();
    let run = || -> Result<Vec<u8>, openssl::error::ErrorStack> {
        let (m, e, n) = (
            BigNum::from_slice(&m)?,
            BigNum::from_slice(&e)?,
            BigNum::from_slice(&n)?,
        );
        let mut r = BigNum::new()?;
        let mut ctx = BigNumContext::new()?;
        r.mod_exp(&m, &e, &n, &mut ctx)?;
        Ok(r.to_vec())
    };
    if n.iter().all(|b| *b == 0) {
        return String::new();
    }
    match run() {
        Ok(mut be) => {
            be.reverse();
            be.resize(width, 0);
            to_hex(&be)
        }
        Err(_) => String::new(),
    }
}

/// Register the crypto/encoding builtins onto `engine`.
pub fn register(engine: &mut Engine) {
    engine.register_fn("md5", |s: &str| digest_hex::<md5::Md5>(s));
    engine.register_fn("sha1", |s: &str| digest_hex::<sha1::Sha1>(s));
    engine.register_fn("sha256", |s: &str| digest_hex::<Sha256>(s));
    engine.register_fn("sha512", |s: &str| digest_hex::<sha2::Sha512>(s));
    engine.register_fn("hmac_sha256", hmac_sha256_hex);
    engine.register_fn("hmac_sha1_hex", hmac_sha1_hex);
    engine.register_fn("md5_hex", raw_digest_hex::<md5::Md5>);
    engine.register_fn("sha1_hex", raw_digest_hex::<sha1::Sha1>);
    engine.register_fn("rc4_hex", rc4_hex);
    engine.register_fn("rsa_public_le_hex", rsa_public_le_hex);

    engine.register_fn("base64_encode", |s: &str| STANDARD.encode(s.as_bytes()));
    // Lossy: invalid base64 or non-UTF8 output yields "" (feeds test the result).
    engine.register_fn("base64_decode", |s: &str| {
        STANDARD
            .decode(s.as_bytes())
            .map(|b| String::from_utf8_lossy(&b).into_owned())
            .unwrap_or_default()
    });
    // base64_encode_hex(hex) → base64 of the RAW bytes a hex string decodes to.
    // Bridges the pack/`p*`/`hexstr` builtins (which all work in hex) to base64,
    // so a feed can assemble a binary blob as hex and emit it base64-encoded in a
    // text field (e.g. a serialized-object payload carried inside a SOAP body).
    // Whitespace and `:` separators are ignored; malformed hex yields "".
    engine.register_fn("base64_encode_hex", |h: &str| match decode_hex_strict(h) {
        Some(bytes) => STANDARD.encode(&bytes),
        None => String::new(),
    });
}

/// Decode a hex string (whitespace/`:` ignored) into bytes; `None` on bad input.
fn decode_hex_strict(s: &str) -> Option<Vec<u8>> {
    let cleaned: String = s
        .chars()
        .filter(|c| !c.is_whitespace() && *c != ':')
        .collect();
    // Non-ASCII input would split a char in the byte slicing below (panic).
    if !cleaned.len().is_multiple_of(2) || !cleaned.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let mut out = Vec::with_capacity(cleaned.len() / 2);
    let bytes = cleaned.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match u8::from_str_radix(&cleaned[i..i + 2], 16) {
            Ok(b) => out.push(b),
            Err(_) => return None,
        }
        i += 2;
    }
    Some(out)
}

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

    fn eng() -> Engine {
        let mut e = Engine::new();
        register(&mut e);
        e
    }

    fn eval_str(code: &str) -> String {
        eng().eval::<String>(code).expect("eval ok")
    }

    #[test]
    fn digests_match_known_vectors() {
        assert_eq!(eval_str(r#"md5("")"#), "d41d8cd98f00b204e9800998ecf8427e");
        assert_eq!(
            eval_str(r#"sha1("abc")"#),
            "a9993e364706816aba3e25717850c26c9cd0d89d"
        );
        assert_eq!(
            eval_str(r#"sha256("abc")"#),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
        assert_eq!(
            eval_str(r#"sha512("abc")"#),
            "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a\
2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"
        );
    }

    #[test]
    fn hmac_sha256_known_vector() {
        // RFC 4231-style: key "key", data "The quick brown fox jumps over the lazy dog"
        assert_eq!(
            eval_str(r#"hmac_sha256("key", "The quick brown fox jumps over the lazy dog")"#),
            "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"
        );
    }

    #[test]
    fn hmac_sha1_hex_known_vectors() {
        // RFC 2202 test case 1: key = 0x0b * 20, data = "Hi There".
        assert_eq!(
            eval_str(
                r#"hmac_sha1_hex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "4869205468657265")"#
            ),
            "b617318655057264e28bc0b6fb378c8ef146be00"
        );
        // RFC 2202 test case 2: key "Jefe", data "what do ya want for nothing?".
        assert_eq!(
            eval_str(
                r#"hmac_sha1_hex("4a656665", "7768617420646f2079612077616e7420666f72206e6f7468696e673f")"#
            ),
            "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"
        );
        // Empty key (blank password) is valid HMAC input.
        assert_eq!(
            eval_str(r#"hmac_sha1_hex("", "")"#),
            "fbdb1d1b18aa6c08324b7d64b71fb76370690e1d"
        );
        // Non-UTF-8 bytes are fine; malformed hex yields "".
        assert_eq!(strlen_of(r#"hmac_sha1_hex("ff00", "80ff")"#), 40);
        assert_eq!(eval_str(r#"hmac_sha1_hex("zz", "00")"#), "");
        assert_eq!(eval_str(r#"hmac_sha1_hex("00", "0")"#), "");
        // Non-ASCII input is malformed, not a panic.
        assert_eq!(eval_str(r#"hmac_sha1_hex("a\u00e90", "00")"#), "");
    }

    #[test]
    fn raw_digests_hash_bytes_not_text() {
        // "abc" as hex → the usual vectors.
        assert_eq!(
            eval_str(r#"md5_hex("616263")"#),
            "900150983cd24fb0d6963f7d28e17f72"
        );
        assert_eq!(
            eval_str(r#"sha1_hex("616263")"#),
            "a9993e364706816aba3e25717850c26c9cd0d89d"
        );
        // Non-UTF-8 bytes hash as bytes.
        assert_eq!(
            eval_str(r#"md5_hex("ff")"#),
            "00594fd4f42ba43fc1ca0427a0576295"
        );
        assert_eq!(
            eval_str(r#"md5_hex("")"#),
            "d41d8cd98f00b204e9800998ecf8427e"
        );
        assert_eq!(eval_str(r#"sha1_hex("0")"#), "");
    }

    #[test]
    fn rc4_known_vectors_and_skip() {
        // Wikipedia vectors: Key/"Plaintext", Wiki/"pedia", Secret/"Attack at dawn".
        assert_eq!(
            eval_str(r#"rc4_hex("4b6579", "506c61696e74657874", 0)"#),
            "bbf316e8d940af0ad3"
        );
        assert_eq!(
            eval_str(r#"rc4_hex("57696b69", "7065646961", 0)"#),
            "1021bf0420"
        );
        assert_eq!(
            eval_str(r#"rc4_hex("536563726574", "41747461636b206174206461776e", 0)"#),
            "45a01f645fc35b383552544b9bf5"
        );
        // Encrypting in two parts with skip == one pass.
        assert_eq!(eval_str(r#"rc4_hex("4b6579", "506c61", 0)"#), "bbf316");
        assert_eq!(
            eval_str(r#"rc4_hex("4b6579", "696e74657874", 3)"#),
            "e8d940af0ad3"
        );
        assert_eq!(eval_str(r#"rc4_hex("", "00", 0)"#), "");
        assert_eq!(eval_str(r#"rc4_hex("4b", "zz", 0)"#), "");
        assert_eq!(eval_str(r#"rc4_hex("4b", "00", -1)"#), "");
        assert_eq!(eval_str(r#"rc4_hex("4b", "00", 16777217)"#), "");
    }

    #[test]
    fn rsa_public_le_known_vector() {
        // n = 3233 (61*53), e = 17, m = 65 → 2790 (textbook RSA). LE hex: n = a10c,
        // e = 11, m = 41, c = 0x0ae6 → e60a.
        assert_eq!(eval_str(r#"rsa_public_le_hex("41", "11", "a10c")"#), "e60a");
        // Result padded to the modulus width: 2^17 mod 3233 = 1752 = 0x06d8.
        assert_eq!(
            eval_str(r#"rsa_public_le_hex("02", "11", "a10c0000")"#),
            "d8060000"
        );
        assert_eq!(eval_str(r#"rsa_public_le_hex("02", "11", "0000")"#), "");
        assert_eq!(eval_str(r#"rsa_public_le_hex("02", "1", "a10c")"#), "");
        // Oversized modulus is refused (8193 bits).
        let big = format!(r#"rsa_public_le_hex("02", "11", "{}")"#, "f".repeat(2050));
        assert_eq!(eval_str(&big), "");
    }

    fn strlen_of(code: &str) -> usize {
        eval_str(code).len()
    }

    #[test]
    fn base64_roundtrip() {
        assert_eq!(eval_str(r#"base64_encode("hello")"#), "aGVsbG8=");
        assert_eq!(eval_str(r#"base64_decode("aGVsbG8=")"#), "hello");
        assert_eq!(eval_str(r#"base64_decode("!!not base64!!")"#), ""); // invalid → ""
    }

    #[test]
    fn base64_encode_hex_known_vectors() {
        // "hello" == 68656c6c6f → aGVsbG8=
        assert_eq!(eval_str(r#"base64_encode_hex("68656c6c6f")"#), "aGVsbG8=");
        // Raw binary that is NOT valid UTF-8 (Java serialization magic ac ed 00 05)
        // still encodes correctly — this is the whole point of the builtin.
        assert_eq!(eval_str(r#"base64_encode_hex("aced0005")"#), "rO0ABQ==");
        // separators ignored
        assert_eq!(eval_str(r#"base64_encode_hex("ac:ed 00 05")"#), "rO0ABQ==");
        // odd length / bad hex → ""
        assert_eq!(eval_str(r#"base64_encode_hex("abc")"#), "");
        assert_eq!(eval_str(r#"base64_encode_hex("zz")"#), "");
    }
}