Skip to main content

eggsec_nse/
lib.rs

1//! NSE (Nmap Scripting Engine) support for Eggsec
2//!
3//! This module provides the ability to run Nmap NSE scripts using a Lua interpreter.
4//! It leverages mlua (Lua 5.4) and wraps existing Eggsec functionality
5//! to provide NSE-compatible libraries.
6
7use ipnetwork::IpNetwork;
8use std::net::IpAddr;
9use std::path::PathBuf;
10
11#[cfg(all(feature = "nse", target_family = "unix"))]
12#[link(name = "z")]
13unsafe extern "C" {}
14
15/// Install the ring crypto provider used by rustls-backed reqwest clients.
16pub fn install_tls_provider() {
17    use std::sync::Once;
18    static INIT: Once = Once::new();
19    INIT.call_once(|| {
20        // `install_default()` returns Err if another provider is already
21        // installed; either outcome is acceptable because the process-level
22        // provider must simply exist when rustls clients are constructed.
23        if rustls::crypto::ring::default_provider()
24            .install_default()
25            .is_err()
26        {
27            tracing::debug!("rustls default provider already installed; keeping existing");
28        }
29    });
30}
31
32/// Configuration for running NSE scripts.
33pub struct NseConfig {
34    pub target: String,
35    pub script: String,
36    pub script_args: Option<String>,
37    pub script_file: Option<String>,
38    pub json: bool,
39    pub verbose: bool,
40}
41
42impl NseConfig {
43    pub fn new(
44        target: &str,
45        script: &str,
46        script_args: Option<&str>,
47        script_file: Option<&str>,
48        json: bool,
49        verbose: bool,
50    ) -> Self {
51        Self {
52            target: target.to_string(),
53            script: script.to_string(),
54            script_args: script_args.map(|s| s.to_string()),
55            script_file: script_file.map(|s| s.to_string()),
56            json,
57            verbose,
58        }
59    }
60}
61
62/// Sandbox configuration for restricting NSE Lua script capabilities.
63///
64/// When sandboxing is enabled, dangerous operations like `io.popen` (arbitrary
65/// command execution) and unrestricted filesystem access are blocked or limited.
66#[derive(Debug, Clone)]
67pub struct SandboxConfig {
68    /// Whether sandboxing is enabled.
69    pub enabled: bool,
70    /// If set, restrict file operations to this directory.
71    pub allowed_dir: Option<PathBuf>,
72    /// If non-empty, only these commands are allowed via `io.popen`.
73    /// If empty and sandbox is enabled, `io.popen` is fully blocked.
74    pub allowed_commands: Vec<String>,
75    /// Whether to log sandbox violations instead of blocking them.
76    pub log_violations: bool,
77    /// If non-empty, only network connections to these CIDR ranges are allowed.
78    /// If empty and sandbox is enabled, socket connections are allowed but a warning is logged.
79    pub allowed_networks: Vec<IpNetwork>,
80}
81
82impl Default for SandboxConfig {
83    fn default() -> Self {
84        Self {
85            // Sandbox behavior is controlled by the `sandbox` feature.
86            enabled: cfg!(feature = "sandbox"),
87            allowed_dir: Some(PathBuf::from("/tmp/eggsec-nse")),
88            allowed_commands: Vec::new(),
89            log_violations: true,
90            allowed_networks: Vec::new(),
91        }
92    }
93}
94
95impl SandboxConfig {
96    fn allowed_root(&self) -> Option<PathBuf> {
97        let dir = self.allowed_dir.as_ref()?;
98        // Return the raw path; canonicalization is checked per-path in get_allowed_path().
99        // This allows the sandbox to reference a not-yet-created directory.
100        Some(dir.clone())
101    }
102
103    /// Create a sandbox config with sandboxing enabled and default settings.
104    pub fn enabled() -> Self {
105        Self {
106            enabled: true,
107            ..Default::default()
108        }
109    }
110
111    /// Check if a file path is allowed under the sandbox and return the canonical path.
112    ///
113    /// This method canonicalizes the path and verifies it starts with the allowed root
114    /// using path-component semantics (`Path::strip_prefix` / `Path::starts_with` on
115    /// canonical paths only). String-prefix fallback is never used.
116    ///
117    /// Returns `Some(canonical_path)` if allowed, `None` if blocked or invalid.
118    ///
119    /// # Security Note
120    /// The returned canonical path must be used for actual file operations to avoid
121    /// TOCTOU (Time-of-Check-Time-of-Use) vulnerabilities. A separate check followed
122    /// by operations on the original path could allow symlink attacks.
123    pub fn get_allowed_path(&self, path: &str) -> Option<PathBuf> {
124        if !self.enabled {
125            return Some(PathBuf::from(path));
126        }
127
128        // Sandbox enabled but no allowed_dir configured — allow all paths
129        let Some(allowed_dir) = self.allowed_root() else {
130            return Some(PathBuf::from(path));
131        };
132
133        let path_buf = PathBuf::from(path);
134
135        // Try to canonicalize the path directly
136        if let Ok(canonical) = path_buf.canonicalize() {
137            if canonical.starts_with(&allowed_dir) {
138                return Some(canonical);
139            }
140            return None;
141        }
142
143        // File doesn't exist — try canonicalizing the parent
144        if let Some(parent) = path_buf.parent() {
145            if let Ok(canonical_parent) = parent.canonicalize() {
146                if canonical_parent.starts_with(&allowed_dir) {
147                    return Some(canonical_parent.join(path_buf.file_name()?));
148                }
149            }
150        }
151
152        // Cannot canonicalize path or parent — reject (no string-prefix fallback)
153        None
154    }
155
156    /// Check if a command is allowed via `io.popen`.
157    pub fn is_command_allowed(&self, cmd: &str) -> bool {
158        if !self.enabled {
159            return true;
160        }
161
162        if self.allowed_commands.is_empty() {
163            return false;
164        }
165
166        // Block commands containing shell metacharacters to prevent injection
167        if cmd.contains(';')
168            || cmd.contains('|')
169            || cmd.contains('&')
170            || cmd.contains('$')
171            || cmd.contains('`')
172            || cmd.contains('\n')
173            || cmd.contains('\r')
174        {
175            return false;
176        }
177
178        let cmd_name = cmd.split_whitespace().next().unwrap_or(cmd);
179        self.allowed_commands
180            .iter()
181            .any(|allowed| cmd_name == allowed)
182    }
183
184    /// Check if a network target IP is allowed under the sandbox.
185    ///
186    /// Returns `true` if:
187    /// - Sandbox is disabled
188    /// - `allowed_networks` is empty (allow all with warning)
189    /// - The IP matches any network in `allowed_networks`
190    ///
191    /// Returns `false` if the IP does not match any allowed network.
192    pub fn is_network_allowed(&self, ip: IpAddr) -> bool {
193        if !self.enabled {
194            return true;
195        }
196
197        if self.allowed_networks.is_empty() {
198            return true;
199        }
200
201        self.allowed_networks
202            .iter()
203            .any(|network| network.contains(ip))
204    }
205
206    /// Check if a network target host is allowed.
207    ///
208    /// This resolves the hostname and checks the resulting IP against allowed networks.
209    /// Returns `false` if resolution fails while an allowlist is configured.
210    ///
211    /// # Security Note - DNS Rebinding
212    /// This method checks if ANY resolved IP is allowed, but the actual connection
213    /// may use a DIFFERENT IP if DNS changes between check and connection time.
214    /// For sensitive operations, use `resolve_host()` immediately before connecting
215    /// to get the actual IPs that will be used, and ensure DNS hasn't changed.
216    pub fn is_host_allowed(&self, host: &str) -> bool {
217        !self.resolve_host(host).is_empty()
218    }
219
220    /// Resolve a hostname to a list of IP addresses.
221    ///
222    /// # Security Note - DNS Rebinding
223    /// DNS responses can change between calls. For sandbox enforcement, you should:
224    /// 1. Call this method to resolve the host
225    /// 2. Immediately use one of the returned IPs for the connection
226    /// 3. Do not re-resolve the same hostname before connecting
227    ///
228    /// If sandboxing is disabled or no networks are restricted, returns all resolved IPs.
229    /// If resolution fails or no IPs match the allowlist, returns an empty vector.
230    pub fn resolve_host(&self, host: &str) -> Vec<IpAddr> {
231        use std::net::ToSocketAddrs;
232
233        if !self.enabled {
234            if let Ok(addrs) = format!("{}:0", host).to_socket_addrs() {
235                return addrs.map(|a| a.ip()).collect();
236            }
237            return Vec::new();
238        }
239
240        if self.allowed_networks.is_empty() {
241            if let Ok(addrs) = format!("{}:0", host).to_socket_addrs() {
242                return addrs.map(|a| a.ip()).collect();
243            }
244            return Vec::new();
245        }
246
247        let Ok(addrs) = format!("{}:0", host).to_socket_addrs() else {
248            return Vec::new();
249        };
250
251        addrs
252            .map(|a| a.ip())
253            .filter(|ip| self.is_network_allowed(*ip))
254            .collect()
255    }
256}
257
258#[cfg(feature = "nse")]
259pub mod async_executor;
260#[cfg(feature = "nse")]
261pub mod brokered_stream;
262#[cfg(feature = "nse")]
263pub mod capabilities;
264#[cfg(feature = "nse")]
265pub mod context;
266#[cfg(feature = "nse")]
267pub mod cve;
268pub mod effect_manifest;
269#[cfg(feature = "nse")]
270pub mod executor;
271#[cfg(feature = "nse")]
272pub mod executor_core;
273#[cfg(feature = "nse")]
274pub mod format;
275pub mod limits;
276pub mod output;
277pub mod profile;
278#[cfg(feature = "nse")]
279pub mod providers;
280#[cfg(feature = "nse")]
281pub mod public_api;
282#[cfg(feature = "nse")]
283pub mod report;
284pub mod resolver;
285#[cfg(feature = "nse")]
286pub mod run;
287#[cfg(feature = "nse")]
288pub mod wrappers;
289
290#[cfg(feature = "nse")]
291pub mod libraries;
292
293#[cfg(feature = "nse")]
294pub use async_executor::AsyncNseExecutor;
295#[cfg(feature = "nse")]
296pub use capabilities::{
297    NseCapabilityContext, NseCapabilityDecision, NseCapabilityEvent, NseCapabilityKind,
298    NseCapabilityRequest,
299};
300#[cfg(feature = "nse")]
301pub use executor::NseExecutor;
302#[cfg(feature = "nse")]
303pub use executor_core::ExecutorCore;
304#[cfg(feature = "nse")]
305pub use executor_core::SandboxMetrics;
306#[cfg(feature = "nse")]
307pub use executor_core::{default_module_policy, default_script_policy};
308#[cfg(feature = "nse")]
309pub use limits::{
310    NseCancellationToken, NseExecutionLimits, NseExecutionStats, NseLimitViolation,
311    NseResourceCounters,
312};
313
314pub use profile::{
315    NseExecutionProfileKind, NseModulePolicy, NseNetworkPolicy, NseScriptPolicy,
316    ResolvedNseExecutionProfile, ScopeInput,
317};
318
319pub use resolver::{
320    is_builtin_script, validate_nse_module_name, NseLoadDiagnostic, NseLoadError, NseModuleName,
321    NseScriptSource, ResolvedNseModule, ResolvedNseScript, ScriptResolver,
322};
323
324pub use effect_manifest::{
325    automated_library_eligibility, classified_libraries, classify, eligibility_counts,
326    eligible_for_profile, is_automated_library_safe, is_automated_profile, EligibilityCounts,
327    LibraryEffectEntry, NseAutomatedLibraryEligibility,
328};
329
330pub use resolver::registry::{
331    all_libraries, find_library, libraries_by_category, libraries_missing_from_nmap,
332    libraries_with_side_effects, registry_count, sandbox_policy_for_library, EnforcementStatus,
333    NseFallbackBehavior, NseLibraryCategory, NseLibraryDescriptor, NseSandboxSideEffect,
334};
335
336#[cfg(feature = "nse")]
337pub use report::{
338    NseCapabilityEventSummary, NseCompatibilitySummary, NseEvidenceItem, NseEvidenceKind,
339    NseExecutionStatsSummary, NseLibraryUseReport, NseLimitsSummary, NseOutputSummary,
340    NseProfileSummary, NseRequiredModuleReport, NseRequiredModuleSource,
341    NseResolverDiagnosticSummary, NseResolverSummary, NseRuleEvaluationReport,
342    NseRunCompatibilityStatus, NseRunFidelity, NseRunReport, NseSandboxSummary,
343    NseScriptSourceSummary,
344};
345
346#[cfg(feature = "nse")]
347pub use context::{NseContextSource, NseHostContext, NsePortContext, NseServiceContext};
348#[cfg(feature = "nse")]
349pub use providers::{
350    broker_dns_lookup, broker_env_var, broker_fs_create_dir_all, broker_fs_current_dir,
351    broker_fs_exists, broker_fs_hard_link, broker_fs_metadata, broker_fs_open, broker_fs_read,
352    broker_fs_read_dir, broker_fs_read_link, broker_fs_read_to_string, broker_fs_remove_dir,
353    broker_fs_remove_file, broker_fs_rename, broker_fs_resolve, broker_fs_set_current_dir,
354    broker_fs_set_readonly, broker_fs_set_unix_mode, broker_fs_symlink, broker_fs_symlink_metadata,
355    broker_fs_write, broker_http_request, broker_is_privileged, broker_network_interfaces,
356    broker_process_run, broker_process_spawn, broker_random_f64, broker_random_fill,
357    broker_random_u32, broker_resolve_and_select, broker_tcp_connect, broker_tcp_connect_endpoint,
358    broker_tcp_receive, broker_tcp_send, broker_temp_dir, broker_udp_connect,
359    broker_udp_connect_endpoint, broker_udp_receive, broker_udp_send, broker_unix_timestamp,
360    CountingClockProvider, CountingDnsProvider, CountingEnvironmentProvider,
361    CountingFilesystemProvider, CountingHttpProvider, CountingProcessProvider,
362    CountingRandomProvider, CountingTcpSocketProvider, CountingUdpSocketProvider,
363    DenyFilesystemProvider, DenyProcessProvider, DeterministicRandomProvider, FixedClockProvider,
364    MapDnsProvider, MapEnvironmentProvider, MemoryTcpConnection, MemoryTcpSocketProvider,
365    MemoryUdpSocket, MemoryUdpSocketProvider, MockHttpProvider, NativeChildProcess,
366    NativeClockProvider, NativeDnsProvider, NativeEnvironmentProvider, NativeFileHandle,
367    NativeFilesystemProvider, NativeHttpProvider, NativeProcessProvider, NativeRandomProvider,
368    NativeTcpConnection, NativeTcpSocketProvider, NativeUdpSocket, NativeUdpSocketProvider,
369    NseChildProcess, NseClockProvider, NseDirEntry, NseDnsAnswer, NseDnsProvider, NseDnsQuery,
370    NseDnsRecord, NseDnsRecordType, NseEnvironmentProvider, NseFileHandle, NseFileMetadata,
371    NseFileType, NseFilesystemProvider, NseHostServices, NseHttpError, NseHttpMethod,
372    NseHttpProvider, NseHttpRequest, NseHttpResponse, NseIpAddress, NseNetworkInterface,
373    NseOpenMode, NseProcessProvider, NseProcessResult, NseProcessSpec, NseProviderError,
374    NseRandomProvider, NseResolvedEndpoint, NseTcpConnection, NseTcpSocketProvider,
375    NseTransportProtocol, NseUdpSocket, NseUdpSocketProvider, ScriptedDnsProvider,
376};
377#[cfg(feature = "nse")]
378pub use run::{
379    execute_nse_run, extract_static_requires, script_name_for_source, NseRunError, NseRunErrorKind,
380    NseRunRequest,
381};
382
383/// Compatibility wrapper that defaults to `ManualPermissive` profile.
384///
385/// # Manual-only
386///
387/// This function is unused in production. Prefer [`run_cli_with_profile`]
388/// with an explicit profile for all surfaces.
389#[cfg(feature = "nse")]
390pub async fn run_cli(config: NseConfig) -> anyhow::Result<()> {
391    run_cli_with_profile(config, None).await
392}
393
394#[cfg(feature = "nse")]
395pub async fn run_cli_with_profile(
396    config: NseConfig,
397    profile: Option<ResolvedNseExecutionProfile>,
398) -> anyhow::Result<()> {
399    let target = config.target.clone();
400    let script = config.script.clone();
401    let script_args = config.script_args.clone().unwrap_or_default();
402    let script_file = config.script_file.clone();
403    let json = config.json;
404
405    let resolved_profile =
406        profile.unwrap_or_else(|| ResolvedNseExecutionProfile::manual_permissive(Some(&target)));
407
408    tracing::info!(
409        profile = %resolved_profile.kind,
410        sandbox_enabled = resolved_profile.sandbox.enabled,
411        audit_label = %resolved_profile.audit_label,
412        "NSE execution profile resolved"
413    );
414
415    for warning in &resolved_profile.warnings {
416        tracing::warn!("{}", warning);
417    }
418
419    println!("Running NSE script '{}' against '{}'", script, target);
420    if resolved_profile
421        .warnings
422        .iter()
423        .any(|w| w.contains("sandbox"))
424    {
425        println!("Warning: sandbox enforcement is disabled (feature not compiled)");
426    }
427
428    // Thin adapter over the canonical runtime pipeline: named scripts use
429    // the built-in source identity so policy and diagnostics match the
430    // Eggsec dispatch surface; file sources resolve through ScriptResolver.
431    let script_source = if let Some(ref script_file) = script_file {
432        crate::resolver::NseScriptSource::File {
433            path: std::path::PathBuf::from(script_file),
434        }
435    } else {
436        crate::resolver::NseScriptSource::Builtin {
437            name: script.clone(),
438        }
439    };
440    let request = crate::run::NseRunRequest::new(&target, script_source, resolved_profile)
441        .with_script_args(&script_args);
442
443    let report = tokio::task::spawn_blocking(move || crate::run::execute_nse_run(request))
444        .await
445        .map_err(|e| anyhow::anyhow!("Task execution failed: {}", e))?
446        .map_err(|e| {
447            // Preserve the historical output contract: resolution failures
448            // (including profile file denials) render a failure report in
449            // JSON mode before bailing; execution failures bail directly.
450            if json && e.kind == crate::run::NseRunErrorKind::Resolution {
451                match serde_json::to_string_pretty(&e.failure_report()) {
452                    Ok(rendered) => println!("{}", rendered),
453                    Err(render_err) => {
454                        tracing::warn!("Failed to render NSE failure report: {}", render_err);
455                    }
456                }
457            }
458            anyhow::anyhow!("{}", e)
459        })?;
460
461    if json {
462        println!("{}", serde_json::to_string_pretty(&report)?);
463    } else {
464        print_human_report(&report);
465    }
466
467    Ok(())
468}
469
470#[cfg(feature = "nse")]
471fn print_human_report(report: &crate::report::NseRunReport) {
472    print!("{}", crate::format::format_human_report(report));
473}
474
475#[cfg(not(feature = "nse"))]
476pub async fn run_cli(_config: NseConfig) -> anyhow::Result<()> {
477    anyhow::bail!("NSE support requires the 'nse' feature. Build with: cargo build --features nse")
478}
479
480#[cfg(not(feature = "nse"))]
481pub async fn run_cli_with_profile(
482    _config: NseConfig,
483    _profile: Option<ResolvedNseExecutionProfile>,
484) -> anyhow::Result<()> {
485    anyhow::bail!("NSE support requires the 'nse' feature. Build with: cargo build --features nse")
486}
487
488#[cfg(feature = "nse")]
489pub fn get_builtin_script(name: &str) -> String {
490    match name {
491        "default" | "discovery" => r#"
492-- Default NSE discovery script
493local stdnse = require "stdnse"
494
495stdnse.verbose1("Starting NSE discovery scan...")
496
497local host = nmap.target
498if host and host ~= "" then
499    stdnse.format_output({status = "open", service = "discovered"}, {separator = ", "})
500end
501
502local output = stdnse.output_table()
503output.host = host or "unknown"
504output.status = "discovered"
505output.scan_time = os.date("*t")
506
507return output
508"#
509        .to_string(),
510        "banner" => r#"
511-- Banner grabbing script
512local stdnse = require "stdnse"
513local comm = require "comm"
514local socket = require "socket"
515
516local host = nmap.target
517local port = tonumber(stdnse.get_script_args("port")) or 80
518
519if not host or host == "" then
520    return stdnse.output_table()
521end
522
523local s = socket.connect(host, port)
524if s then
525    s:send("HEAD / HTTP/1.0\r\n\r\n")
526    local status, response = s:receive(1024)
527    s:close()
528
529    local output = stdnse.output_table()
530    output.banner = response or ""
531    output.host = host
532    output.port = port
533    return output
534end
535
536return nil
537"#
538        .to_string(),
539        "http-headers" => r#"
540-- HTTP headers discovery script
541local stdnse = require "stdnse"
542local http = require "http"
543
544local host = nmap.target
545local port = tonumber(stdnse.get_script_args("port")) or 80
546
547if not host or host == "" then
548    return stdnse.output_table()
549end
550
551local response = http.get(host, port, "/")
552
553local output = stdnse.output_table()
554output.host = host
555output.port = port
556output.title = response.title or ""
557output.status = response.status or 0
558
559return output
560"#
561        .to_string(),
562        "dns-check" => r#"
563-- DNS resolution check script
564local stdnse = require "stdnse"
565local dns = require "dns"
566
567local host = nmap.target
568
569if not host or host == "" then
570    return stdnse.output_table()
571end
572
573local success = dns.query(host)
574
575local output = stdnse.output_table()
576output.host = host
577output.resolved = success
578
579return output
580"#
581        .to_string(),
582        "ssl-cert" => r#"
583-- SSL certificate information script
584local stdnse = require "stdnse"
585local sslcert = require "sslcert"
586local tls = require "tls"
587
588local host = nmap.target
589local port = tonumber(stdnse.get_script_args("port")) or 443
590
591if not host or host == "" then
592    return stdnse.output_table()
593end
594
595local output = stdnse.output_table()
596output.host = host
597output.port = port
598output.tls = "available"
599
600return output
601"#
602        .to_string(),
603        _ => {
604            format!(
605                r#"
606-- Custom NSE script: {}
607local stdnse = require "stdnse"
608
609stdnse.verbose1("Executing custom NSE script: {}")
610
611local output = stdnse.output_table()
612output.script = "{}"
613output.status = "executed"
614output.libraries = {{
615    stdnse = true,
616    nmap = true,
617    socket = true,
618    http = true,
619}}
620
621return output
622"#,
623                name, name, name
624            )
625        }
626    }
627}