httpjail 0.6.2

Monitor and restrict HTTP/HTTPS requests from processes
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
pub mod dns;
mod nftables;
mod resources;
mod seccomp;

#[cfg(target_os = "linux")]
pub mod docker;

use super::Jail;
use super::JailConfig;
use crate::sys_resource::{ManagedResource, SystemResource};
use anyhow::{Context, Result};
use resources::{NFTable, NetnsResolv, NetworkNamespace, VethPair};
use std::os::unix::process::CommandExt;
use std::process::{Command, ExitStatus};
use tracing::{debug, info, warn};

// Linux namespace network configuration constants were previously fixed; the
// implementation now computes unique per‑jail subnets dynamically.

/// Format an IP address array as a string
pub fn format_ip(ip: [u8; 4]) -> String {
    format!("{}.{}.{}.{}", ip[0], ip[1], ip[2], ip[3])
}

/// Linux jail implementation using network namespaces
///
/// ## Architecture Overview
///
/// This jail creates an isolated network namespace where all traffic is transparently
/// redirected through our HTTP/HTTPS proxy. Unlike setting HTTP_PROXY environment variables,
/// this approach captures ALL network traffic, even from applications that don't respect
/// proxy settings.
///
/// ```
/// [Application in Namespace] ---> [nftables DNAT] ---> [Proxy on Host:HTTP/HTTPS]
///            |                                               |
///     (10.99.X.2)                                      (10.99.X.1)
///            |                                               |
///       [veth_ns] <------- veth pair --------> [veth_host on Host]
///            |                                               |
///      [Namespace]                                        [Host]
/// ```
///
/// ## Key Design Decisions
///
/// 1. **Network Namespace**: Complete isolation, no interference with host networking
/// 2. **veth Pair**: Virtual ethernet cable connecting namespace to host
/// 3. **Private IP Range**: Unique per-jail /30 within 10.99.0.0/16 (RFC1918)
/// 4. **nftables DNAT**: Transparent redirection without environment variables
/// 5. **DNS Override**: Handle systemd-resolved incompatibility with namespaces
///
/// ## Cleanup Guarantees
///
/// Resources are cleaned up in priority order:
/// 1. **Namespace deletion**: Automatically cleans up veth pair and namespace nftables rules
/// 2. **Host nftables table**: Atomic cleanup of entire table with all rules
/// 3. **Config directory**: /etc/netns/<namespace>/ removed if it exists
///
/// The namespace deletion is the critical cleanup - even if host nftables cleanup fails,
/// the jail is effectively destroyed once the namespace is gone.
///
/// Provides complete network isolation without persistent system state
pub struct LinuxJail {
    config: JailConfig,
    // IMPORTANT: Field order matters! Rust drops fields in declaration order (top to bottom).
    // We want cleanup to happen in reverse order of creation:
    // 1. DNS server stopped (explicit in Drop::drop)
    // 2. netns_resolv cleaned (unmount bind-mount, remove /etc/netns dir)
    // 3. nftables cleaned (remove firewall rules)
    // 4. veth_pair cleaned (delete veth pair)
    // 5. namespace cleaned (delete network namespace)
    netns_resolv: Option<ManagedResource<NetnsResolv>>,
    nftables: Option<ManagedResource<NFTable>>,
    veth_pair: Option<ManagedResource<VethPair>>,
    namespace: Option<ManagedResource<NetworkNamespace>>,
    // Host-side DNS server for DNAT redirection
    host_dns_server: Option<dns::DummyDnsServer>,
    // Per-jail computed networking (unique /30 inside 10.99/16)
    host_ip: [u8; 4],
    host_cidr: String,
    guest_cidr: String,
    subnet_cidr: String,
}

impl LinuxJail {
    fn validate_invoking_user() -> Result<()> {
        let uid = std::env::var("SUDO_UID")
            .ok()
            .and_then(|value| value.parse::<u32>().ok());
        let gid = std::env::var("SUDO_GID")
            .ok()
            .and_then(|value| value.parse::<u32>().ok());
        anyhow::ensure!(
            uid.is_some_and(|uid| uid != 0) && gid.is_some(),
            "Linux strong mode requires sudo from a non-root user"
        );
        Ok(())
    }

