vopono_core 0.1.22

Library code for running VPN connections in network namespaces
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
use std::{
    ffi::CString,
    io::Write,
    os::fd::{BorrowedFd, FromRawFd, IntoRawFd},
    os::unix::{io::RawFd, process::CommandExt},
    path::{Path, PathBuf},
    process::{Child, Command, Stdio},
};

use anyhow::{Context, bail};
use log::debug;
use nix::{
    fcntl::{OFlag, open},
    mount::{MsFlags, mount},
    sched::{CloneFlags, setns, unshare},
    sys::stat::Mode,
    unistd::close,
};

use super::{netns::NetworkNamespace, port_forwarding::Forwarder};
use crate::util::{
    check_process_running, env_vars::set_env_vars, get_running_process_pids, parse_command_str,
    process_is_in_network_namespace,
};

// NOTE: Known single-instance clients (browsers, and eventually launchers such
// as gnome-terminal-server) are only *warned* about today; fully blocking them
// would also block legitimate separate-profile launches. A blocking policy
// would need per-application profile detection and is deliberately left as
// future work.
const SINGLE_INSTANCE_APPLICATIONS: &[&str] = &[
    "google-chrome-stable",
    "google-chrome-beta",
    "google-chrome",
    "google-chrome-unstable",
    "chromium",
    "chromium-browser",
    "brave",
    "brave-browser",
    "firefox",
    "firefox-developer-edition",
    "firefox-bin",
    "librewolf",
    "vivaldi",
    "vivaldi-stable",
    "opera",
    "microsoft-edge",
    "microsoft-edge-stable",
];

pub struct ApplicationWrapper {
    pub handle: Child,
    pub port_forwarding: Option<Box<dyn Forwarder>>,
    _etc_overlay: Option<tempfile::TempDir>,
}

