forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

net.rs264 lines, 9.1 KiBHistoryRawDownload
1//! The network of a builtin job that asked for one.
2//!
3//! The job gets its own network namespace, and `pasta` (from the passt package) connects it to
4//! the internet through the runner's own sockets. Inside, the job sees `192.0.2.2/24` with the
5//! gateway at `192.0.2.1` and DNS at `192.0.2.3`. The host's loopback is not mapped, and
6//! blackhole routes send private, link-local (cloud metadata) and multicast ranges nowhere, so
7//! a job cannot reach the runner's own services or its LAN. There is no IPv6.
8//!
9//! pasta has to start in the host's namespaces and attach to the helper's new ones, so it can't
10//! be a child of the helper after the unshare. A `__sandbox-net` helper of this same binary is
11//! started before it, and blocks on stdin until the helper has unshared. It then runs pasta,
12//! which forks into the background once the namespace is set up and exits 0. pasta writes its
13//! pid to a file, and [`stop_pasta`] ends it after the job.
14
15use std::ffi::OsString;
16use std::fs;
17use std::io::{self, Read, Write};
18use std::path::{Path, PathBuf};
19use std::process::{Child, Command, Stdio};
20
21use nix::sched::{CloneFlags, unshare};
22use nix::sys::signal::{Signal, kill};
23use nix::unistd::Pid;
24
25use super::SandboxError;
26
27/// The hidden subcommand that waits for the go byte and starts pasta.
28pub const NET_HELPER_CMD: &str = "__sandbox-net";
29/// The job's resolver, which pasta forwards to the host's.
30pub const DNS_ADDR: &str = "192.0.2.3";
31/// Where pasta is looked for, in order.
32const PASTA_PATHS: [&str; 3] = ["/usr/bin/pasta", "/usr/local/bin/pasta", "/bin/pasta"];
33const IP_DIRS: [&str; 4] = ["/usr/sbin", "/usr/bin", "/sbin", "/bin"];
34/// Ranges the job must not reach: "this network", private, carrier-grade NAT, link-local (cloud
35/// metadata), benchmarking, multicast and reserved.
36const BLOCKED: [&str; 9] = [
37 "0.0.0.0/8",
38 "10.0.0.0/8",
39 "100.64.0.0/10",
40 "169.254.0.0/16",
41 "172.16.0.0/12",
42 "192.168.0.0/16",
43 "198.18.0.0/15",
44 "224.0.0.0/4",
45 "240.0.0.0/4",
46];
47
48/// Where pasta writes its pid: in the job dir itself, since libcontainer removes `state` with the
49/// container.
50pub fn pid_file(job_dir: &Path) -> PathBuf {
51 job_dir.join("pasta.pid")
52}
53
54/// The installed pasta binary, if any.
55pub fn find_pasta() -> Option<PathBuf> {
56 PASTA_PATHS.iter().map(PathBuf::from).find(|p| p.is_file())
57}
58
59/// A started `__sandbox-net` helper that is waiting for its go byte.
60pub struct PendingNet {
61 child: Child,
62}
63
64/// Starts the `__sandbox-net` helper. Call it before entering the user namespace, then call
65/// [`PendingNet::attach`] right after.
66pub fn prepare(pasta: &Path, pid_file: &Path) -> Result<PendingNet, SandboxError> {
67 let exe = std::env::current_exe().map_err(SandboxError::io("cannot find the runner binary"))?;
68 let child = Command::new(exe)
69 .arg(NET_HELPER_CMD)
70 .arg(pasta)
71 .arg(std::process::id().to_string())
72 .arg(pid_file)
73 .stdin(Stdio::piped())
74 .stdout(Stdio::null())
75 .stderr(Stdio::piped())
76 .spawn()
77 .map_err(SandboxError::io("cannot start the network helper"))?;
78 Ok(PendingNet { child })
79}
80
81impl PendingNet {
82 /// Moves this process into a new network namespace, has pasta connect it, and sets up the
83 /// routes. Must run inside the job's user namespace, which owns the new network namespace.
84 pub fn attach(mut self) -> Result<(), SandboxError> {
85 let Some(mut go) = self.child.stdin.take() else {
86 self.stop();
87 return Err(SandboxError::Setup(
88 "no stdin for the network helper".into(),
89 ));
90 };
91 let signalled = unshare(CloneFlags::CLONE_NEWNET)
92 .map_err(|e| SandboxError::Setup(format!("cannot create a network namespace: {e}")))
93 .and_then(|()| {
94 go.write_all(b"1")
95 .map_err(SandboxError::io("cannot signal the network helper"))
96 });
97 // Closing stdin ends the helper's wait if the byte never landed.
98 drop(go);
99 if let Err(e) = signalled {
100 self.stop();
101 return Err(e);
102 }
103 let output = self
104 .child
105 .wait_with_output()
106 .map_err(SandboxError::io("waiting for the network helper"))?;
107 if !output.status.success() {
108 let stderr = String::from_utf8_lossy(&output.stderr);
109 let detail = match stderr.trim() {
110 "" => output.status.to_string(),
111 text => text.to_owned(),
112 };
113 return Err(SandboxError::Setup(format!("cannot start pasta: {detail}")));
114 }
115 configure_routes()
116 }
117
118 fn stop(&mut self) {
119 let _ = self.child.kill();
120 let _ = self.child.wait();
121 }
122}
123
124/// Brings loopback up and blackholes [`BLOCKED`]. pasta has already added the address and the
125/// default route.
126fn configure_routes() -> Result<(), SandboxError> {
127 let ip = IP_DIRS
128 .iter()
129 .map(|dir| Path::new(dir).join("ip"))
130 .find(|p| p.is_file())
131 .ok_or_else(|| SandboxError::Setup("`ip` (iproute2) is not installed".into()))?;
132 let mut script = String::from("link set lo up\n");
133 for range in BLOCKED {
134 script.push_str(&format!("route add blackhole {range}\n"));
135 }
136 let mut child = Command::new(ip)
137 .args(["-batch", "-"])
138 .stdin(Stdio::piped())
139 .stdout(Stdio::null())
140 .stderr(Stdio::piped())
141 .spawn()
142 .map_err(SandboxError::io("cannot run ip"))?;
143 if let Some(mut stdin) = child.stdin.take() {
144 stdin
145 .write_all(script.as_bytes())
146 .map_err(SandboxError::io("cannot write to ip"))?;
147 }
148 let output = child
149 .wait_with_output()
150 .map_err(SandboxError::io("waiting for ip"))?;
151 if output.status.success() {
152 Ok(())
153 } else {
154 Err(SandboxError::Setup(format!(
155 "cannot set up the job's routes: {}",
156 String::from_utf8_lossy(&output.stderr).trim()
157 )))
158 }
159}
160
161/// Ends the pasta whose pid is in `pid_file`, if it is still running. The pid is only signalled
162/// when it still names a pasta process, so a reused pid is left alone.
163pub fn stop_pasta(pid_file: &Path) {
164 let Ok(text) = fs::read_to_string(pid_file) else {
165 return;
166 };
167 let Ok(pid) = text.trim().parse::<i32>() else {
168 return;
169 };
170 if pid <= 1 {
171 return;
172 }
173 let comm = fs::read_to_string(format!("/proc/{pid}/comm")).unwrap_or_default();
174 if matches!(comm.trim(), "pasta" | "passt" | "pasta.avx2" | "passt.avx2") {
175 let _ = kill(Pid::from_raw(pid), Signal::SIGTERM);
176 }
177}
178
179/// `<exe> __sandbox-net <pasta> <parent> <pid_file>`, with the go byte on stdin. Exit 0 once
180/// pasta has connected the parent's network namespace, or 125 with a `forge-sandbox:` line.
181pub fn net_helper_main(args: &[OsString]) -> i32 {
182 match net_helper(args) {
183 Ok(()) => 0,
184 Err(message) => {
185 eprintln!("forge-sandbox: {message}");
186 125
187 }
188 }
189}
190
191fn net_helper(args: &[OsString]) -> Result<(), String> {
192 let [pasta, parent, pid_file] = args else {
193 return Err("usage: __sandbox-net <pasta> <parent> <pid_file>".into());
194 };
195 let parent: u32 = parent
196 .to_str()
197 .and_then(|s| s.parse().ok())
198 .filter(|&p| p > 1)
199 .ok_or("parent must be a pid")?;
200 let mut byte = [0u8; 1];
201 loop {
202 match io::stdin().lock().read(&mut byte) {
203 Ok(1) => break,
204 Ok(_) => return Err("network setup was cancelled".into()),
205 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
206 Err(e) => return Err(format!("cannot read from the parent: {e}")),
207 }
208 }
209 let output = Command::new(pasta)
210 .args(pasta_args(parent, Path::new(pid_file)))
211 .stdin(Stdio::null())
212 .stdout(Stdio::null())
213 .stderr(Stdio::piped())
214 .output()
215 .map_err(|e| format!("cannot run pasta: {e}"))?;
216 if output.status.success() {
217 Ok(())
218 } else {
219 Err(format!(
220 "pasta failed ({}): {}",
221 output.status,
222 String::from_utf8_lossy(&output.stderr).trim()
223 ))
224 }
225}
226
227/// No ports are forwarded in either direction, the gateway does not map to the host's loopback,
228/// and pasta does not watch the namespace (that needs a netns dir SELinux may deny), so it is
229/// stopped through its pid file.
230fn pasta_args(parent: u32, pid_file: &Path) -> Vec<OsString> {
231 let mut args: Vec<OsString> = [
232 "-q",
233 "--config-net",
234 "-4",
235 "-a",
236 "192.0.2.2",
237 "-n",
238 "24",
239 "-g",
240 "192.0.2.1",
241 "--no-map-gw",
242 "--dns-forward",
243 DNS_ADDR,
244 "-t",
245 "none",
246 "-u",
247 "none",
248 "-T",
249 "none",
250 "-U",
251 "none",
252 "--no-netns-quit",
253 "--pid",
254 ]
255 .into_iter()
256 .map(OsString::from)
257 .collect();
258 args.push(pid_file.into());
259 args.push("--userns".into());
260 args.push(format!("/proc/{parent}/ns/user").into());
261 args.push("--netns".into());
262 args.push(format!("/proc/{parent}/ns/net").into());
263 args
264}