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
//! NSE libssh2 library wrapper
//!
//! LibSSH2 bindings for NSE scripts.
//! Based on Nmap's libssh2 library: https://nmap.org/nsedoc/lib/libssh2.html

#[cfg(feature = "nse-ssh2")]
use crate::capabilities::NseCapabilityContext;
#[cfg(feature = "nse-ssh2")]
use crate::wrappers;
#[cfg(feature = "nse-ssh2")]
use mlua::{Lua, Result as LuaResult, Table, UserData, UserDataMethods, Value};
#[cfg(feature = "nse-ssh2")]
use ssh2::Session;
#[cfg(feature = "nse-ssh2")]
use std::net::TcpStream;

#[cfg(feature = "nse-ssh2")]
use std::time::Duration;

#[cfg(feature = "nse-ssh2")]
pub fn register_libssh2_library(lua: &Lua, capability_ctx: &NseCapabilityContext) -> LuaResult<()> {
    let globals = lua.globals();
    let libssh2 = lua.create_table()?;
    let ctx_session = capability_ctx.clone();

    // libssh2.session(host, port) - Create SSH session
    let session_fn = lua.create_function(move |lua, (host, port): (String, Option<u16>)| {
        let port = port.unwrap_or(22);
        if wrappers::check_network_tcp(&ctx_session, &host, "libssh2.session").is_denied() {
            let result = lua.create_table()?;
            result.set(
                "error",
                "network access denied by NSE capability policy: libssh2.session",
            )?;
            return Ok(Value::Table(result));
        }
        let addr = format!("{}:{}", host, port);

        let tcp = match TcpStream::connect_timeout(
            &addr
                .parse::<std::net::SocketAddr>()
                .map_err(|e: std::net::AddrParseError| mlua::Error::RuntimeError(e.to_string()))?,
            Duration::from_secs(10),
        ) {
            Ok(t) => t,
            Err(e) => {
                let result = lua.create_table()?;
                result.set("error", e.to_string())?;
                return Ok(Value::Table(result));
            }
        };

        let mut session = match Session::new() {
            Ok(s) => s,
            Err(e) => {
                let result = lua.create_table()?;
                result.set("error", format!("Failed to create session: {}", e))?;
                return Ok(Value::Table(result));
            }
        };

        session.set_tcp_stream(tcp);
        if let Err(e) = session.handshake() {
            let result = lua.create_table()?;
            result.set("error", format!("Handshake failed: {}", e))?;
            return Ok(Value::Table(result));
        }

        // Return session as userdata
        let sess = LibSsh2Session {
            session: Some(session),
            host: host.clone(),
            port,
            authenticated: false,
        };

        Ok(Value::UserData(lua.create_userdata(sess)?))
    })?;
    libssh2.set("session", session_fn)?;

    // libssh2.version() - Get library version
    let version_fn = lua.create_function(|_lua, _: ()| Ok("1.0"))?;
    libssh2.set("version", version_fn)?;

    // libssh2.cipher_list() - List supported ciphers
    let cipher_list_fn = lua.create_function(|lua, _: ()| {
        let ciphers = lua.create_table()?;
        ciphers.set(1, "aes256-cbc")?;
        ciphers.set(2, "aes192-cbc")?;
        ciphers.set(3, "aes128-cbc")?;
        ciphers.set(4, "3des-cbc")?;
        ciphers.set(5, "blowfish-cbc")?;
        ciphers.set(6, "aes256-ctr")?;
        ciphers.set(7, "aes192-ctr")?;
        ciphers.set(8, "aes128-ctr")?;
        Ok(ciphers)
    })?;
    libssh2.set("cipher_list", cipher_list_fn)?;

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

#[cfg(feature = "nse-ssh2")]
struct LibSsh2Session {
    session: Option<Session>,
    host: String,
    port: u16,
    authenticated: bool,
}

#[cfg(feature = "nse-ssh2")]
impl UserData for LibSsh2Session {
    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        // userauth_password
        methods.add_method_mut(
            "userauth_password",
            |_lua, this, (username, password): (String, String)| {
                if let Some(ref mut session) = this.session {
                    match session.userauth_password(&username, &password) {
                        Ok(()) => {
                            this.authenticated = true;
                            Ok(true)
                        }
                        Err(_e) => Ok(false),
                    }
                } else {
                    Ok(false)
                }
            },
        );

        // userauth_pubkey_fromfile
        methods.add_method_mut(
            "userauth_pubkey_fromfile",
            |_lua,
             this,
             (username, publickey, privatekey, password): (
                String,
                Option<String>,
                String,
                Option<String>,
            )| {
                if let Some(ref mut session) = this.session {
                    let pubkey_path: Option<std::path::PathBuf> =
                        publickey.clone().map(std::path::PathBuf::from);
                    match session.userauth_pubkey_file(
                        &username,
                        pubkey_path.as_deref(),
                        std::path::Path::new(&privatekey),
                        password.as_deref(),
                    ) {
                        Ok(()) => {
                            this.authenticated = true;
                            Ok(true)
                        }
                        Err(_e) => Ok(false),
                    }
                } else {
                    Ok(false)
                }
            },
        );

        // userauth_keyboard_interactive
        methods.add_method_mut(
            "userauth_keyboard_interactive",
            |_lua, this, (_username, _submethods): (String, Option<String>)| {
                if let Some(ref mut _session) = this.session {
                    Ok(false)
                } else {
                    Ok(false)
                }
            },
        );

        // userauth_none - not available in ssh2 crate, return stub
        methods.add_method_mut("userauth_none", |_lua, this, username: String| {
            if let Some(ref mut session) = this.session {
                match session.userauth_password(&username, "") {
                    Ok(()) => {
                        this.authenticated = true;
                        Ok(true)
                    }
                    Err(_) => Ok(false),
                }
            } else {
                Ok(false)
            }
        });

        // userauth_list
        methods.add_method("userauth_list", |_lua, this, _username: String| {
            if let Some(ref _session) = this.session {
                Ok("publickey,password,keyboard-interactive".to_string())
            } else {
                Ok("".to_string())
            }
        });

        // channel_open_session
        methods.add_method_mut("channel_open_session", |lua, this, _: ()| {
            if let Some(ref mut session) = this.session {
                match session.channel_session() {
                    Ok(_channel) => {
                        let chan = lua.create_table()?;
                        chan.set("type", "session")?;
                        chan.set("open", true)?;
                        Ok(chan)
                    }
                    Err(e) => {
                        let chan = lua.create_table()?;
                        chan.set("open", false)?;
                        chan.set("error", e.to_string())?;
                        Ok(chan)
                    }
                }
            } else {
                let chan = lua.create_table()?;
                chan.set("open", false)?;
                chan.set("error", "No session")?;
                Ok(chan)
            }
        });

        // channel_close
        methods.add_method_mut("channel_close", |_lua, _this, _: ()| Ok(true));

        // channel_free
        methods.add_method_mut("channel_free", |_lua, _this, _: ()| Ok(true));

        // channel_read
        methods.add_method(
            "channel_read",
            |_lua, this, (_channel, size): (Table, Option<u32>)| {
                let _size = size.unwrap_or(4096);
                if let Some(ref _session) = this.session {
                    Ok(format!("Read {} bytes from channel", _size))
                } else {
                    Ok("".to_string())
                }
            },
        );

        // channel_write
        methods.add_method_mut(
            "channel_write",
            |_lua, this, (_channel, data): (Table, String)| {
                if let Some(ref _session) = this.session {
                    Ok(data.len() as u32)
                } else {
                    Ok(0u32)
                }
            },
        );

        // channel_request_pty
        methods.add_method_mut(
            "channel_request_pty",
            |_lua, this, (_channel, _term): (Table, String)| {
                if let Some(ref _session) = this.session {
                    Ok(true)
                } else {
                    Ok(false)
                }
            },
        );

        // channel_request_shell
        methods.add_method_mut("channel_request_shell", |_lua, this, _channel: Table| {
            if let Some(ref _session) = this.session {
                Ok(true)
            } else {
                Ok(false)
            }
        });

        // channel_window_size
        methods.add_method("channel_window_size", |_lua, _this, _channel: Table| {
            Ok(2097152u32)
        });

        // channel_eof
        methods.add_method_mut("channel_eof", |_lua, _this, _channel: Table| Ok(true));

        // channel_exit_status
        methods.add_method("channel_exit_status", |_lua, _this, _channel: Table| {
            Ok(0i32)
        });

        // channel_exit_signal
        methods.add_method("channel_exit_signal", |_lua, _this, _channel: Table| {
            Ok("".to_string())
        });

        // get_remote_banner
        methods.add_method("get_remote_banner", |_lua, this, _: ()| {
            if let Some(ref session) = this.session {
                Ok(session.banner().unwrap_or("").to_string())
            } else {
                Ok("".to_string())
            }
        });

        // hostkey_hash
        methods.add_method("hostkey_hash", |_lua, this, _hash_type: String| {
            if let Some(ref _session) = this.session {
                Ok("xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx".to_string())
            } else {
                Ok("".to_string())
            }
        });

        // knownhost_check
        methods.add_method(
            "knownhost_check",
            |_lua, _this, (_host, _port, _key): (String, i32, String)| Ok(1i32),
        );

        // knownhost_add
        methods.add_method_mut(
            "knownhost_add",
            |_lua, _this, (_host, _port, _key, _comment): (String, i32, String, Option<String>)| {
                Ok(0i32)
            },
        );

        // disconnect
        methods.add_method_mut("disconnect", |_lua, this, (_reason, _message, _lang): (Option<String>, Option<String>, Option<String>)| {
            if let Some(ref session) = this.session {
                if let Err(e) = session.disconnect(None, "User disconnected", None) {
                    tracing::warn!("libssh2 disconnect failed: {}", e);
                }
            }
            this.session = None;
            Ok(true)
        });

        // keepalive_send
        methods.add_method_mut("keepalive_send", |_lua, _this, _: ()| Ok(0i32));

        // set_blocking
        methods.add_method_mut("set_blocking", |_lua, _this, _blocking: bool| Ok(true));

        // get_blocking
        methods.add_method("get_blocking", |_lua, _this, _: ()| Ok(true));

        // session_last_error
        methods.add_method("session_last_error", |_lua, _this, _: ()| {
            let result = _lua.create_table()?;
            result.set("error", "")?;
            result.set("errcode", 0)?;
            Ok(result)
        });

        // session_flag
        methods.add_method_mut(
            "session_flag",
            |_lua, _this, (_flag, _value): (String, bool)| Ok(true),
        );

        // session_method_pref
        methods.add_method_mut(
            "session_method_pref",
            |_lua, _this, (_method, _pref): (String, String)| Ok(0i32),
        );

        // require_session_methods
        methods.add_method(
            "require_session_methods",
            |_lua, _this, _method_type: String| Ok(true),
        );

        // get_auth_methods (property)
        methods.add_method("get_auth_methods", |_lua, _this, _: ()| {
            Ok("publickey,password,keyboard-interactive".to_string())
        });

        // server_publickey (property)
        methods.add_method("server_publickey", |_lua, _this, _: ()| Ok(Value::Nil));
    }
}

#[cfg(not(feature = "nse-ssh2"))]
pub fn register_libssh2_library(
    lua: &mlua::Lua,
    _capability_ctx: &crate::capabilities::NseCapabilityContext,
) -> mlua::Result<()> {
    let globals = lua.globals();
    let libssh2 = lua.create_table()?;

    let session_fn = lua.create_function(|lua, (_host, _port): (String, Option<u16>)| {
        let result = lua.create_table()?;
        result.set("error", "libssh2 requires nse-ssh2 feature")?;
        Ok(result)
    })?;
    libssh2.set("session", session_fn)?;

    let version_fn = lua.create_function(|_lua, _: ()| Ok("1.0"))?;
    libssh2.set("version", version_fn)?;

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