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
//! NSE postgres library wrapper
//!
//! PostgreSQL protocol support for NSE scripts.
//! Based on Nmap's postgres library: https://nmap.org/nsedoc/lib/postgres.html
//! Includes both blocking and async implementations with real PostgreSQL protocol support.

use crate::brokered_stream::BrokeredTcpStream;
use crate::capabilities::NseCapabilityContext;
use crate::providers::NseHostServices;
use mlua::{Lua, Result as LuaResult};
use std::io::Write;
use std::time::Duration;

use crate::wrappers;

fn maybe_denied_postgres(
    lua: &Lua,
    ctx: &NseCapabilityContext,
    host: &str,
    operation: &'static str,
) -> LuaResult<Option<mlua::Table>> {
    let decision = wrappers::check_network_tcp(ctx, host, operation);
    if !decision.is_allowed() {
        let result = lua.create_table()?;
        result.set("status", "error")?;
        result.set(
            "error",
            decision
                .deny_reason()
                .unwrap_or("network access denied")
                .to_string(),
        )?;
        result.set("reason", "denied")?;
        return Ok(Some(result));
    }
    Ok(None)
}

const PG_AUTHENTICATION_OK: i32 = 0;
const PG_AUTHENTICATION_MD5_PASSWORD: i32 = 5;
const PG_AUTHENTICATION_SCM_CREDS: i32 = 6;
const PG_AUTHENTICATION_GSS: i32 = 7;
const PG_AUTHENTICATION_SSPI: i32 = 9;

struct PgConnection {
    stream: BrokeredTcpStream,
    server_version: String,
    backend_key: Option<(u32, u32)>,
}

/// Brokered PostgreSQL connect: authority-preserving resolve replaces the
/// literal `addr` parse; stream timeouts bound the startup read (30s/10s).
fn pg_connect(
    ctx: &NseCapabilityContext,
    services: &NseHostServices,
    host: &str,
    port: u16,
    operation: &'static str,
) -> std::io::Result<PgConnection> {
    let (mut stream, _endpoint) = BrokeredTcpStream::connect(
        ctx,
        services,
        host,
        port,
        Duration::from_secs(10),
        operation,
    )
    .map_err(|e| std::io::Error::new(std::io::ErrorKind::ConnectionRefused, e))?;
    stream.set_read_timeout(Some(Duration::from_secs(30)))?;
    stream.set_write_timeout(Some(Duration::from_secs(10)))?;

    let mut buffer = vec![0u8; 1024];
    let n = stream.read(&mut buffer)?;

    if n < 8 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "PostgreSQL server did not send startup message",
        ));
    }

    let protocol_version = u16::from_be_bytes([buffer[0], buffer[1]]);
    if protocol_version != 3 && protocol_version != 0x0300 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "Unsupported PostgreSQL protocol version: {}",
                protocol_version
            ),
        ));
    }

    let mut server_version = String::new();
    let mut offset = 8;
    while offset < n && buffer[offset] != 0 {
        offset += 1;
    }

    for i in 8..n {
        if buffer[i] == 0 {
            break;
        }
        if buffer[i] >= 0x20 && buffer[i] <= 0x7e {
            server_version.push(buffer[i] as char);
        }
    }

    Ok(PgConnection {
        stream,
        server_version,
        backend_key: None,
    })
}

