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
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::sync::Arc;

#[derive(Debug, Clone)]
pub struct HostInfo {
    pub ip: String,
    pub hostname: Option<String>,
    pub mac: Option<String>,
    pub os: Option<String>,
    pub address_family: String,
}

impl HostInfo {
    pub fn new(ip: String) -> Self {
        Self {
            ip,
            hostname: None,
            mac: None,
            os: None,
            address_family: "inet".to_string(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct PortInfo {
    pub number: u16,
    pub protocol: String,
    pub state: String,
    pub service: Option<String>,
    pub version: Option<String>,
}

impl PortInfo {
    pub fn new(number: u16, protocol: String, state: String) -> Self {
        Self {
            number,
            protocol,
            state,
            service: None,
            version: None,
        }
    }

    pub fn to_table(&self, lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
        let table = lua.create_table()?;
        table.set("number", self.number)?;
        table.set("protocol", self.protocol.as_str())?;
        table.set("state", self.state.as_str())?;
        if let Some(ref svc) = self.service {
            table.set("service", svc.as_str())?;
        }
        if let Some(ref ver) = self.version {
            table.set("version", ver.as_str())?;
        }
        Ok(table)
    }
}

/// Source of host/port/service context data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum NseContextSource {
    /// Data came from an actual scan result.
    Scan,
    /// Data was provided as a test fixture.
    Fixture,
    /// Data was synthetically generated (e.g., target string only).
    Synthetic,
    /// Source is unknown or not tracked.
    Unknown,
}

impl fmt::Display for NseContextSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Scan => write!(f, "scan"),
            Self::Fixture => write!(f, "fixture"),
            Self::Synthetic => write!(f, "synthetic"),
            Self::Unknown => write!(f, "unknown"),
        }
    }
}

/// Service context for a port, capturing what is known about the service.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseServiceContext {
    /// Service name (e.g., "http", "ssh", "https").
    pub name: Option<String>,
    /// Service product (e.g., "Apache httpd", "OpenSSH").
    pub product: Option<String>,
    /// Service version (e.g., "2.4.41", "8.1p1").
    pub version: Option<String>,
    /// Tunnel type (e.g., "ssl", "ssl/http").
    pub tunnel: Option<String>,
    /// Confidence in the service detection (0.0 - 1.0).
    pub confidence: Option<f32>,
}

impl NseServiceContext {
    pub fn new() -> Self {
        Self {
            name: None,
            product: None,
            version: None,
            tunnel: None,
            confidence: None,
        }
    }

    /// Build a Lua table compatible with Nmap's `port.service` structure.
    pub fn to_table(&self, lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
        let table = lua.create_table()?;
        if let Some(ref name) = self.name {
            table.set("name", name.as_str())?;
        }
        if let Some(ref product) = self.product {
            table.set("product", product.as_str())?;
        }
        if let Some(ref version) = self.version {
            table.set("version", version.as_str())?;
        }
        if let Some(ref tunnel) = self.tunnel {
            table.set("tunnel", tunnel.as_str())?;
        }
        if let Some(confidence) = self.confidence {
            table.set("confidence", confidence)?;
        }
        Ok(table)
    }
}

impl Default for NseServiceContext {
    fn default() -> Self {
        Self::new()
    }
}

/// Host context for NSE rule evaluation and script execution.
///
/// Carries structured host data with explicit provenance tracking.
/// Fields that are not available from scan data are `None` rather
/// than fabricated.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NseHostContext {
    /// Host IP address.
    pub ip: String,
    /// Hostname (DNS name) if known.
    pub hostname: Option<String>,
    /// Target label (usually the original target string).
    pub target_label: String,
    /// Source of this context data.
    pub source: NseContextSource,
}

impl NseHostContext {
    pub fn new(ip: String, target_label: String, source: NseContextSource) -> Self {
        Self {
            ip,
            hostname: None,
            target_label,
            source,
        }
    }

    /// Build a Lua host table compatible with Nmap's `host` structure.
    ///
    /// Sets: `ip`, `name`, `hostname`, `binip`, `address_family`, and
    /// `eggsec_context_source` for provenance tracking.
    pub fn to_table(&self, lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
        let table = lua.create_table()?;
        table.set("ip", self.ip.as_str())?;
        table.set("binip", self.ip.as_str())?;
        if let Some(ref hostname) = self.hostname {
            table.set("name", hostname.as_str())?;
            table.set("hostname", hostname.as_str())?;
        }
        table.set("address_family", "inet")?;
        table.set("eggsec_context_source", self.source.to_string())?;
        Ok(table)
    }

