eggsec-nse 0.3.0

Standalone Lua-based Nmap Scripting Engine runtime
Documentation
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! NSE (Nmap Scripting Engine) support for Eggsec
//!
//! This module provides the ability to run Nmap NSE scripts using a Lua interpreter.
//! It leverages mlua (Lua 5.4) and wraps existing Eggsec functionality
//! to provide NSE-compatible libraries.

use ipnetwork::IpNetwork;
use std::net::IpAddr;
use std::path::PathBuf;

#[cfg(all(feature = "nse", target_family = "unix"))]
#[link(name = "z")]
unsafe extern "C" {}

/// Install the ring crypto provider used by rustls-backed reqwest clients.
pub fn install_tls_provider() {
    use std::sync::Once;
    static INIT: Once = Once::new();
    INIT.call_once(|| {
        // `install_default()` returns Err if another provider is already
        // installed; either outcome is acceptable because the process-level
        // provider must simply exist when rustls clients are constructed.
        if rustls::crypto::ring::default_provider()
            .install_default()
            .is_err()
        {
            tracing::debug!("rustls default provider already installed; keeping existing");
        }
    });
}

/// Configuration for running NSE scripts.
pub struct NseConfig {
    pub target: String,
    pub script: String,
    pub script_args: Option<String>,
    pub script_file: Option<String>,
    pub json: bool,
    pub verbose: bool,
}

impl NseConfig {
    pub fn new(
        target: &str,
        script: &str,
        script_args: Option<&str>,
        script_file: Option<&str>,
        json: bool,
        verbose: bool,
    ) -> Self {
        Self {
            target: target.to_string(),
            script: script.to_string(),
            script_args: script_args.map(|s| s.to_string()),
            script_file: script_file.map(|s| s.to_string()),
            json,
            verbose,
        }
    }
}

/// Sandbox configuration for restricting NSE Lua script capabilities.
///
/// When sandboxing is enabled, dangerous operations like `io.popen` (arbitrary
/// command execution) and unrestricted filesystem access are blocked or limited.
#[derive(Debug, Clone)]
pub struct SandboxConfig {
    /// Whether sandboxing is enabled.
    pub enabled: bool,
    /// If set, restrict file operations to this directory.
    pub allowed_dir: Option<PathBuf>,
    /// If non-empty, only these commands are allowed via `io.popen`.
    /// If empty and sandbox is enabled, `io.popen` is fully blocked.
    pub allowed_commands: Vec<String>,
    /// Whether to log sandbox violations instead of blocking them.
    pub log_violations: bool,
    /// If non-empty, only network connections to these CIDR ranges are allowed.
    /// If empty and sandbox is enabled, socket connections are allowed but a warning is logged.
    pub allowed_networks: Vec<IpNetwork>,
}

impl Default for SandboxConfig {
    fn default() -> Self {
        Self {
            // Sandbox behavior is controlled by the `sandbox` feature.
            enabled: cfg!(feature = "sandbox"),
            allowed_dir: Some(PathBuf::from("/tmp/eggsec-nse")),
            allowed_commands: Vec::new(),
            log_violations: true,
            allowed_networks: Vec::new(),
        }
    }
}

impl SandboxConfig {
    fn allowed_root(&self) -> Option<PathBuf> {
        let dir = self.allowed_dir.as_ref()?;
        // Return the raw path; canonicalization is checked per-path in get_allowed_path().
        // This allows the sandbox to reference a not-yet-created directory.
        Some(dir.clone())
    }

    /// Create a sandbox config with sandboxing enabled and default settings.
    pub fn enabled() -> Self {
        Self {
            enabled: true,
            ..Default::default()
        }
    }