    fn build_command(&self, command: &[String], extra_env: &[(String, String)]) -> Result<Command> {
        if command.is_empty() {
            anyhow::bail!("No command specified");
        }

        debug!(
            "Executing command in namespace {}: {:?}",
            self.namespace_name(),
            command
        );

        // Check if we're running as root and should drop privileges
        let current_uid = unsafe { libc::getuid() };
        let drop_privs = if current_uid == 0 {
            // Running as root - check for SUDO_UID/SUDO_GID to drop privileges to original user
            match (std::env::var("SUDO_UID"), std::env::var("SUDO_GID")) {
                (Ok(uid), Ok(gid))
                    if uid.parse::<u32>().is_ok_and(|uid| uid != 0)
                        && gid.parse::<u32>().is_ok() =>
                {
                    debug!(
                        "Will drop privileges to uid={} gid={} after entering namespace",
                        uid, gid
                    );
                    Some((uid, gid))
                }
                _ => {
                    anyhow::bail!(
                        "Linux strong mode requires sudo from a non-root user so the command cannot alter its own network policy"
                    );
                }
            }
        } else {
            // Not root - no privilege dropping needed
            None
        };

        // DNS CONFIGURATION: Use standard ip netns exec approach
        //
        // ip netns exec automatically creates a mount namespace and bind-mounts
        // /etc/netns/<namespace>/resolv.conf over /etc/resolv.conf when present.
        //
        // KNOWN LIMITATION: This may fail on systems where /etc/resolv.conf is a symlink
        // to a target that doesn't exist in the mount namespace (e.g., systemd-resolved).
        // In such cases, DNS queries will still reach our dummy DNS server via the nftables
        // rules, but applications that directly check /etc/resolv.conf may see stale content.
        //
        // We cannot safely "fix" this because:
        // - Mount namespaces only isolate mount tables, not filesystems
        // - Any file operations (rm, cp, touch) affect the host
        // - Bind-mounts over symlinks require the symlink target to exist
        //
        // Reference: https://man7.org/linux/man-pages/man8/ip-netns.8.html

        // A private PID namespace and fresh /proc prevent same-UID payloads
        // from tracing or importing sockets from host-network processes.
        let mut cmd = Command::new("/usr/sbin/ip");
        cmd.args([
            "netns",
            "exec",
            &self.namespace_name(),
            "/usr/bin/unshare",
            "--pid",
            "--fork",
            "--kill-child=SIGKILL",
            "--mount-proc",
        ]);

        // Add setpriv for privilege dropping if needed
        if let Some((uid, gid)) = drop_privs {
            cmd.arg("/usr/bin/setpriv");
            cmd.arg("--no-new-privs");
            cmd.arg(format!("--reuid={}", uid));
            cmd.arg(format!("--regid={}", gid));
            cmd.arg("--clear-groups");
            cmd.arg("--");
        }

        // Add user command
        for arg in command {
            cmd.arg(arg);
        }

        // Set environment variables
        for (key, value) in extra_env {
            cmd.env(key, value);
        }

        // Preserve SUDO environment variables for consistency with macOS
        if let Ok(sudo_user) = std::env::var("SUDO_USER") {
            cmd.env("SUDO_USER", sudo_user);
        }
        if let Ok(sudo_uid) = std::env::var("SUDO_UID") {
            cmd.env("SUDO_UID", sudo_uid);
        }
        if let Ok(sudo_gid) = std::env::var("SUDO_GID") {
            cmd.env("SUDO_GID", sudo_gid);
        }

        debug!("Executing command: {:?}", cmd);

        // Note: We do NOT set HTTP_PROXY/HTTPS_PROXY environment variables here.
        // The jail uses nftables rules to transparently redirect traffic to the proxy,
        // making it work with applications that don't respect proxy environment variables.

        // Prevent access to host pathname Unix sockets (including local agents
        // capable of making requests outside this network namespace).
        // SAFETY: the pre-exec hook uses only raw syscalls and static BPF data.
        unsafe { cmd.pre_exec(seccomp::block_unix_sockets) };
        Ok(cmd)
    }

    pub fn new(config: JailConfig) -> Result<Self> {
        let (host_ip, host_cidr, guest_cidr, subnet_cidr) =
            Self::compute_subnet_for_jail(&config.jail_id);
        Ok(Self {
            config,
            netns_resolv: None,
            nftables: None,
            veth_pair: None,
            namespace: None,
            host_dns_server: None,
            host_ip,
            host_cidr,
            guest_cidr,
            subnet_cidr,
        })
    }

    /// Check if running as root
    fn check_root() -> Result<()> {
        // Check UID directly using libc
        #[cfg(target_os = "linux")]
        let uid = unsafe { libc::getuid() };
        #[cfg(not(target_os = "linux"))]
        let uid = 1000; // Non-root UID for non-Linux platforms

        if uid != 0 {
            anyhow::bail!(
                "Network namespace operations require root access. Please run with sudo."
            );
        }
        Ok(())
    }

