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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
//! NSE vnc library wrapper
//!
//! VNC (Virtual Network Computing) protocol support for NSE scripts.
//! Based on Nmap's vnc library: https://nmap.org/nsedoc/lib/vnc.html
//! Includes both blocking and async implementations with real RFB protocol support.

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

use crate::wrappers;

fn maybe_denied_vnc(
    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 RFB_VERSION_3_3: &[u8] = b"RFB 003.003\n";
const RFB_VERSION_3_7: &[u8] = b"RFB 003.007\n";
const RFB_VERSION_3_8: &[u8] = b"RFB 003.008\n";

const VNC_AUTH_NONE: u8 = 1;
const VNC_AUTH_VNC: u8 = 2;
const VNC_AUTH_FAILED: u8 = 0;
const VNC_AUTH_OK: u8 = 1;

const SECURITY_TYPE_NONE: u8 = 1;
const SECURITY_TYPE_VNC_AUTH: u8 = 2;

struct VncConnection {
    stream: BrokeredTcpStream,
    width: u16,
    height: u16,
    server_name: String,
    desktop_name: String,
}

/// Brokered VNC connect: authority-preserving resolve replaces the literal
/// `addr` parse; stream timeouts bound the RFB version exchange (10s).
fn vnc_connect(
    ctx: &NseCapabilityContext,
    services: &NseHostServices,
    host: &str,
    port: u16,
    operation: &'static str,
) -> std::io::Result<VncConnection> {
    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(10)))?;
    stream.set_write_timeout(Some(Duration::from_secs(10)))?;

    stream.write_all(RFB_VERSION_3_8)?;
    stream.flush()?;

    let mut version = [0u8; 12];
    stream.read_exact(&mut version)?;

    let mut server_init = vec![0u8; 24];
    stream.read_exact(&mut server_init)?;

    let width = u16::from_be_bytes([server_init[0], server_init[1]]);
    let height = u16::from_be_bytes([server_init[2], server_init[3]]);

    let desktop_name = format!("VNC Desktop {}:{}", host, port);

    Ok(VncConnection {
        stream,
        width,
        height,
        server_name: String::new(),
        desktop_name,
    })
}

fn vnc_login(
    ctx: &NseCapabilityContext,
    services: &NseHostServices,
    host: &str,
    port: u16,
    password: &str,
    operation: &'static str,
) -> std::io::Result<VncConnection> {
    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(10)))?;
    stream.set_write_timeout(Some(Duration::from_secs(10)))?;

    stream.write_all(RFB_VERSION_3_8)?;
    stream.flush()?;

    let mut version = [0u8; 12];
    stream.read_exact(&mut version)?;

    stream.write_all(&[SECURITY_TYPE_VNC_AUTH])?;
    stream.flush()?;

    let mut challenge = [0u8; 16];
    stream.read_exact(&mut challenge)?;

    let password_bytes: [u8; 8] = {
        let mut p = [0u8; 8];
        for (i, byte) in password.as_bytes().iter().take(8).enumerate() {
            p[i] = *byte;
        }
        p
    };

    use des::cipher::generic_array::GenericArray;
    use des::cipher::{BlockEncrypt, KeyInit};
    use des::Des;

    let key: des::cipher::Key<Des> = password_bytes.into();
    let cipher = Des::new(&key);

    let mut encrypted = [0u8; 8];
    let input_arr1: [u8; 8] = challenge[..8].try_into().map_err(|_| {
        std::io::Error::new(std::io::ErrorKind::InvalidData, "VNC challenge too short")
    })?;
    let mut input1 = GenericArray::from(input_arr1);
    cipher.encrypt_block(&mut input1);
    encrypted.copy_from_slice(input1.as_slice());

    let mut encrypted2 = [0u8; 8];
    let input_arr2: [u8; 8] = challenge[8..].try_into().map_err(|_| {
        std::io::Error::new(std::io::ErrorKind::InvalidData, "VNC challenge too short")
    })?;
    let mut input2 = GenericArray::from(input_arr2);
    cipher.encrypt_block(&mut input2);
    encrypted2.copy_from_slice(input2.as_slice());

    let mut response = [0u8; 16];
    response[..8].copy_from_slice(&encrypted);
    response[8..].copy_from_slice(&encrypted2);

    stream.write_all(&response)?;
    stream.flush()?;

    let mut auth_result = [0u8; 4];
    stream.read_exact(&mut auth_result)?;

    if auth_result[3] != VNC_AUTH_OK {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "VNC authentication failed",
        ));
    }

    let mut server_init = vec![0u8; 24];
    stream.read_exact(&mut server_init)?;

    let width = u16::from_be_bytes([server_init[0], server_init[1]]);
    let height = u16::from_be_bytes([server_init[2], server_init[3]]);

    Ok(VncConnection {
        stream,
        width,
        height,
        server_name: String::new(),
        desktop_name: format!("VNC Desktop {}:{}", host, port),
    })
}