    /// Check if a file path is allowed under the sandbox and return the canonical path.
    ///
    /// This method canonicalizes the path and verifies it starts with the allowed root
    /// using path-component semantics (`Path::strip_prefix` / `Path::starts_with` on
    /// canonical paths only). String-prefix fallback is never used.
    ///
    /// Returns `Some(canonical_path)` if allowed, `None` if blocked or invalid.
    ///
    /// # Security Note
    /// The returned canonical path must be used for actual file operations to avoid
    /// TOCTOU (Time-of-Check-Time-of-Use) vulnerabilities. A separate check followed
    /// by operations on the original path could allow symlink attacks.
    pub fn get_allowed_path(&self, path: &str) -> Option<PathBuf> {
        if !self.enabled {
            return Some(PathBuf::from(path));
        }

        // Sandbox enabled but no allowed_dir configured — allow all paths
        let Some(allowed_dir) = self.allowed_root() else {
            return Some(PathBuf::from(path));
        };

        let path_buf = PathBuf::from(path);

        // Try to canonicalize the path directly
        if let Ok(canonical) = path_buf.canonicalize() {
            if canonical.starts_with(&allowed_dir) {
                return Some(canonical);
            }
            return None;
        }

        // File doesn't exist — try canonicalizing the parent
        if let Some(parent) = path_buf.parent() {
            if let Ok(canonical_parent) = parent.canonicalize() {
                if canonical_parent.starts_with(&allowed_dir) {
                    return Some(canonical_parent.join(path_buf.file_name()?));
                }
            }
        }

        // Cannot canonicalize path or parent — reject (no string-prefix fallback)
        None
    }

    /// Check if a command is allowed via `io.popen`.
    pub fn is_command_allowed(&self, cmd: &str) -> bool {
        if !self.enabled {
            return true;
        }

        if self.allowed_commands.is_empty() {
            return false;
        }

        // Block commands containing shell metacharacters to prevent injection
        if cmd.contains(';')
            || cmd.contains('|')
            || cmd.contains('&')
            || cmd.contains('$')
            || cmd.contains('`')
            || cmd.contains('\n')
            || cmd.contains('\r')
        {
            return false;
        }

        let cmd_name = cmd.split_whitespace().next().unwrap_or(cmd);
        self.allowed_commands
            .iter()
            .any(|allowed| cmd_name == allowed)
    }

    /// Check if a network target IP is allowed under the sandbox.
    ///
    /// Returns `true` if:
    /// - Sandbox is disabled
    /// - `allowed_networks` is empty (allow all with warning)
    /// - The IP matches any network in `allowed_networks`
    ///
    /// Returns `false` if the IP does not match any allowed network.
    pub fn is_network_allowed(&self, ip: IpAddr) -> bool {
        if !self.enabled {
            return true;
        }

        if self.allowed_networks.is_empty() {
            return true;
        }

        self.allowed_networks
            .iter()
            .any(|network| network.contains(ip))
    }

    /// Check if a network target host is allowed.
    ///
    /// This resolves the hostname and checks the resulting IP against allowed networks.
    /// Returns `false` if resolution fails while an allowlist is configured.
    ///
    /// # Security Note - DNS Rebinding
    /// This method checks if ANY resolved IP is allowed, but the actual connection
    /// may use a DIFFERENT IP if DNS changes between check and connection time.
    /// For sensitive operations, use `resolve_host()` immediately before connecting
    /// to get the actual IPs that will be used, and ensure DNS hasn't changed.
    pub fn is_host_allowed(&self, host: &str) -> bool {
        !self.resolve_host(host).is_empty()
    }

    /// Resolve a hostname to a list of IP addresses.
    ///
    /// # Security Note - DNS Rebinding
    /// DNS responses can change between calls. For sandbox enforcement, you should:
    /// 1. Call this method to resolve the host
    /// 2. Immediately use one of the returned IPs for the connection
    /// 3. Do not re-resolve the same hostname before connecting
    ///
    /// If sandboxing is disabled or no networks are restricted, returns all resolved IPs.
    /// If resolution fails or no IPs match the allowlist, returns an empty vector.
    pub fn resolve_host(&self, host: &str) -> Vec<IpAddr> {
        use std::net::ToSocketAddrs;

        if !self.enabled {
            if let Ok(addrs) = format!("{}:0", host).to_socket_addrs() {
                return addrs.map(|a| a.ip()).collect();
            }
            return Vec::new();
        }

        if self.allowed_networks.is_empty() {
            if let Ok(addrs) = format!("{}:0", host).to_socket_addrs() {
                return addrs.map(|a| a.ip()).collect();
            }
            return Vec::new();
        }

        let Ok(addrs) = format!("{}:0", host).to_socket_addrs() else {
            return Vec::new();
        };

        addrs
            .map(|a| a.ip())
            .filter(|ip| self.is_network_allowed(*ip))
            .collect()
    }
}