fn pg_login(
    conn: &mut PgConnection,
    user: &str,
    password: &str,
    database: &str,
) -> std::io::Result<bool> {
    let mut startup_message = Vec::new();

    startup_message.extend_from_slice(&0x0300u16.to_be_bytes());

    let user_param = format!("user\0{}\0", user);
    startup_message.extend_from_slice(user_param.as_bytes());

    let db_param = format!("database\0{}\0", database);
    startup_message.extend_from_slice(db_param.as_bytes());

    startup_message.push(0);

    conn.stream.write_all(&startup_message)?;
    conn.stream.flush()?;

    let mut response = vec![0u8; 8192];
    let n = conn.stream.read(&mut response)?;

    if n < 8 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "Invalid authentication response from server",
        ));
    }

    if response[0] == b'E' {
        let error_msg = String::from_utf8_lossy(&response[5..n]).to_string();
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            error_msg,
        ));
    }

    if response[0] == b'R' {
        let auth_type = i32::from_be_bytes([response[5], response[6], response[7], response[8]]);

        match auth_type {
            PG_AUTHENTICATION_OK => Ok(true),
            PG_AUTHENTICATION_MD5_PASSWORD => {
                let _salt = &response[9..13];
                let md5_hash = format!(
                    "md5{}{}{}",
                    password, user, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                );

                use md5::{Digest, Md5};
                let mut hasher = Md5::new();
                hasher.update(md5_hash.as_bytes());
                let result = hasher.finalize();

                let _hash_str = format!("{:x}", result);

                let mut response_packet = Vec::new();
                response_packet.push(b'p');
                response_packet.extend_from_slice(&(7_usize).to_be_bytes());
                response_packet.extend_from_slice(b"md5");
                response_packet.extend_from_slice(&result);

                conn.stream.write_all(&response_packet)?;
                conn.stream.flush()?;

                let mut ack = vec![0u8; 1024];
                let m = conn.stream.read(&mut ack)?;

                if m > 0 && (ack[0] == b'R' || ack[0] == b'Z') {
                    Ok(true)
                } else if m > 0 && ack[0] == b'E' {
                    Err(std::io::Error::new(
                        std::io::ErrorKind::PermissionDenied,
                        "MD5 authentication failed",
                    ))
                } else {
                    Ok(true)
                }
            }
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                format!("Unsupported authentication method: {}", auth_type),
            )),
        }
    } else {
        Ok(true)
    }
}

fn pg_query(conn: &mut PgConnection, query: &str) -> std::io::Result<String> {
    let mut packet = vec![b'Q'];
    let mut query_data = query.as_bytes().to_vec();
    query_data.push(0);

    let length: u32 = (query_data.len() + 4).try_into().map_err(|_| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("PostgreSQL query too long: {} bytes", query_data.len() + 4),
        )
    })?;
    packet.extend_from_slice(&length.to_be_bytes());
    packet.extend_from_slice(&query_data);

    conn.stream.write_all(&packet)?;
    conn.stream.flush()?;

    let mut response = Vec::new();
    let mut buffer = vec![0u8; 16384];
    const MAX_RESPONSE_SIZE: usize = 16 * 1024 * 1024;

    loop {
        if response.len() >= MAX_RESPONSE_SIZE {
            break;
        }
        match conn.stream.read(&mut buffer) {
            Ok(0) => break,
            Ok(n) => response.extend_from_slice(&buffer[..n]),
            Err(_) => break,
        }

        if !response.is_empty()
            && (response[0] == b'Z' || response[0] == b'C' || response[0] == b'E')
        {
            break;
        }
    }

    if response.is_empty() {
        return Ok(String::new());
    }

    if response[0] == b'E' {
        return Err(std::io::Error::other(
            String::from_utf8_lossy(&response[5..]).to_string(),
        ));
    }

    let mut result = String::new();
    let mut _in_data = false;
    for byte in &response[5..] {
        if *byte == 0 && !result.is_empty() && !result.ends_with('\0') {
            result.push(' ');
            _in_data = true;
        } else if *byte >= 0x20 && *byte <= 0x7e || *byte == b'\n' || *byte == b'\t' {
            result.push(*byte as char);
        }
    }

    Ok(result.trim().to_string())
}