    /// Get the namespace name from the config
    fn namespace_name(&self) -> String {
        format!("httpjail_{}", self.config.jail_id)
    }

    /// Get the veth host interface name
    fn veth_host(&self) -> String {
        format!("vh_{}", self.config.jail_id)
    }

    /// Get the veth namespace interface name
    fn veth_ns(&self) -> String {
        format!("vn_{}", self.config.jail_id)
    }

    /// Compute a stable unique /30 in 10.99.0.0/16 for this jail
    /// There are 16384 possible /30 subnets in the /16.
    fn compute_subnet_for_jail(jail_id: &str) -> ([u8; 4], String, String, String) {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        jail_id.hash(&mut hasher);
        let h = hasher.finish();
        let idx = (h % 16384) as u32; // 0..16383
        let base = idx * 4; // network base offset within 10.99/16
        let third = ((base >> 8) & 0xFF) as u8;
        let fourth = (base & 0xFF) as u8;
        let network = [10u8, 99u8, third, fourth];
        let host_ip = [
            network[0],
            network[1],
            network[2],
            network[3].saturating_add(1),
        ];
        let guest_ip = [
            network[0],
            network[1],
            network[2],
            network[3].saturating_add(2),
        ];
        let host_cidr = format!("{}/30", format_ip(host_ip));
        let guest_cidr = format!("{}/30", format_ip(guest_ip));
        let subnet_cidr = format!("{}/30", format_ip(network));
        (host_ip, host_cidr, guest_cidr, subnet_cidr)
    }

    /// Expose the host veth IPv4 address for a given jail_id.
    /// This allows early binding of the proxy to the precise interface IP
    /// without falling back to 0.0.0.0.
    pub fn compute_host_ip_for_jail_id(jail_id: &str) -> [u8; 4] {
        let (host_ip, _host_cidr, _guest_cidr, _subnet_cidr) =
            Self::compute_subnet_for_jail(jail_id);
        host_ip
    }

    /// Create the network namespace using ManagedResource
    fn create_namespace(&mut self) -> Result<()> {
        self.namespace = Some(ManagedResource::<NetworkNamespace>::create(
            &self.config.jail_id,
        )?);
        info!("Created network namespace: {}", self.namespace_name());
        Ok(())
    }

    /// Set up veth pair for namespace connectivity using ManagedResource
    fn setup_veth_pair(&mut self) -> Result<()> {
        // Create veth pair
        self.veth_pair = Some(ManagedResource::<VethPair>::create(&self.config.jail_id)?);

        debug!(
            "Created veth pair: {} <-> {}",
            self.veth_host(),
            self.veth_ns()
        );

        // Move veth_ns end into the namespace
        let output = Command::new("/usr/sbin/ip")
            .args([
                "link",
                "set",
                &self.veth_ns(),
                "netns",
                &self.namespace_name(),
            ])
            .output()
            .context("Failed to move veth to namespace")?;

        if !output.status.success() {
            anyhow::bail!(
                "Failed to move veth to namespace: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        Ok(())
    }

    /// Configure networking inside the namespace
    fn configure_namespace_networking(&self) -> Result<()> {
        let namespace_name = self.namespace_name();
        let veth_ns = self.veth_ns();

        // Format the host IP once
        let host_ip = format_ip(self.host_ip);

        // Commands to run inside the namespace
        let commands = vec![
            // Bring up loopback
            vec!["/usr/sbin/ip", "link", "set", "lo", "up"],
            // Configure veth interface with IP
            vec![
                "/usr/sbin/ip",
                "addr",
                "add",
                &self.guest_cidr,
                "dev",
                &veth_ns,
            ],
            vec!["/usr/sbin/ip", "link", "set", &veth_ns, "up"],
            // Add default route pointing to host
            vec!["/usr/sbin/ip", "route", "add", "default", "via", &host_ip],
        ];

        for cmd_args in commands {
            let mut cmd = Command::new("/usr/sbin/ip");
            cmd.args(["netns", "exec", &namespace_name]);
            cmd.args(&cmd_args);

            debug!("Executing in namespace: {:?}", cmd);
            let output = cmd.output().context(format!(
                "Failed to execute: ip netns exec {} {:?}",
                namespace_name, cmd_args
            ))?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                anyhow::bail!(
                    "Failed to configure namespace networking ({}): {}",
                    cmd_args.join(" "),
                    stderr
                );
            }
        }

        // Verify routes were added
        let mut verify_cmd = Command::new("/usr/sbin/ip");
        verify_cmd.args([
            "netns",
            "exec",
            &namespace_name,
            "/usr/sbin/ip",
            "route",
            "show",
        ]);
        if let Ok(output) = verify_cmd.output() {
            let routes = String::from_utf8_lossy(&output.stdout);
            info!(
                "Routes in namespace {} after configuration:\n{}",
                namespace_name, routes
            );

            if !routes.contains(&host_ip) && !routes.contains("default") {
                warn!(
                    "WARNING: No route to host {} found in namespace. Network may not work properly.",
                    host_ip
                );
            }
        }

        debug!("Configured networking inside namespace {}", namespace_name);
        Ok(())
    }

    /// Configure host side of veth pair
    fn configure_host_networking(&self) -> Result<()> {
        let veth_host = self.veth_host();

        // Configure host side of veth
        let commands = vec![
            vec!["addr", "add", &self.host_cidr, "dev", &veth_host],
            vec!["link", "set", &veth_host, "up"],
        ];

        for cmd_args in commands {
            let output = Command::new("/usr/sbin/ip")
                .args(&cmd_args)
                .output()
                .context(format!("Failed to execute: ip {:?}", cmd_args))?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                // Ignore "File exists" errors for IP addresses (might be from previous run)
                if !stderr.contains("File exists") {
                    anyhow::bail!(
                        "Failed to configure host networking (ip {}): {}",
                        cmd_args.join(" "),
                        stderr
                    );
                }
            }
        }

        // Proxy and dummy DNS traffic is delivered to the host locally; host-wide
        // IP forwarding is unnecessary and must not be changed by a jail.

        debug!("Configured host side networking for {}", veth_host);
        Ok(())
    }