#[cfg(feature = "nse")]
pub mod async_executor;
#[cfg(feature = "nse")]
pub mod brokered_stream;
#[cfg(feature = "nse")]
pub mod capabilities;
#[cfg(feature = "nse")]
pub mod context;
#[cfg(feature = "nse")]
pub mod cve;
pub mod effect_manifest;
#[cfg(feature = "nse")]
pub mod executor;
#[cfg(feature = "nse")]
pub mod executor_core;
#[cfg(feature = "nse")]
pub mod format;
pub mod limits;
pub mod output;
pub mod profile;
#[cfg(feature = "nse")]
pub mod providers;
#[cfg(feature = "nse")]
pub mod public_api;
#[cfg(feature = "nse")]
pub mod report;
pub mod resolver;
#[cfg(feature = "nse")]
pub mod run;
#[cfg(feature = "nse")]
pub mod wrappers;

#[cfg(feature = "nse")]
pub mod libraries;

#[cfg(feature = "nse")]
pub use async_executor::AsyncNseExecutor;
#[cfg(feature = "nse")]
pub use capabilities::{
    NseCapabilityContext, NseCapabilityDecision, NseCapabilityEvent, NseCapabilityKind,
    NseCapabilityRequest,
};
#[cfg(feature = "nse")]
pub use executor::NseExecutor;
#[cfg(feature = "nse")]
pub use executor_core::ExecutorCore;
#[cfg(feature = "nse")]
pub use executor_core::SandboxMetrics;
#[cfg(feature = "nse")]
pub use executor_core::{default_module_policy, default_script_policy};
#[cfg(feature = "nse")]
pub use limits::{
    NseCancellationToken, NseExecutionLimits, NseExecutionStats, NseLimitViolation,
    NseResourceCounters,
};

pub use profile::{
    NseExecutionProfileKind, NseModulePolicy, NseNetworkPolicy, NseScriptPolicy,
    ResolvedNseExecutionProfile, ScopeInput,
};

pub use resolver::{
    is_builtin_script, validate_nse_module_name, NseLoadDiagnostic, NseLoadError, NseModuleName,
    NseScriptSource, ResolvedNseModule, ResolvedNseScript, ScriptResolver,
};

pub use effect_manifest::{
    automated_library_eligibility, classified_libraries, classify, eligibility_counts,
    eligible_for_profile, is_automated_library_safe, is_automated_profile, EligibilityCounts,
    LibraryEffectEntry, NseAutomatedLibraryEligibility,
};

pub use resolver::registry::{
    all_libraries, find_library, libraries_by_category, libraries_missing_from_nmap,
    libraries_with_side_effects, registry_count, sandbox_policy_for_library, EnforcementStatus,
    NseFallbackBehavior, NseLibraryCategory, NseLibraryDescriptor, NseSandboxSideEffect,
};

#[cfg(feature = "nse")]
pub use report::{
    NseCapabilityEventSummary, NseCompatibilitySummary, NseEvidenceItem, NseEvidenceKind,
    NseExecutionStatsSummary, NseLibraryUseReport, NseLimitsSummary, NseOutputSummary,
    NseProfileSummary, NseRequiredModuleReport, NseRequiredModuleSource,
    NseResolverDiagnosticSummary, NseResolverSummary, NseRuleEvaluationReport,
    NseRunCompatibilityStatus, NseRunFidelity, NseRunReport, NseSandboxSummary,
    NseScriptSourceSummary,
};