impl ApplicationWrapper {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        netns: &NetworkNamespace,
        application: &str,
        user: Option<String>,
        group: Option<String>,
        working_directory: Option<PathBuf>,
        port_forwarding: Option<Box<dyn Forwarder>>,
        silent: bool,
        host_env_vars: &std::collections::HashMap<String, String>,
        pipe_io: bool,
        stdio_fds: Option<(RawFd, RawFd, RawFd)>,
        take_controlling_tty: bool,
    ) -> anyhow::Result<Self> {
        let app_vec = parse_command_str(application)?;

        let shared_process_name = app_vec.first().and_then(|program| {
            Path::new(program)
                .file_name()
                .and_then(|name| name.to_str())
                .filter(|name| SINGLE_INSTANCE_APPLICATIONS.contains(name))
        });
        let shared_process_pids = shared_process_name
            .map(|name| {
                get_running_process_pids(name)
                    .into_iter()
                    .filter(|pid| {
                        // A matching process already inside this exact netns
                        // cannot cause the host-namespace escape described by
                        // this warning.  If inspection fails, keep the warning
                        // conservative and report the PID to the user.
                        !matches!(process_is_in_network_namespace(*pid, &netns.name), Ok(true))
                    })
                    .collect::<Vec<_>>()
            })
            .unwrap_or_default();

        if let Some(shared_process_name) = shared_process_name
            && !shared_process_pids.is_empty()
        {
            report_warning(
                format!(
                    "{shared_process_name} is already running outside network namespace '{}' (PID(s): {}). It may reuse that process instead of starting inside vopono; use a separate profile/data directory or stop the existing instance.",
                    netns.name,
                    shared_process_pids
                        .iter()
                        .map(u32::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
                silent,
                stdio_fds,
            );
        }

        let app_vec_ptrs: Vec<&str> = app_vec.iter().map(|s| s.as_str()).collect();

        let (mut handle, etc_overlay) = Self::run_with_env_in_netns(
            netns,
            app_vec_ptrs.as_slice(),
            user,
            group,
            silent,
            pipe_io,
            pipe_io,
            stdio_fds,
            take_controlling_tty,
            working_directory,
            port_forwarding.as_deref(),
            host_env_vars,
        )?;

        let pid = handle.id();
        if check_process_running(pid) {
            match process_is_in_network_namespace(pid, &netns.name) {
                Ok(true) => {
                    debug!(
                        "Verified application PID {pid} is in network namespace '{}'",
                        netns.name
                    );
                }
                Ok(false) => {
                    let _ = handle.kill();
                    let _ = handle.wait();
                    bail!(
                        "Refusing to launch application: PID {pid} is not in network namespace '{}'",
                        netns.name
                    );
                }
                Err(error) => {
                    log::warn!(
                        "Could not verify that application PID {pid} is in network namespace '{}': {error}",
                        netns.name
                    );
                }
            }
        } else if !shared_process_pids.is_empty() {
            report_warning(
                format!(
                    "Application launcher PID {pid} exited before its network namespace could be verified; the existing process may have handled the request instead."
                ),
                silent,
                stdio_fds,
            );
        }

        Ok(Self {
            handle,
            port_forwarding,
            _etc_overlay: etc_overlay,
        })
    }

    pub fn wait_with_output(self) -> anyhow::Result<std::process::Output> {
        let output = self.handle.wait_with_output()?;
        Ok(output)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn run_with_env_in_netns(
        netns: &NetworkNamespace,
        command: &[&str],
        user: Option<String>,
        group: Option<String>,
        silent: bool,
        capture_output: bool,
        capture_input: bool,
        stdio_fds: Option<(RawFd, RawFd, RawFd)>,
        take_controlling_tty: bool,
        set_dir: Option<PathBuf>,
        forwarder: Option<&dyn Forwarder>,
        host_env_vars: &std::collections::HashMap<String, String>,
    ) -> anyhow::Result<(Child, Option<tempfile::TempDir>)> {
        let (prog, args) = command.split_first().context("Command cannot be empty")?;
        let mut handle: Command;

        // The daemon needs direct setns so it can attach the client's stdio and PTY without
        // another process layer.
        let use_direct_setns = nix::unistd::getuid().is_root()
            && (stdio_fds.is_some() || (capture_output && capture_input));
        let mut etc_overlay = None;

        if use_direct_setns {
            handle = Command::new(prog);
            handle.args(args);
            // Prepare all data outside the closure
            let user_details = if let Some(user_name) = user {
                debug!(
                    "(daemon) Preparing to run '{}' in netns '{}' as user '{}'",
                    command.join(" "),
                    netns.name,
                    user_name
                );
                let target_user = nix::unistd::User::from_name(&user_name)?
                    .with_context(|| format!("User '{}' not found", user_name))?;

                let target_group = if let Some(group_name) = group {
                    nix::unistd::Group::from_name(&group_name)?
                        .with_context(|| format!("Group '{}' not found", group_name))?
                } else {
                    nix::unistd::Group::from_gid(target_user.gid)?
                        .with_context(|| "Primary group for user not found")?
                };

                //  Before forking, set the DBUS session address environment variable.
                let dbus_socket_path = format!("/run/user/{}/bus", target_user.uid.as_raw());
                if std::path::Path::new(&dbus_socket_path).exists() {
                    let dbus_address = format!("unix:path={}", dbus_socket_path);
                    debug!("Setting DBUS_SESSION_BUS_ADDRESS to {}", dbus_address);
                    handle.env("DBUS_SESSION_BUS_ADDRESS", dbus_address);
                } else {
                    log::warn!(
                        "Could not find user DBus socket at {}. Graphical applications may fail to integrate with the desktop.",
                        dbus_socket_path
                    );
                }

                //  Set environment and working directory on the Command builder itself.
                // This is the safe and correct way to prepare the child's environment.
                handle.env("HOME", &target_user.dir);
                handle.env("USER", &target_user.name);
                handle.env("LOGNAME", &target_user.name);

                if let Some(dir) = set_dir {
                    handle.current_dir(dir);
                } else {
                    handle.current_dir(&target_user.dir);
                }

                Some((
                    target_user.uid,
                    target_group.gid,
                    CString::new(target_user.name)?,
                ))
            } else {
                if let Some(dir) = set_dir {
                    handle.current_dir(dir);
                }
                None
            };

            let netns_path_cstr = CString::new(format!("/var/run/netns/{}", netns.name))?;
            let want_controlling_tty = take_controlling_tty;
            let root_c = CString::new("/").unwrap();
            let etc_ns_dir = format!("/etc/netns/{}", netns.name);
            let overlay = tempfile::Builder::new()
                .prefix("vopono-etc-")
                .tempdir()
                .context("Failed to create private /etc overlay directory")?;
            let upper_dir = overlay.path().join("upper");
            let work_dir = overlay.path().join("work");
            std::fs::create_dir(&upper_dir)?;
            std::fs::create_dir(&work_dir)?;
            for name in ["resolv.conf", "hosts", "nsswitch.conf"] {
                let source = PathBuf::from(&etc_ns_dir).join(name);
                if source.is_file() {
                    std::fs::copy(&source, upper_dir.join(name)).with_context(|| {
                        format!(
                            "Failed to stage {} for namespace {}",
                            source.display(),
                            netns.name
                        )
                    })?;
                }
            }
            let overlay_options = CString::new(format!(
                "lowerdir=/etc,upperdir={},workdir={}",
                upper_dir.display(),
                work_dir.display()
            ))?;
            let overlay_source = CString::new("vopono-etc").unwrap();
            let overlay_type = CString::new("overlay").unwrap();
            let etc_c = CString::new("/etc").unwrap();
            let ping_path = CString::new("/proc/sys/net/ipv4/ping_group_range").unwrap();
            etc_overlay = Some(overlay);

            unsafe {
                handle.pre_exec(move || {
                    // The closure now ONLY contains async-signal-safe syscall wrappers.
                    let ns_fd = open(netns_path_cstr.as_c_str(), OFlag::O_RDONLY, Mode::empty())?;
                    setns(
                        ns_fd.try_clone().expect("Clone failed"),
                        CloneFlags::CLONE_NEWNET,
                    )?;
                    close(ns_fd)?;

                    // Create a private mount namespace for the child to safely overlay /etc files
                    unshare(CloneFlags::CLONE_NEWNS)?;
                    // Make mounts private to avoid propagating to the host
                    mount::<std::ffi::CStr, std::ffi::CStr, std::ffi::CStr, std::ffi::CStr>(
                        None,
                        root_c.as_c_str(),
                        None,
                        MsFlags::MS_REC | MsFlags::MS_PRIVATE,
                        None,
                    )?;

                    // Give the child a stable private /etc view. Namespace-specific resolver
                    // files in the upper layer cannot be displaced when NetworkManager,
                    // Tailscale, or systemd-resolved atomically replaces the host resolv.conf.
                    //
                    // Tailscale MagicDNS and direct tailnet routes are intentionally unavailable
                    // inside the VPN namespace. Users can currently expose a host-side proxy with
                    // --allow-host-access and connect to it through vopono.host.
                    // Host-side service forwarding remains opt-in; exposing
                    // selected Tailscale services automatically would weaken
                    // the namespace boundary.
                    mount(
                        Some(overlay_source.as_c_str()),
                        etc_c.as_c_str(),
                        Some(overlay_type.as_c_str()),
                        MsFlags::empty(),
                        Some(overlay_options.as_c_str()),
                    )?;

                    // Enable unprivileged ping inside the netns by widening ping_group_range
                    // Write "0 2147483647" to /proc/sys/net/ipv4/ping_group_range via raw syscalls
                    let fd = libc::open(ping_path.as_ptr(), libc::O_WRONLY);
                    if fd >= 0 {
                        let data = b"0 2147483647\n";
                        let _ = libc::write(fd, data.as_ptr() as *const _, data.len());
                        libc::close(fd);
                    }

                    // If the child should be truly interactive, make it a session leader and
                    // set the controlling terminal to stdin (fd 0). This fixes bash job control
                    // and routes signals like Ctrl+C to the child instead of the client.
                    if want_controlling_tty {
                        // Create a new session
                        let _ = libc::setsid();
                        // If stdin is a TTY, take it as controlling terminal
                        // Use TIOCSCTTY with arg 1 to forcibly acquire if already in use
                        let fd0: i32 = 0;
                        if libc::isatty(fd0) == 1 {
                            // Attempt to acquire the TTY as controlling terminal. Only set
                            // the foreground process group if that succeeded.
                            let acquire_res = libc::ioctl(fd0, libc::TIOCSCTTY as _, 1);
                            if acquire_res == 0 {
                                let pgrp = libc::getpgrp();
                                let _ = libc::tcsetpgrp(fd0, pgrp);
                            }
                        }
                    }

                    if let Some((uid, gid, user_name_cstr)) = &user_details {
                        nix::unistd::initgroups(user_name_cstr, *gid)?;
                        nix::unistd::setgid(*gid)?;
                        nix::unistd::setuid(*uid)?;
                    }

                    Ok(())
                });
            }
        } else {
            // This non-daemon path remains unchanged
            handle = Command::new("ip");
            handle.args(["netns", "exec", netns.name.as_str()]);

            let mut sudo_args: Vec<String> = vec![
                "sudo".to_string(),
                "--preserve-env".to_string(),
                "--set-home".to_string(),
            ];
            if let Some(user_str) = &user {
                sudo_args.push("--user".to_string());
                sudo_args.push(user_str.clone());
            }
            if let Some(group_str) = &group {
                sudo_args.push("--group".to_string());
                sudo_args.push(group_str.clone());
            }

            debug!(
                "ip netns exec {} {} {}",
                netns.name,
                sudo_args.join(" "),
                command.join(" ")
            );
            handle.args(sudo_args);
            handle.args(command);
            if let Some(cdir) = set_dir {
                handle.current_dir(cdir);
            }
        }

        set_env_vars(netns, forwarder, &mut handle, host_env_vars);

        if silent {
            handle.stdout(Stdio::null());
            handle.stderr(Stdio::null());
        }
        match (stdio_fds, capture_input, capture_output) {
            (Some((fd_in, fd_out_orig, fd_err_orig)), _, _) => unsafe {
                // Ensure each Stdio gets a unique owned fd to avoid double-closing.
                let in_fd = fd_in;
                let mut out_fd = fd_out_orig;
                let mut err_fd = fd_err_orig;
                if out_fd == in_fd {
                    out_fd = nix::unistd::dup(BorrowedFd::borrow_raw(out_fd))
                        .map_err(|e| std::io::Error::other(format!("dup stdout failed: {e}")))?
                        .into_raw_fd();
                }
                if err_fd == in_fd || err_fd == out_fd {
                    err_fd = nix::unistd::dup(BorrowedFd::borrow_raw(err_fd))
                        .map_err(|e| std::io::Error::other(format!("dup stderr failed: {e}")))?
                        .into_raw_fd();
                }
                handle.stdin(Stdio::from_raw_fd(in_fd));
                handle.stdout(Stdio::from_raw_fd(out_fd));
                handle.stderr(Stdio::from_raw_fd(err_fd));
            },
            (None, true, true) => {
                handle.stdin(Stdio::piped());
                handle.stdout(Stdio::piped());
                handle.stderr(Stdio::piped());
            }
            (None, true, false) => {
                handle.stdin(Stdio::piped());
            }
            (None, false, true) => {
                handle.stdout(Stdio::piped());
                handle.stderr(Stdio::piped());
            }
            _ => {}
        }

        let child = handle.spawn()?;
        Ok((child, etc_overlay))
    }
}

fn report_warning(message: String, silent: bool, stdio_fds: Option<(RawFd, RawFd, RawFd)>) {
    if silent {
        if let Some((_, _, stderr_fd)) = stdio_fds
            && let Ok(dup_fd) = nix::unistd::dup(unsafe { BorrowedFd::borrow_raw(stderr_fd) })
        {
            let mut stderr = std::fs::File::from(dup_fd);
            let _ = writeln!(stderr, "warning: {message}");
            let _ = stderr.flush();
        }
    } else {
        log::warn!("{message}");
    }
}