    /// Add nftables rules inside the namespace for traffic redirection
    ///
    /// We use DNAT (Destination NAT) instead of REDIRECT for a critical reason:
    /// - REDIRECT changes the destination to 127.0.0.1 (localhost) within the namespace
    /// - Our proxy runs on the HOST, not inside the namespace
    /// - DNAT allows us to redirect to the host's IP address (10.99.X.1) where the proxy is actually listening
    /// - This is why we must use DNAT to 10.99.X.1:PORT instead of REDIRECT
    fn setup_namespace_nftables(&self) -> Result<()> {
        let namespace_name = self.namespace_name();
        let host_ip = format_ip(self.host_ip);

        // Create namespace-side nftables rules with DNS redirection
        let _table = nftables::NFTable::new_namespace_table_with_dns(
            &namespace_name,
            &host_ip,
            self.config.http_proxy_port,
            self.config.https_proxy_port,
            53, // DNS server port (unused but kept for API compatibility)
        )?;

        // The table will be cleaned up automatically when it goes out of scope
        // But we want to keep it alive for the duration of the jail
        std::mem::forget(_table);

        Ok(())
    }

    /// Setup NAT on the host for namespace connectivity
    fn setup_host_nat(&mut self) -> Result<()> {
        // Create NFTable resource
        let mut nftable = ManagedResource::<NFTable>::create(&self.config.jail_id)?;

        // Create and add the host-side nftables table
        if let Some(table_wrapper) = nftable.inner_mut() {
            let table = nftables::NFTable::new_host_table(
                &self.config.jail_id,
                &self.subnet_cidr,
                self.config.http_proxy_port,
                self.config.https_proxy_port,
            )?;
            table_wrapper.set_table(table);

            info!(
                "Set up NAT rules for namespace {} with subnet {}",
                self.namespace_name(),
                self.subnet_cidr
            );
        }

        self.nftables = Some(nftable);
        Ok(())
    }

    /// Start DNS server using /etc/netns/ mechanism
    ///
    /// ## DNS Strategy Overview
    ///
    /// Uses Linux kernel's built-in /etc/netns/ feature:
    ///
    /// 1. **Create /etc/netns/httpjail_<id>/resolv.conf** pointing to host_ip
    ///    - Kernel automatically bind-mounts it when entering namespace
    ///    - All DNS queries from namespace go to host_ip
    ///    - Works with symlinked /etc/resolv.conf
    ///    - Standard Linux mechanism, simple and robust
    ///
    /// 2. **Host DNS server** (runs in this process on host side):
    ///    - Binds to host_ip:53 on the host side of the veth pair
    ///    - Handles all DNS queries from the namespace
    ///    - Returns dummy IP 6.6.6.6 to prevent data exfiltration
    fn start_dns_server(&mut self) -> Result<()> {
        let host_ip_str = format!(
            "{}.{}.{}.{}",
            self.host_ip[0], self.host_ip[1], self.host_ip[2], self.host_ip[3]
        );

        // 1. Create /etc/netns/httpjail_<id>/resolv.conf (kernel auto-mounts it)
        info!(
            "Creating /etc/netns resolv.conf with nameserver {}",
            host_ip_str
        );

        let netns_resolv = NetnsResolv::create_with_nameserver(&self.config.jail_id, &host_ip_str)
            .context("Failed to create /etc/netns resolv.conf")?;

        self.netns_resolv = Some(ManagedResource::from_resource(netns_resolv));

        // 2. Start host DNS server
        info!("Starting host DNS server on {}", host_ip_str);

        let mut host_server = dns::DummyDnsServer::new();
        let host_addr = format!("{}:53", host_ip_str);
        host_server
            .start(&host_addr)
            .context("Failed to start host DNS server")?;

        info!("Started host DNS server on {}", host_addr);
        self.host_dns_server = Some(host_server);

        Ok(())
    }