#[cfg(feature = "nse")]
pub use context::{NseContextSource, NseHostContext, NsePortContext, NseServiceContext};
#[cfg(feature = "nse")]
pub use providers::{
    broker_dns_lookup, broker_env_var, broker_fs_create_dir_all, broker_fs_current_dir,
    broker_fs_exists, broker_fs_hard_link, broker_fs_metadata, broker_fs_open, broker_fs_read,
    broker_fs_read_dir, broker_fs_read_link, broker_fs_read_to_string, broker_fs_remove_dir,
    broker_fs_remove_file, broker_fs_rename, broker_fs_resolve, broker_fs_set_current_dir,
    broker_fs_set_readonly, broker_fs_set_unix_mode, broker_fs_symlink, broker_fs_symlink_metadata,
    broker_fs_write, broker_http_request, broker_is_privileged, broker_network_interfaces,
    broker_process_run, broker_process_spawn, broker_random_f64, broker_random_fill,
    broker_random_u32, broker_resolve_and_select, broker_tcp_connect, broker_tcp_connect_endpoint,
    broker_tcp_receive, broker_tcp_send, broker_temp_dir, broker_udp_connect,
    broker_udp_connect_endpoint, broker_udp_receive, broker_udp_send, broker_unix_timestamp,
    CountingClockProvider, CountingDnsProvider, CountingEnvironmentProvider,
    CountingFilesystemProvider, CountingHttpProvider, CountingProcessProvider,
    CountingRandomProvider, CountingTcpSocketProvider, CountingUdpSocketProvider,
    DenyFilesystemProvider, DenyProcessProvider, DeterministicRandomProvider, FixedClockProvider,
    MapDnsProvider, MapEnvironmentProvider, MemoryTcpConnection, MemoryTcpSocketProvider,
    MemoryUdpSocket, MemoryUdpSocketProvider, MockHttpProvider, NativeChildProcess,
    NativeClockProvider, NativeDnsProvider, NativeEnvironmentProvider, NativeFileHandle,
    NativeFilesystemProvider, NativeHttpProvider, NativeProcessProvider, NativeRandomProvider,
    NativeTcpConnection, NativeTcpSocketProvider, NativeUdpSocket, NativeUdpSocketProvider,
    NseChildProcess, NseClockProvider, NseDirEntry, NseDnsAnswer, NseDnsProvider, NseDnsQuery,
    NseDnsRecord, NseDnsRecordType, NseEnvironmentProvider, NseFileHandle, NseFileMetadata,
    NseFileType, NseFilesystemProvider, NseHostServices, NseHttpError, NseHttpMethod,
    NseHttpProvider, NseHttpRequest, NseHttpResponse, NseIpAddress, NseNetworkInterface,
    NseOpenMode, NseProcessProvider, NseProcessResult, NseProcessSpec, NseProviderError,
    NseRandomProvider, NseResolvedEndpoint, NseTcpConnection, NseTcpSocketProvider,
    NseTransportProtocol, NseUdpSocket, NseUdpSocketProvider, ScriptedDnsProvider,
};
#[cfg(feature = "nse")]
pub use run::{
    execute_nse_run, extract_static_requires, script_name_for_source, NseRunError, NseRunErrorKind,
    NseRunRequest,
};

/// Compatibility wrapper that defaults to `ManualPermissive` profile.
///
/// # Manual-only
///
/// This function is unused in production. Prefer [`run_cli_with_profile`]
/// with an explicit profile for all surfaces.
#[cfg(feature = "nse")]
pub async fn run_cli(config: NseConfig) -> anyhow::Result<()> {
    run_cli_with_profile(config, None).await
}

#[cfg(feature = "nse")]
pub async fn run_cli_with_profile(
    config: NseConfig,
    profile: Option<ResolvedNseExecutionProfile>,
) -> anyhow::Result<()> {
    let target = config.target.clone();
    let script = config.script.clone();
    let script_args = config.script_args.clone().unwrap_or_default();
    let script_file = config.script_file.clone();
    let json = config.json;

    let resolved_profile =
        profile.unwrap_or_else(|| ResolvedNseExecutionProfile::manual_permissive(Some(&target)));

    tracing::info!(
        profile = %resolved_profile.kind,
        sandbox_enabled = resolved_profile.sandbox.enabled,
        audit_label = %resolved_profile.audit_label,
        "NSE execution profile resolved"
    );

    for warning in &resolved_profile.warnings {
        tracing::warn!("{}", warning);
    }

    println!("Running NSE script '{}' against '{}'", script, target);
    if resolved_profile
        .warnings
        .iter()
        .any(|w| w.contains("sandbox"))
    {
        println!("Warning: sandbox enforcement is disabled (feature not compiled)");
    }

    // Thin adapter over the canonical runtime pipeline: named scripts use
    // the built-in source identity so policy and diagnostics match the
    // Eggsec dispatch surface; file sources resolve through ScriptResolver.
    let script_source = if let Some(ref script_file) = script_file {
        crate::resolver::NseScriptSource::File {
            path: std::path::PathBuf::from(script_file),
        }
    } else {
        crate::resolver::NseScriptSource::Builtin {
            name: script.clone(),
        }
    };
    let request = crate::run::NseRunRequest::new(&target, script_source, resolved_profile)
        .with_script_args(&script_args);

    let report = tokio::task::spawn_blocking(move || crate::run::execute_nse_run(request))
        .await
        .map_err(|e| anyhow::anyhow!("Task execution failed: {}", e))?
        .map_err(|e| {
            // Preserve the historical output contract: resolution failures
            // (including profile file denials) render a failure report in
            // JSON mode before bailing; execution failures bail directly.
            if json && e.kind == crate::run::NseRunErrorKind::Resolution {
                match serde_json::to_string_pretty(&e.failure_report()) {
                    Ok(rendered) => println!("{}", rendered),
                    Err(render_err) => {
                        tracing::warn!("Failed to render NSE failure report: {}", render_err);
                    }
                }
            }
            anyhow::anyhow!("{}", e)
        })?;

    if json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print_human_report(&report);
    }

    Ok(())
}