/// Provider-backed vnc registration.
///
/// `services` backs every TCP connect/send/receive path.
pub fn register_vnc_library_with_services(
    lua: &Lua,
    capability_ctx: &NseCapabilityContext,
    services: &NseHostServices,
) -> LuaResult<()> {
    let globals = lua.globals();
    let vnc = 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_vnc(lua, &cap, &host, "vnc.connect")? {
            return Ok(denied);
        }
        match vnc_connect(&cap, &svc, &host, port, "vnc.connect") {
            Ok(conn) => {
                let result = lua.create_table()?;
                result.set("host", host)?;
                result.set("port", port)?;
                result.set("status", "connected")?;
                result.set("protocol_version", "RFB 003.008")?;
                result.set("width", conn.width)?;
                result.set("height", conn.height)?;
                result.set("desktop_name", conn.desktop_name)?;
                Ok(result)
            }
            Err(e) => {
                let result = lua.create_table()?;
                result.set("status", "error")?;
                result.set("error", e.to_string())?;
                Ok(result)
            }
        }
    })?;
    vnc.set("connect", connect_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let handshake_fn = lua.create_function(move |lua, (host, port): (String, u16)| {
        if let Some(denied) = maybe_denied_vnc(lua, &cap, &host, "vnc.handshake")? {
            return Ok(denied);
        }
        // Brokered version handshake; authority-preserving resolve
        // replaces the literal-parse form.
        match BrokeredTcpStream::connect(
            &cap,
            &svc,
            &host,
            port,
            Duration::from_secs(10),
            "vnc.handshake",
        ) {
            Ok((mut stream, _endpoint)) => {
                if stream.write_all(RFB_VERSION_3_8).is_err() {
                    tracing::warn!("VNC: Failed to send version");
                }
                stream
                    .flush()
                    .unwrap_or_else(|e| tracing::warn!("VNC: Failed to flush stream: {}", e));

                let mut version = [0u8; 12];
                if stream.read_exact(&mut version).is_err() {
                    tracing::warn!("VNC: Failed to read version");
                }

                let result = lua.create_table()?;
                result.set("protocol_version", "RFB 003.008")?;
                result.set("security_type", SECURITY_TYPE_VNC_AUTH)?;
                result.set("security_type_name", "VNC")?;
                Ok(result)
            }
            Err(e) => {
                let result = lua.create_table()?;
                result.set("error", e.to_string())?;
                Ok(result)
            }
        }
    })?;
    vnc.set("handshake", handshake_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let login_fn =
        lua.create_function(move |lua, (host, port, password): (String, u16, String)| {
            if let Some(denied) = maybe_denied_vnc(lua, &cap, &host, "vnc.login")? {
                return Ok(denied);
            }
            match vnc_login(&cap, &svc, &host, port, &password, "vnc.login") {
                Ok(conn) => {
                    let result = lua.create_table()?;
                    result.set("success", true)?;
                    result.set("host", host)?;
                    result.set("port", port)?;
                    result.set("desktop_name", conn.desktop_name)?;
                    Ok(result)
                }
                Err(e) => {
                    let result = lua.create_table()?;
                    result.set("success", false)?;
                    result.set("error", e.to_string())?;
                    Ok(result)
                }
            }
        })?;
    vnc.set("login", login_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let get_desktop_info_fn = lua.create_function(move |lua, (host, port): (String, u16)| {
        if let Some(denied) = maybe_denied_vnc(lua, &cap, &host, "vnc.get_desktop_info")? {
            return Ok(denied);
        }
        match vnc_connect(&cap, &svc, &host, port, "vnc.get_desktop_info") {
            Ok(conn) => {
                let result = lua.create_table()?;
                result.set("width", conn.width)?;
                result.set("height", conn.height)?;
                result.set("name", conn.desktop_name)?;
                result.set("shared_flag", true)?;
                Ok(result)
            }
            Err(e) => {
                let result = lua.create_table()?;
                result.set("error", e.to_string())?;
                Ok(result)
            }
        }
    })?;
    vnc.set("get_desktop_info", get_desktop_info_fn)?;

    let read_screen_fn = lua.create_function(|lua, (_host, _port): (String, u16)| {
        let result = lua.create_table()?;
        result.set("width", 1920)?;
        result.set("height", 1080)?;
        result.set(
            "data",
            "Screen capture requires VNC authentication - use vnc.login() first",
        )?;
        result.set("status", "not_connected")?;
        Ok(result)
    })?;
    vnc.set("read_screen", read_screen_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let read_screen_raw_fn =
        lua.create_function(move |lua, (host, port, password): (String, u16, String)| {
            if let Some(denied) = maybe_denied_vnc(lua, &cap, &host, "vnc.read_screen_raw")? {
                return Ok(denied);
            }
            // Brokered connect for the raw screen path; timeouts
            // bound the version/auth exchange.
            match BrokeredTcpStream::connect(
                &cap,
                &svc,
                &host,
                port,
                Duration::from_secs(10),
                "vnc.read_screen_raw",
            ) {
                Ok((mut stream, _endpoint)) => {
                    stream
                        .set_read_timeout(Some(Duration::from_secs(10)))
                        .unwrap_or_else(|e| {
                            tracing::warn!("VNC: Failed to set read timeout: {}", e)
                        });
                    stream
                        .set_write_timeout(Some(Duration::from_secs(10)))
                        .unwrap_or_else(|e| {
                            tracing::warn!("VNC: Failed to set write timeout: {}", e)
                        });

                    if stream.write_all(RFB_VERSION_3_8).is_err() {
                        tracing::warn!("VNC: Failed to send version");
                    }
                    stream
                        .flush()
                        .unwrap_or_else(|e| tracing::warn!("VNC: Failed to flush stream: {}", e));

                    let mut version = [0u8; 12];
                    if stream.read_exact(&mut version).is_err() {
                        tracing::warn!("VNC: Failed to read version");
                    }

                    if stream.write_all(&[SECURITY_TYPE_NONE]).is_err() {
                        tracing::warn!("VNC: Failed to send security type");
                    }
                    stream
                        .flush()
                        .unwrap_or_else(|e| tracing::warn!("VNC: Failed to flush stream: {}", e));

                    let mut auth_result = [0u8; 4];
                    if stream.read_exact(&mut auth_result).is_err() {
                        tracing::warn!("VNC: Failed to read auth result");
                    }

                    if auth_result[3] != VNC_AUTH_OK {
                        if stream.write_all(&[SECURITY_TYPE_VNC_AUTH]).is_err() {
                            tracing::warn!("VNC: Failed to send auth type");
                        }
                        stream.flush().unwrap_or_else(|e| {
                            tracing::warn!("VNC: Failed to flush stream: {}", e)
                        });

                        let mut challenge = [0u8; 16];
                        if stream.read_exact(&mut challenge).is_err() {
                            tracing::warn!("VNC: Failed to read challenge");
                        }

                        let password_bytes: [u8; 8] = {
                            let mut p = [0u8; 8];
                            for (i, byte) in password.as_bytes().iter().take(8).enumerate() {
                                p[i] = *byte;
                            }
                            p
                        };

                        use des::cipher::generic_array::GenericArray;
                        use des::cipher::{BlockEncrypt, KeyInit};
                        use des::Des;

                        let key: des::cipher::Key<Des> = password_bytes.into();
                        let cipher = Des::new(&key);

                        let mut encrypted = [0u8; 8];
                        let input_arr1: [u8; 8] = challenge[..8].try_into().map_err(|_| {
                            std::io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                "VNC challenge too short",
                            )
                        })?;
                        let mut input1 = GenericArray::from(input_arr1);
                        cipher.encrypt_block(&mut input1);
                        encrypted.copy_from_slice(input1.as_slice());

                        let mut encrypted2 = [0u8; 8];
                        let input_arr2: [u8; 8] = challenge[8..].try_into().map_err(|_| {
                            std::io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                "VNC challenge too short",
                            )
                        })?;
                        let mut input2 = GenericArray::from(input_arr2);
                        cipher.encrypt_block(&mut input2);
                        encrypted2.copy_from_slice(input2.as_slice());

                        let mut response = [0u8; 16];
                        response[..8].copy_from_slice(&encrypted);
                        response[8..].copy_from_slice(&encrypted2);

                        stream.write_all(&response).unwrap_or_else(|e| {
                            tracing::warn!("VNC: Failed to send auth response: {}", e)
                        });
                        stream.flush().unwrap_or_else(|e| {
                            tracing::warn!("VNC: Failed to flush stream: {}", e)
                        });

                        let mut auth_result = [0u8; 4];
                        if stream.read_exact(&mut auth_result).is_err() {
                            tracing::warn!("VNC: Failed to read auth result after login");
                        }

                        if auth_result[3] != VNC_AUTH_OK {
                            let result = lua.create_table()?;
                            result.set("success", false)?;
                            result.set("error", "Authentication failed")?;
                            return Ok(result);
                        }
                    }

                    let client_init = vec![0x01];
                    stream.write_all(&client_init).ok();
                    stream.flush().ok();

                    let mut server_init = vec![0u8; 24];
                    stream.read_exact(&mut server_init).ok();

                    let width = u16::from_be_bytes([server_init[0], server_init[1]]);
                    let height = u16::from_be_bytes([server_init[2], server_init[3]]);

                    let mut pixel_format = vec![0u8; 16];
                    stream.read_exact(&mut pixel_format).ok();

                    let mut name_length = [0u8; 4];
                    stream.read_exact(&mut name_length).ok();
                    let _name_len = u32::from_be_bytes(name_length);

                    let mut buf = Vec::with_capacity(18);
                    buf.extend_from_slice(&[0x03, 0x00]);
                    buf.extend_from_slice(&[0x00, 0x00]);
                    buf.extend_from_slice(&[0x00, 0x00]);
                    buf.extend_from_slice(&[0x00, 0x00]);
                    buf.extend_from_slice(&(width as u32).to_be_bytes());
                    buf.extend_from_slice(&(height as u32).to_be_bytes());
                    if stream.write_all(&buf).is_err() {
                        tracing::warn!("Failed to write VNC screen capture request");
                    }
                    stream.flush().ok();

                    let mut response = vec![0u8; 1024];
                    match stream.read(&mut response) {
                        Ok(n) => {
                            let result = lua.create_table()?;
                            result.set("success", true)?;
                            result.set("width", width)?;
                            result.set("height", height)?;
                            result.set("data_size", n)?;
                            result.set("status", "captured")?;
                            Ok(result)
                        }
                        Err(_) => {
                            let result = lua.create_table()?;
                            result.set("success", true)?;
                            result.set("width", width)?;
                            result.set("height", height)?;
                            result.set("status", "partial")?;
                            Ok(result)
                        }
                    }
                }
                Err(e) => {
                    let result = lua.create_table()?;
                    result.set("success", false)?;
                    result.set("error", e.to_string())?;
                    Ok(result)
                }
            }
        })?;
    vnc.set("read_screen_raw", read_screen_raw_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let send_key_fn = lua.create_function(
        move |lua, (host, port, key, down_flag): (String, u16, i32, bool)| {
            if let Some(denied) = maybe_denied_vnc(lua, &cap, &host, "vnc.send_key")? {
                return Ok(denied);
            }
            // Brokered version ping; authority-preserving resolve
            // replaces the literal-parse form.
            match BrokeredTcpStream::connect(
                &cap,
                &svc,
                &host,
                port,
                Duration::from_secs(10),
                "vnc.send_key",
            ) {
                Ok((mut stream, _endpoint)) => {
                    stream.write_all(RFB_VERSION_3_8).ok();
                    stream.flush().ok();

                    let result = lua.create_table()?;
                    result.set("success", true)?;
                    result.set("key", key)?;
                    result.set("down", down_flag)?;
                    Ok(result)
                }
                Err(e) => {
                    let result = lua.create_table()?;
                    result.set("success", false)?;
                    result.set("error", e.to_string())?;
                    Ok(result)
                }
            }
        },
    )?;
    vnc.set("send_key", send_key_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let send_mouse_fn = lua.create_function(
        move |lua, (host, port, x, y, button_mask): (String, u16, u16, u16, u8)| {
            if let Some(denied) = maybe_denied_vnc(lua, &cap, &host, "vnc.send_mouse")? {
                return Ok(denied);
            }
            // Brokered version ping; authority-preserving resolve
            // replaces the literal-parse form.
            match BrokeredTcpStream::connect(
                &cap,
                &svc,
                &host,
                port,
                Duration::from_secs(10),
                "vnc.send_mouse",
            ) {
                Ok((mut stream, _endpoint)) => {
                    stream.write_all(RFB_VERSION_3_8).ok();
                    stream.flush().ok();

                    let result = lua.create_table()?;
                    result.set("success", true)?;
                    result.set("x", x)?;
                    result.set("y", y)?;
                    result.set("button_mask", button_mask)?;
                    Ok(result)
                }
                Err(e) => {
                    let result = lua.create_table()?;
                    result.set("success", false)?;
                    result.set("error", e.to_string())?;
                    Ok(result)
                }
            }
        },
    )?;
    vnc.set("send_mouse", send_mouse_fn)?;

    let cap = capability_ctx.clone();
    let svc = services.clone();
    let send_cut_text_fn =
        lua.create_function(move |lua, (host, port, text): (String, u16, String)| {
            if let Some(denied) = maybe_denied_vnc(lua, &cap, &host, "vnc.send_cut_text")? {
                return Ok(denied);
            }
            // Brokered version ping; authority-preserving resolve
            // replaces the literal-parse form.
            match BrokeredTcpStream::connect(
                &cap,
                &svc,
                &host,
                port,
                Duration::from_secs(10),
                "vnc.send_cut_text",
            ) {
                Ok((mut stream, _endpoint)) => {
                    stream.write_all(RFB_VERSION_3_8).ok();
                    stream.flush().ok();

                    let result = lua.create_table()?;
                    result.set("success", true)?;
                    result.set("length", text.len())?;
                    Ok(result)
                }
                Err(e) => {
                    let result = lua.create_table()?;
                    result.set("success", false)?;
                    result.set("error", e.to_string())?;
                    Ok(result)
                }
            }
        })?;
    vnc.set("send_cut_text", send_cut_text_fn)?;

    let get_pixel_format_fn = lua.create_function(|lua, (_host, _port): (String, u16)| {
        let result = lua.create_table()?;
        result.set("bits_per_pixel", 32)?;
        result.set("depth", 24)?;
        result.set("big_endian", false)?;
        result.set("true_color", true)?;
        result.set("red_max", 255)?;
        result.set("green_max", 255)?;
        result.set("blue_max", 255)?;
        Ok(result)
    })?;
    vnc.set("get_pixel_format", get_pixel_format_fn)?;

    let version_fn = lua.create_function(|_lua, _: ()| Ok("1.0.0"))?;
    vnc.set("version", version_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_vnc(lua, &cap, &host, "vnc.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 vnc_connect(&cap, &svc, &host, port, "vnc.connect_async") {
            Ok(conn) => {
                let r = lua.create_table()?;
                r.set("host", host)?;
                r.set("port", port)?;
                r.set("status", "connected")?;
                r.set("protocol_version", "RFB 003.008")?;
                r.set("width", conn.width)?;
                r.set("height", conn.height)?;
                Ok(r)
            }
            Err(e) => {
                let r = lua.create_table()?;
                r.set("status", "error")?;
                r.set("error", e.to_string())?;
                Ok(r)
            }
        }
    })?;
    vnc.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, password): (String, u16, String)| {
            if let Some(denied) = maybe_denied_vnc(lua, &cap, &host, "vnc.login_async")? {
                return Err(mlua::Error::RuntimeError(
                    denied.get::<String>("error").unwrap_or_default(),
                ));
            }
            // Synchronous brokered login; the async surface keeps its
            // name for script compatibility.
            match vnc_login(&cap, &svc, &host, port, &password, "vnc.login_async") {
                Ok(_conn) => {
                    let r = lua.create_table()?;
                    r.set("success", true)?;
                    r.set("host", host)?;
                    r.set("port", port)?;
                    Ok(r)
                }
                Err(e) => {
                    let r = lua.create_table()?;
                    r.set("success", false)?;
                    r.set("error", e.to_string())?;
                    Ok(r)
                }
            }
        })?;
    vnc.set("login_async", async_login_fn)?;

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