noctis 0.5.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(),
    }
}

/// 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("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")"#), "");
    }

    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")"#), "");
    }
}