eggsec-nse 0.3.0

Standalone Lua-based Nmap Scripting Engine runtime
Documentation
//! NSE datetime library wrapper
//!
//! Date and time utilities for NSE scripts.
//! Based on Nmap's datetime library.

use mlua::{Lua, Result as LuaResult};

use crate::capabilities::NseCapabilityContext;

pub fn register_datetime_library(
    lua: &Lua,
    capability_ctx: &NseCapabilityContext,
) -> LuaResult<()> {
    register_datetime_library_with_services(
        lua,
        capability_ctx,
        &crate::providers::NseHostServices::native(),
    )
}

/// Provider-backed datetime registration.
///
/// Clock reads go through [`crate::providers::broker_unix_timestamp`] so
/// injected fixed clocks drive NSE scripts deterministically while
/// capability/cancellation/accounting semantics stay centralized.
pub fn register_datetime_library_with_services(
    lua: &Lua,
    capability_ctx: &NseCapabilityContext,
    services: &crate::providers::NseHostServices,
) -> LuaResult<()> {
    let globals = lua.globals();

    let datetime = lua.create_table().map_err(|e| {
        mlua::Error::RuntimeError(format!("Failed to create datetime table: {}", e))
    })?;

    let cap_ctx = capability_ctx.clone();
    let svc = services.clone();
    datetime.set(
        "now",
        lua.create_function(move |_lua, _: ()| {
            crate::providers::broker_unix_timestamp(&cap_ctx, &svc, "datetime.now")
                .map_err(|e| mlua::Error::RuntimeError(format!("Time clock access denied: {e}")))
        })?,
    )?;

    let cap_ctx = capability_ctx.clone();
    let svc = services.clone();
    datetime.set(
        "current_time",
        lua.create_function(move |_lua, _: ()| {
            let ts =
                crate::providers::broker_unix_timestamp(&cap_ctx, &svc, "datetime.current_time")
                    .map_err(|e| {
                        mlua::Error::RuntimeError(format!("Time clock access denied: {e}"))
                    })?;
            let dt = chrono::DateTime::from_timestamp(ts, 0)
                .map(|d| d.format("%Y-%m-%d %H:%M:%S").to_string())
                .unwrap_or_default();
            Ok(dt)
        })?,
    )?;

    let cap_ctx = capability_ctx.clone();
    let svc = services.clone();
    datetime.set(
        "timestamp",
        lua.create_function(move |_lua, _: ()| {
            crate::providers::broker_unix_timestamp(&cap_ctx, &svc, "datetime.timestamp")
                .map_err(|e| mlua::Error::RuntimeError(format!("Time clock access denied: {e}")))
        })?,
    )?;

    datetime.set(
        "parse_timespec",
        lua.create_function(|_lua, timespec: String| {
            let timespec = timespec.to_lowercase();

            let seconds: i64 = if timespec.contains('s') {
                timespec.replace("s", "").parse().unwrap_or(0)
            } else if timespec.contains('m') {
                timespec.replace("m", "").parse::<i64>().unwrap_or(0) * 60
            } else if timespec.contains('h') {
                timespec.replace("h", "").parse::<i64>().unwrap_or(0) * 3600
            } else if timespec.contains('d') {
                timespec.replace("d", "").parse::<i64>().unwrap_or(0) * 86400
            } else {
                timespec.parse().unwrap_or(0)
            };

            Ok(seconds)
        })?,
    )?;

    datetime.set(
        "format_time",
        lua.create_function(|_lua, (timestamp, format): (i64, String)| {
            use chrono::{TimeZone, Utc};
            let dt = Utc.timestamp_opt(timestamp, 0).single();
            match dt {
                Some(d) => Ok(d.format(&format).to_string()),
                None => Ok("".to_string()),
            }
        })?,
    )?;

    datetime.set(
        "format_date",
        lua.create_function(|_lua, (timestamp, format): (i64, String)| {
            use chrono::{TimeZone, Utc};
            let dt = Utc.timestamp_opt(timestamp, 0).single();
            match dt {
                Some(d) => Ok(d.format(&format).to_string()),
                None => Ok("".to_string()),
            }
        })?,
    )?;

    let cap_ctx = capability_ctx.clone();
    let svc = services.clone();
    datetime.set(
        "isotime",
        lua.create_function(move |_lua, timestamp: Option<i64>| {
            let ts = if let Some(ts) = timestamp {
                ts
            } else {
                crate::providers::broker_unix_timestamp(&cap_ctx, &svc, "datetime.isotime")
                    .map_err(|e| {
                        mlua::Error::RuntimeError(format!("Time clock access denied: {e}"))
                    })?
            };
            use chrono::{TimeZone, Utc};
            let dt = Utc.timestamp_opt(ts, 0).single();
            match dt {
                Some(d) => Ok(d.to_rfc3339()),
                None => Ok("".to_string()),
            }
        })?,
    )?;

    datetime.set(
        "to_epoch",
        lua.create_function(
            |_lua, (year, month, day, hour, min, sec): (i32, i32, i32, i32, i32, i32)| {
                use chrono::{TimeZone, Utc};
                let dt = Utc
                    .with_ymd_and_hms(
                        year,
                        month as u32,
                        day as u32,
                        hour as u32,
                        min as u32,
                        sec as u32,
                    )
                    .single();
                match dt {
                    Some(d) => Ok(d.timestamp()),
                    None => Ok(0i64),
                }
            },
        )?,
    )?;

    datetime.set(
        "diff",
        lua.create_function(|_lua, (t1, t2): (i64, i64)| Ok(t1 - t2))?,
    )?;

    globals.set("datetime", datetime)?;
    Ok(())
}