    /// Derive a host context from a `HostInfo` and target string.
    pub fn from_host_info(host: &HostInfo, target: &str) -> Self {
        Self {
            ip: host.ip.clone(),
            hostname: host.hostname.clone(),
            target_label: target.to_string(),
            source: NseContextSource::Scan,
        }
    }

    /// Create a synthetic context from just a target string.
    pub fn synthetic(target: &str) -> Self {
        Self {
            ip: target.to_string(),
            hostname: None,
            target_label: target.to_string(),
            source: NseContextSource::Synthetic,
        }
    }
}

/// Port context for NSE rule evaluation and script execution.
///
/// Carries structured port/service data with explicit provenance tracking.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NsePortContext {
    /// Port number.
    pub port: u16,
    /// Protocol (e.g., "tcp", "udp").
    pub protocol: String,
    /// Port state (e.g., "open", "closed", "filtered", "unknown").
    pub state: String,
    /// Service context if known.
    pub service: Option<NseServiceContext>,
    /// Source of this context data.
    pub source: NseContextSource,
}

impl NsePortContext {
    pub fn new(port: u16, protocol: String, state: String, source: NseContextSource) -> Self {
        Self {
            port,
            protocol,
            state,
            service: None,
            source,
        }
    }

    /// Build a Lua port table compatible with Nmap's `port` structure.
    ///
    /// Sets: `number`, `protocol`, `state`, `service` (sub-table),
    /// `version` (convenience), and `eggsec_context_source`.
    pub fn to_table(&self, lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
        let table = lua.create_table()?;
        table.set("number", self.port)?;
        table.set("protocol", self.protocol.as_str())?;
        table.set("state", self.state.as_str())?;
        if let Some(ref svc) = self.service {
            table.set("service", svc.to_table(lua)?)?;
            if let Some(ref version) = svc.version {
                table.set("version", version.as_str())?;
            }
        }
        table.set("eggsec_context_source", self.source.to_string())?;
        Ok(table)
    }

    /// Derive a port context from a `PortInfo`.
    pub fn from_port_info(port: &PortInfo) -> Self {
        let service = port.service.as_ref().map(|name| NseServiceContext {
            name: Some(name.clone()),
            product: None,
            version: port.version.clone(),
            tunnel: None,
            confidence: None,
        });
        Self {
            port: port.number,
            protocol: port.protocol.clone(),
            state: port.state.clone(),
            service,
            source: NseContextSource::Scan,
        }
    }

    /// Create a minimal port context (port number and protocol only).
    pub fn minimal(port: u16, protocol: &str) -> Self {
        Self {
            port,
            protocol: protocol.to_string(),
            state: "unknown".to_string(),
            service: None,
            source: NseContextSource::Synthetic,
        }
    }
}

#[derive(Debug, Clone)]
pub struct ScriptOutputSection {
    pub key: String,
    pub value: String,
    pub output_type: String,
}

#[derive(Debug, Clone)]
pub struct ScriptOutput {
    pub lines: Vec<String>,
    pub output_table: Option<FxHashMap<String, String>>,
    pub severity: String,
    pub sections: Vec<ScriptOutputSection>,
    pub raw_output: String,
}

impl ScriptOutput {
    pub fn new() -> Self {
        Self {
            lines: Vec::new(),
            output_table: None,
            severity: "ok".to_string(),
            sections: Vec::new(),
            raw_output: String::new(),
        }
    }

    pub fn add_line(&mut self, line: String) {
        self.lines.push(line.clone());
        if !self.raw_output.is_empty() {
            self.raw_output.push('\n');
        }
        self.raw_output.push_str(&line);
    }

    pub fn add_section(&mut self, key: String, value: String) {
        self.sections.push(ScriptOutputSection {
            key: key.clone(),
            value: value.clone(),
            output_type: "table".to_string(),
        });
        let line = format!("{}: {}", key, value);
        self.add_line(line);
    }

    pub fn set_table(&mut self, table: FxHashMap<String, String>) {
        self.output_table = Some(table);
    }

    pub fn to_nse_string(&self) -> String {
        let mut output = String::new();

        for section in &self.sections {
            output.push_str(&section.key);
            output.push_str(": ");
            output.push_str(&section.value);
            output.push('\n');
        }

        if !self.lines.is_empty() {
            output.push_str(&self.lines.join("\n"));
        }

        output
    }

    pub fn clear(&mut self) {
        self.lines.clear();
        self.output_table = None;
        self.sections.clear();
        self.raw_output.clear();
        self.severity = "ok".to_string();
    }
}

impl Default for ScriptOutput {
    fn default() -> Self {
        Self::new()
    }
}