    /// Stop the DNS server
    fn stop_dns_server(&mut self) {
        // Stop host DNS server (runs in threads, cleanup on drop)
        if let Some(_server) = self.host_dns_server.take() {
            debug!("Stopping host DNS server (cleanup on drop)");
        }
    }
}

impl Drop for LinuxJail {
    fn drop(&mut self) {
        // Stop the DNS server if running
        self.stop_dns_server();
    }
}

impl Jail for LinuxJail {
    fn setup(&mut self, _proxy_port: u16) -> Result<()> {
        // Reject unsafe privilege retention before allocating jail resources.
        Self::check_root()?;
        Self::validate_invoking_user()?;

        // Create network namespace
        self.create_namespace()?;

        // Set up veth pair
        self.setup_veth_pair()?;

        // Configure host networking FIRST so the veth link is up
        self.configure_host_networking()?;

        // Configure namespace networking after host side is ready
        self.configure_namespace_networking()?;

        // Start the dummy DNS server in the namespace
        self.start_dns_server()?;

        // Set up NAT for namespace connectivity
        self.setup_host_nat()?;

        // Add nftables rules inside namespace
        self.setup_namespace_nftables()?;

        info!(
            "Linux jail setup complete using namespace {} with HTTP proxy on port {} and HTTPS proxy on port {}",
            self.namespace_name(),
            self.config.http_proxy_port,
            self.config.https_proxy_port
        );
        Ok(())
    }

    fn execute(&self, command: &[String], extra_env: &[(String, String)]) -> Result<ExitStatus> {
        super::run_command(self.build_command(command, extra_env)?, None)
    }

    fn execute_with_timeout(
        &self,
        command: &[String],
        extra_env: &[(String, String)],
        timeout: std::time::Duration,
    ) -> Result<ExitStatus> {
        super::run_command(self.build_command(command, extra_env)?, Some(timeout))
    }

    fn cleanup(&self) -> Result<()> {
        // Since the jail might be in an Arc (e.g., for signal handling),
        // we can't rely on Drop alone. We need to explicitly trigger cleanup
        // of the managed resources by taking them out of the jail.
        // However, since cleanup takes &self not &mut self, we can't modify the jail.
        // The best we can do is ensure the orphan cleanup works.
        info!("Triggering jail cleanup for {}", self.config.jail_id);

        // Call the static cleanup method which will clean up all resources
        Self::cleanup_orphaned(&self.config.jail_id)?;

        Ok(())
    }

    fn jail_id(&self) -> &str {
        &self.config.jail_id
    }

    fn cleanup_orphaned(jail_id: &str) -> Result<()>
    where
        Self: Sized,
    {
        debug!("Cleaning up orphaned Linux jail: {}", jail_id);

        // Propagate failures instead of relying on Drop (which can only log them).
        // Only remove the namespace name after deleting host-side resources.
        NetnsResolv::for_existing(jail_id).cleanup()?;
        NFTable::for_existing(jail_id).cleanup()?;
        VethPair::for_existing(jail_id).cleanup()?;
        NetworkNamespace::for_existing(jail_id).cleanup()?;
        Ok(())
    }
}

impl Clone for LinuxJail {
    fn clone(&self) -> Self {
        // Note: We don't clone the ManagedResource fields as they represent
        // system resources that shouldn't be duplicated
        Self {
            config: self.config.clone(),
            netns_resolv: None,
            nftables: None,
            veth_pair: None,
            namespace: None,
            host_dns_server: None,
            host_ip: self.host_ip,
            host_cidr: self.host_cidr.clone(),
            guest_cidr: self.guest_cidr.clone(),
            subnet_cidr: self.subnet_cidr.clone(),
        }
    }
}