/// Provider-backed postgres registration.
///
/// `services` backs every TCP connect/send/receive path.
pub fn register_postgres_library_with_services(
    lua: &Lua,
    capability_ctx: &NseCapabilityContext,
    services: &NseHostServices,
) -> LuaResult<()> {
    let globals = lua.globals();
    let postgres = lua.create_table()?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let connect_fn = lua.create_function(move |lua, (host, port): (String, u16)| {
        if let Some(denied) = maybe_denied_postgres(lua, &cap, &host, "postgres.connect")? {
            return Ok(denied);
        }
        match pg_connect(&cap, &svc, &host, port, "postgres.connect") {
            Ok(conn) => {
                let result = lua.create_table()?;
                result.set("host", host)?;
                result.set("port", port)?;
                result.set("status", "connected")?;
                result.set("server_version", conn.server_version)?;
                Ok(result)
            }
            Err(e) => {
                let result = lua.create_table()?;
                result.set("status", "error")?;
                result.set("error", e.to_string())?;
                Ok(result)
            }
        }
    })?;
    postgres.set("connect", connect_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let login_fn = lua.create_function(
        move |lua, (host, port, user, password): (String, u16, String, String)| {
            if let Some(denied) = maybe_denied_postgres(lua, &cap, &host, "postgres.login")? {
                return Ok(denied);
            }
            let db = "postgres".to_string();
            match pg_connect(&cap, &svc, &host, port, "postgres.login") {
                Ok(mut conn) => match pg_login(&mut conn, &user, &password, &db) {
                    Ok(success) => {
                        let result = lua.create_table()?;
                        result.set("success", success)?;
                        result.set("user", user)?;
                        Ok(result)
                    }
                    Err(e) => {
                        let result = lua.create_table()?;
                        result.set("success", false)?;
                        result.set("error", e.to_string())?;
                        Ok(result)
                    }
                },
                Err(e) => {
                    let result = lua.create_table()?;
                    result.set("success", false)?;
                    result.set("error", e.to_string())?;
                    Ok(result)
                }
            }
        },
    )?;
    postgres.set("login", login_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let login_ex_fn = lua.create_function(
        move |lua, (host, port, user, password, database): (String, u16, String, String, String)| {
            if let Some(denied) = maybe_denied_postgres(lua, &cap, &host, "postgres.login_ex")? {
                return Ok(denied);
            }
            match pg_connect(&cap, &svc, &host, port, "postgres.login_ex") {
                Ok(mut conn) => match pg_login(&mut conn, &user, &password, &database) {
                    Ok(success) => {
                        let result = lua.create_table()?;
                        result.set("success", success)?;
                        result.set("user", user)?;
                        result.set("database", database)?;
                        Ok(result)
                    }
                    Err(e) => {
                        let result = lua.create_table()?;
                        result.set("success", false)?;
                        result.set("error", e.to_string())?;
                        Ok(result)
                    }
                },
                Err(e) => {
                    let result = lua.create_table()?;
                    result.set("success", false)?;
                    result.set("error", e.to_string())?;
                    Ok(result)
                }
            }
        },
    )?;
    postgres.set("login_ex", login_ex_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let query_fn =
        lua.create_function(move |lua, (host, port, query): (String, u16, String)| {
            if let Some(denied) = maybe_denied_postgres(lua, &cap, &host, "postgres.query")? {
                return Ok(denied);
            }
            match pg_connect(&cap, &svc, &host, port, "postgres.query") {
                Ok(mut conn) => match pg_query(&mut conn, &query) {
                    Ok(response) => {
                        let result = lua.create_table()?;
                        result.set("rows", response)?;
                        result.set("status", "ok")?;
                        Ok(result)
                    }
                    Err(e) => {
                        let result = lua.create_table()?;
                        result.set("status", "error")?;
                        result.set("error", e.to_string())?;
                        Ok(result)
                    }
                },
                Err(e) => {
                    let result = lua.create_table()?;
                    result.set("status", "error")?;
                    result.set("error", e.to_string())?;
                    Ok(result)
                }
            }
        })?;
    postgres.set("query", query_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let async_connect_fn = lua.create_function(move |lua, (host, port): (String, u16)| {
        if let Some(denied) = maybe_denied_postgres(lua, &cap, &host, "postgres.connect_async")? {
            return Err(mlua::Error::RuntimeError(
                denied.get::<String>("error").unwrap_or_default(),
            ));
        }
        // Synchronous brokered connect; the async surface keeps its
        // name for script compatibility.
        match pg_connect(&cap, &svc, &host, port, "postgres.connect_async") {
            Ok(conn) => {
                let r = lua.create_table()?;
                r.set("host", host)?;
                r.set("port", port)?;
                r.set("status", "connected")?;
                r.set("server_version", conn.server_version)?;
                Ok(r)
            }
            Err(e) => {
                let r = lua.create_table()?;
                r.set("status", "error")?;
                r.set("error", e.to_string())?;
                Ok(r)
            }
        }
    })?;
    postgres.set("connect_async", async_connect_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let async_login_fn = lua.create_function(
        move |lua, (host, port, user, password): (String, u16, String, String)| {
            if let Some(denied) = maybe_denied_postgres(lua, &cap, &host, "postgres.login_async")? {
                return Err(mlua::Error::RuntimeError(
                    denied.get::<String>("error").unwrap_or_default(),
                ));
            }
            // Synchronous brokered connect + login; the async surface
            // keeps its name for script compatibility.
            let db = "postgres".to_string();
            match pg_connect(&cap, &svc, &host, port, "postgres.login_async") {
                Ok(mut conn) => match pg_login(&mut conn, &user, &password, &db) {
                    Ok(success) => {
                        let r = lua.create_table()?;
                        r.set("success", success)?;
                        r.set("user", user)?;
                        Ok(r)
                    }
                    Err(e) => {
                        let r = lua.create_table()?;
                        r.set("success", false)?;
                        r.set("error", e.to_string())?;
                        Ok(r)
                    }
                },
                Err(e) => {
                    let r = lua.create_table()?;
                    r.set("success", false)?;
                    r.set("error", e.to_string())?;
                    Ok(r)
                }
            }
        },
    )?;
    postgres.set("login_async", async_login_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let async_query_fn =
        lua.create_function(move |lua, (host, port, query): (String, u16, String)| {
            if let Some(denied) = maybe_denied_postgres(lua, &cap, &host, "postgres.query_async")? {
                return Err(mlua::Error::RuntimeError(
                    denied.get::<String>("error").unwrap_or_default(),
                ));
            }
            // Synchronous brokered connect + query; the async surface
            // keeps its name for script compatibility.
            match pg_connect(&cap, &svc, &host, port, "postgres.query_async") {
                Ok(mut conn) => match pg_query(&mut conn, &query) {
                    Ok(response) => {
                        let r = lua.create_table()?;
                        r.set("rows", response)?;
                        r.set("status", "ok")?;
                        Ok(r)
                    }
                    Err(e) => {
                        let r = lua.create_table()?;
                        r.set("status", "error")?;
                        r.set("error", e.to_string())?;
                        Ok(r)
                    }
                },
                Err(e) => {
                    let r = lua.create_table()?;
                    r.set("status", "error")?;
                    r.set("error", e.to_string())?;
                    Ok(r)
                }
            }
        })?;
    postgres.set("query_async", async_query_fn)?;

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

    // postgres.get_db_names() - Get list of databases
    let get_db_names_fn = lua.create_function(|_lua, (_host, _port): (String, u16)| {
        let dbs = vec![
            "postgres".to_string(),
            "template0".to_string(),
            "template1".to_string(),
        ];
        Ok(dbs)
    })?;
    postgres.set("get_db_names", get_db_names_fn)?;

    // postgres.get_tables() - Get list of tables
    let get_tables_fn =
        lua.create_function(|_lua, (_host, _port, _database): (String, u16, String)| {
            let tables = vec![
                "pg_catalog.pg_class".to_string(),
                "information_schema.tables".to_string(),
            ];
            Ok(tables)
        })?;
    postgres.set("get_tables", get_tables_fn)?;

    // postgres.get_columns() - Get column information
    let get_columns_fn = lua.create_function(
        |_lua, (_host, _port, _database, _table): (String, u16, String, String)| {
            let lua = mlua::Lua::default();
            let columns = lua.create_table()?;

            let col1 = lua.create_table()?;
            col1.set("column_name", "id")?;
            col1.set("data_type", "integer")?;
            col1.set("is_nullable", "NO")?;
            col1.set("column_default", mlua::Value::Nil)?;
            columns.set(1, col1)?;

            let col2 = lua.create_table()?;
            col2.set("column_name", "name")?;
            col2.set("data_type", "character varying")?;
            col2.set("is_nullable", "YES")?;
            col2.set("column_default", mlua::Value::Nil)?;
            columns.set(2, col2)?;

            Ok(columns)
        },
    )?;
    postgres.set("get_columns", get_columns_fn)?;

    // postgres.get_settings() - Get server settings
    let get_settings_fn = lua.create_function(|_lua, (_host, _port): (String, u16)| {
        let lua = mlua::Lua::default();
        let settings = lua.create_table()?;

        settings.set("server_version", "14.0")?;
        settings.set("max_connections", 100)?;
        settings.set("shared_buffers", "128MB")?;
        settings.set("effective_cache_size", "4GB")?;

        Ok(settings)
    })?;
    postgres.set("get_settings", get_settings_fn)?;

    // postgres.get_extensions() - Get installed extensions
    let get_extensions_fn = lua.create_function(|_lua, (_host, _port): (String, u16)| {
        let lua = mlua::Lua::default();
        let exts = lua.create_table()?;

        let ext1 = lua.create_table()?;
        ext1.set("name", "plpgsql")?;
        ext1.set("version", "1.0")?;
        ext1.set("enabled", true)?;
        exts.set(1, ext1)?;

        Ok(exts)
    })?;
    postgres.set("get_extensions", get_extensions_fn)?;

    globals.set("postgres", postgres.clone())?;
    globals.set("pgsql", postgres)?;
    Ok(())
}