#[cfg(feature = "nse")]
fn print_human_report(report: &crate::report::NseRunReport) {
    print!("{}", crate::format::format_human_report(report));
}

#[cfg(not(feature = "nse"))]
pub async fn run_cli(_config: NseConfig) -> anyhow::Result<()> {
    anyhow::bail!("NSE support requires the 'nse' feature. Build with: cargo build --features nse")
}

#[cfg(not(feature = "nse"))]
pub async fn run_cli_with_profile(
    _config: NseConfig,
    _profile: Option<ResolvedNseExecutionProfile>,
) -> anyhow::Result<()> {
    anyhow::bail!("NSE support requires the 'nse' feature. Build with: cargo build --features nse")
}

#[cfg(feature = "nse")]
pub fn get_builtin_script(name: &str) -> String {
    match name {
        "default" | "discovery" => r#"
-- Default NSE discovery script
local stdnse = require "stdnse"

stdnse.verbose1("Starting NSE discovery scan...")

local host = nmap.target
if host and host ~= "" then
    stdnse.format_output({status = "open", service = "discovered"}, {separator = ", "})
end

local output = stdnse.output_table()
output.host = host or "unknown"
output.status = "discovered"
output.scan_time = os.date("*t")

return output
"#
        .to_string(),
        "banner" => r#"
-- Banner grabbing script
local stdnse = require "stdnse"
local comm = require "comm"
local socket = require "socket"

local host = nmap.target
local port = tonumber(stdnse.get_script_args("port")) or 80

if not host or host == "" then
    return stdnse.output_table()
end

local s = socket.connect(host, port)
if s then
    s:send("HEAD / HTTP/1.0\r\n\r\n")
    local status, response = s:receive(1024)
    s:close()

    local output = stdnse.output_table()
    output.banner = response or ""
    output.host = host
    output.port = port
    return output
end

return nil
"#
        .to_string(),
        "http-headers" => r#"
-- HTTP headers discovery script
local stdnse = require "stdnse"
local http = require "http"

local host = nmap.target
local port = tonumber(stdnse.get_script_args("port")) or 80

if not host or host == "" then
    return stdnse.output_table()
end

local response = http.get(host, port, "/")

local output = stdnse.output_table()
output.host = host
output.port = port
output.title = response.title or ""
output.status = response.status or 0

return output
"#
        .to_string(),
        "dns-check" => r#"
-- DNS resolution check script
local stdnse = require "stdnse"
local dns = require "dns"

local host = nmap.target

if not host or host == "" then
    return stdnse.output_table()
end

local success = dns.query(host)

local output = stdnse.output_table()
output.host = host
output.resolved = success

return output
"#
        .to_string(),
        "ssl-cert" => r#"
-- SSL certificate information script
local stdnse = require "stdnse"
local sslcert = require "sslcert"
local tls = require "tls"

local host = nmap.target
local port = tonumber(stdnse.get_script_args("port")) or 443

if not host or host == "" then
    return stdnse.output_table()
end

local output = stdnse.output_table()
output.host = host
output.port = port
output.tls = "available"

return output
"#
        .to_string(),
        _ => {
            format!(
                r#"
-- Custom NSE script: {}
local stdnse = require "stdnse"

stdnse.verbose1("Executing custom NSE script: {}")

local output = stdnse.output_table()
output.script = "{}"
output.status = "executed"
output.libraries = {{
    stdnse = true,
    nmap = true,
    socket = true,
    http = true,
}}

return output
"#,
                name, name, name
            )
        }
    }
}