pub struct ScanContext {
    pub host: Option<HostInfo>,
    pub ports: FxHashMap<(u16, String), PortInfo>,
    pub target_port: Option<PortInfo>,
    pub output: ScriptOutput,
    pub registry: FxHashMap<String, mlua::Value>,
    pub script_name: Option<String>,
    pub verbose: Option<i32>,
}

impl ScanContext {
    pub fn new() -> Self {
        Self {
            host: None,
            ports: FxHashMap::default(),
            target_port: None,
            output: ScriptOutput::new(),
            registry: FxHashMap::default(),
            script_name: None,
            verbose: Some(1),
        }
    }

    pub fn with_target(target: &str) -> Self {
        let mut ctx = Self::new();
        ctx.host = Some(HostInfo::new(target.to_string()));
        ctx
    }

    pub fn set_verbose(&mut self, level: i32) {
        self.verbose = Some(level);
    }

    pub fn set_host(&mut self, host: HostInfo) {
        self.host = Some(host);
    }

    pub fn add_port(&mut self, port: PortInfo) {
        self.ports
            .insert((port.number, port.protocol.clone()), port);
    }

    pub fn set_target_port(&mut self, port: PortInfo) {
        self.target_port = Some(port.clone());
        self.add_port(port);
    }

    pub fn get_port(&self, number: u16, protocol: &str) -> Option<&PortInfo> {
        self.ports.get(&(number, protocol.to_string()))
    }

    pub fn get_all_ports(&self) -> Vec<&PortInfo> {
        self.ports.values().collect()
    }

    pub fn add_output(&mut self, line: String) {
        self.output.add_line(line);
    }

    pub fn set_severity(&mut self, severity: &str) {
        self.output.severity = severity.to_string();
    }

    pub fn get_output(&self) -> String {
        self.output.to_nse_string()
    }

    pub fn get_raw_output(&self) -> String {
        self.output.raw_output.clone()
    }

    pub fn add_output_section(&mut self, key: String, value: String) {
        self.output.add_section(key, value);
    }

    pub fn get_output_sections(&self) -> &Vec<ScriptOutputSection> {
        &self.output.sections
    }

    pub fn set_output_table(&mut self, table: FxHashMap<String, String>) {
        self.output.set_table(table);
    }

    pub fn get_output_table(&self) -> Option<&FxHashMap<String, String>> {
        self.output.output_table.as_ref()
    }

    pub fn clear_output(&mut self) {
        self.output.clear();
    }

    pub fn set_registry(&mut self, key: String, value: mlua::Value) {
        self.registry.insert(key, value);
    }

    pub fn get_registry(&self, key: &str) -> Option<&mlua::Value> {
        self.registry.get(key)
    }

    pub fn to_host_table(&self, lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
        let table = lua.create_table()?;

        if let Some(ref host) = self.host {
            table.set("ip", host.ip.as_str())?;

            if let Some(ref hostname) = host.hostname {
                table.set("name", hostname.as_str())?;
                table.set("hostname", hostname.as_str())?;
            }

            if let Some(ref mac) = host.mac {
                table.set("mac", mac.as_str())?;
            }

            if let Some(ref os) = host.os {
                let os_table = lua.create_table()?;
                os_table.set("name", os.as_str())?;
                table.set("os", os_table)?;
            }

            table.set("address_family", host.address_family.as_str())?;

            table.set("binip", host.ip.as_str())?;
        }

        Ok(table)
    }

    pub fn to_port_table(&self, lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
        if let Some(ref port) = self.target_port {
            return port.to_table(lua);
        }
        lua.create_table()
    }
}

impl Default for ScanContext {
    fn default() -> Self {
        Self::new()
    }
}

pub struct NseState {
    pub context: Arc<parking_lot::Mutex<ScanContext>>,
    pub scripts_path: Vec<std::path::PathBuf>,
}

impl NseState {
    pub fn new() -> Self {
        Self {
            context: Arc::new(parking_lot::Mutex::new(ScanContext::new())),
            scripts_path: Vec::new(),
        }
    }

    pub fn with_target(target: &str) -> Self {
        Self {
            context: Arc::new(parking_lot::Mutex::new(ScanContext::with_target(target))),
            scripts_path: Vec::new(),
        }
    }

    pub fn get_context(&self) -> Arc<parking_lot::Mutex<ScanContext>> {
        self.context.clone()
    }

    pub fn add_scripts_path(&mut self, path: std::path::PathBuf) {
        if path.exists() && path.is_dir() {
            self.scripts_path.push(path);
        }
    }
}

impl Default for NseState {
    fn default() -> Self {
        Self::new()
    }
}