blackship 0.6.1

A FreeBSD jail manager with state machine control
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
//! Firewall management for jail port forwarding.
//!
//! Uses PF anchors to manage RDR rules without modifying the host's `pf.conf`.
//! Forward definitions are persisted so separate CLI invocations can list,
//! update, and remove them consistently.

use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::fmt::Write as _;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::process::Command;

/// PF anchor name for blackship rules.
const PF_ANCHOR: &str = "blackship";

/// Filter rule inside the `blackship` anchor that evaluates every drain
/// sub-anchor (relative path: `blackship/drain/*`).
const DRAIN_ANCHOR_REFERENCE: &str = "anchor \"drain/*\"";

/// Enable PF on the host: write a minimal /etc/pf.conf carrying the
/// blackship anchors if none exists, persist `pf_enable=YES`, and start pf.
pub fn enable_pf() -> Result<()> {
    if pf_enabled() {
        return Ok(());
    }

    let pf_conf = Path::new("/etc/pf.conf");
    if !pf_conf.exists() {
        let conf = format!(
            "# Generated by blackship setup --enable-pf\n\
             set skip on lo0\n\
             nat-anchor \"{PF_ANCHOR}\"\n\
             rdr-anchor \"{PF_ANCHOR}\"\n\
             anchor \"{PF_ANCHOR}\"\n\
             anchor \"{PF_ANCHOR}/*\"\n\
             pass all\n"
        );
        std::fs::write(pf_conf, conf)
            .map_err(|e| Error::Network(format!("Failed to write /etc/pf.conf: {e}")))?;
        println!("Wrote minimal /etc/pf.conf with blackship anchors (default: pass all)");
    }

    let status = Command::new("/usr/sbin/sysrc")
        .arg("pf_enable=YES")
        .status()
        .map_err(|e| Error::Network(format!("Failed to run sysrc: {e}")))?;
    if !status.success() {
        return Err(Error::Network("sysrc pf_enable=YES failed".to_string()));
    }

    let status = Command::new("/usr/sbin/service")
        .args(["pf", "start"])
        .status()
        .map_err(|e| Error::Network(format!("Failed to start pf: {e}")))?;
    if !status.success() {
        return Err(Error::Network(
            "service pf start failed; check /etc/pf.conf".to_string(),
        ));
    }
    println!("PF enabled and started.");
    Ok(())
}

/// Port forwarding rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortForward {
    /// External port to listen on.
    pub external_port: u16,
    /// Internal (jail) port to forward to.
    pub internal_port: u16,
    /// Protocol (tcp, udp).
    pub protocol: String,
    /// Jail IP address.
    pub jail_ip: IpAddr,
    /// Bind to specific external IP (None = all interfaces).
    pub bind_ip: Option<IpAddr>,
    /// Jail name (for identification).
    pub jail_name: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct PortForwardFile {
    forwards: Vec<PortForward>,
}

impl PortForward {
    /// Create a new port forward rule.
    pub fn new(
        external_port: u16,
        internal_port: u16,
        protocol: &str,
        jail_ip: IpAddr,
        jail_name: &str,
    ) -> Self {
        Self {
            external_port,
            internal_port,
            protocol: protocol.to_string(),
            jail_ip,
            bind_ip: None,
            jail_name: jail_name.to_string(),
        }
    }

    /// Bind to a specific external IP.
    pub const fn with_bind_ip(mut self, ip: IpAddr) -> Self {
        self.bind_ip = Some(ip);
        self
    }

    /// Generate PF RDR rule; errors unless the protocol is `tcp` or `udp`.
    pub fn to_pf_rule(&self) -> Result<String> {
        match self.protocol.as_str() {
            "tcp" | "udp" => {}
            other => {
                return Err(Error::ConfigValidation(format!(
                    "invalid protocol {other:?}: must be \"tcp\" or \"udp\""
                )));
            }
        }

        // A bind address narrows the destination; `on` would take it for an
        // interface name and the rule would never match.
        let destination = self
            .bind_ip
            .map_or_else(|| "any".to_string(), |ip| ip.to_string());

        let safe_name = sanitize_jail_name(&self.jail_name);

        Ok(format!(
            "rdr proto {} from any to {} port {} -> {} port {} # jail:{}",
            self.protocol,
            destination,
            self.external_port,
            self.jail_ip,
            self.internal_port,
            safe_name
        ))
    }
}

/// Strip anything that could break out of a PF comment or anchor path.
pub fn sanitize_jail_name(name: &str) -> String {
    name.chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '_' || c == '.' {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// Sub-anchor holding a jail's drain rules.
pub fn drain_anchor_path(jail_name: &str) -> String {
    format!("{}/drain/{}", PF_ANCHOR, sanitize_jail_name(jail_name))
}

/// Refuse new TCP connections to `ips`, leaving established states alone.
///
/// PF only evaluates the sub-anchor through the `drain/*` reference in the
/// `blackship` anchor, so that ruleset is re-applied first: a host that never
/// ran `setup` or `expose` would otherwise load a fence nothing consults.
pub fn load_drain_anchor(data_dir: &Path, jail_name: &str, ips: &[IpAddr]) -> Result<String> {
    if ips.is_empty() {
        return Err(Error::InvalidArgument(format!(
            "jail '{jail_name}' has no recorded IP to drain"
        )));
    }

    BulkheadManager::from_data_dir(data_dir)?.apply_rules()?;

    let anchor = drain_anchor_path(jail_name);
    pfctl_stdin(&anchor, &drain_rules(ips))?;
    Ok(anchor)
}

fn drain_rules(ips: &[IpAddr]) -> String {
    let mut rules = String::new();
    for ip in ips {
        if !rules.is_empty() {
            rules.push('\n');
        }
        let _ = write!(rules, "block drop in quick proto tcp to {ip} flags S/SA"); // fmt::Write into a String is infallible
    }
    rules
}

/// Drop a drain anchor's rules. Best effort: a missing anchor is success.
pub fn flush_drain_anchor(anchor: &str) {
    // Anchor may not exist yet.
    let _ = Command::new("/sbin/pfctl")
        .args(["-a", anchor, "-F", "rules"])
        .output();
}

/// Every drain sub-anchor PF currently holds, for GC.
pub fn list_drain_anchors() -> Vec<String> {
    let prefix = format!("{PF_ANCHOR}/drain/");
    Command::new("/sbin/pfctl")
        .args(["-a", &format!("{PF_ANCHOR}/drain"), "-s", "Anchors"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .map(str::trim)
                .filter(|line| line.starts_with(&prefix))
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

/// Number of PF states currently tracked for `ip`.
pub fn tcp_state_count(ip: IpAddr) -> usize {
    let needle = ip.to_string();
    Command::new("/sbin/pfctl")
        .args(["-s", "state"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map_or(0, |o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .filter(|line| line.contains("tcp") && line.contains(&needle))
                .count()
        })
}

/// True when PF is loaded and enabled.
pub fn pf_enabled() -> bool {
    Command::new("/sbin/pfctl")
        .args(["-s", "info"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .is_some_and(|o| String::from_utf8_lossy(&o.stdout).contains("Status: Enabled"))
}

fn pfctl_stdin(anchor: &str, rules: &str) -> Result<()> {
    let mut child = Command::new("/sbin/pfctl")
        .args(["-a", anchor, "-f", "-"])
        .stdin(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| Error::Network(format!("Failed to run pfctl: {e}")))?;

    if let Some(stdin) = child.stdin.as_mut() {
        use std::io::Write;
        stdin
            .write_all(rules.as_bytes())
            .map_err(|e| Error::Network(format!("Failed to write rules: {e}")))?;
    }

    let output = child
        .wait_with_output()
        .map_err(|e| Error::Network(format!("Failed to wait for pfctl: {e}")))?;

    if !output.status.success() {
        return Err(Error::Network(format!(
            "pfctl failed for anchor '{}': {}",
            anchor,
            String::from_utf8_lossy(&output.stderr)
        )));
    }

    Ok(())
}

/// Bulkhead manager for PF.
#[derive(Debug, Default)]
pub struct BulkheadManager {
    /// Active port forwards.
    forwards: Vec<PortForward>,
    /// Optional persistence path for forward definitions.
    state_path: Option<PathBuf>,
}

impl BulkheadManager {
    /// Create a bulkhead manager backed by a state file under `data_dir`.
    pub fn from_data_dir(data_dir: &Path) -> Result<Self> {
        let state_path = data_dir.join("port-forwards.toml");
        let forwards = read_forwards(&state_path)?;
        Ok(Self {
            forwards,
            state_path: Some(state_path),
        })
    }

    /// Initialize the PF anchor.
    ///
    /// The host's `pf.conf` must include:
    /// ```text
    /// rdr-anchor "blackship"
    /// anchor "blackship"
    /// ```
    pub fn init() -> Result<()> {
        if !pf_enabled() {
            return Err(Error::Network(
                "PF is not running. Enable it with: service pf start".to_string(),
            ));
        }

        let output = Command::new("/sbin/pfctl")
            .args(["-a", PF_ANCHOR, "-s", "rules"])
            .output()
            .map_err(|e| Error::Network(format!("Failed to check anchor: {e}")))?;

        if !output.status.success() {
            eprintln!("Warning: PF anchor '{PF_ANCHOR}' may not be configured.");
            eprintln!("Add these lines to /etc/pf.conf:");
            eprintln!("  rdr-anchor \"{PF_ANCHOR}\"");
            eprintln!("  anchor \"{PF_ANCHOR}\"");
        }

        Ok(())
    }

    /// Re-apply the currently persisted rules to PF.
    pub fn sync_rules(&self) -> Result<()> {
        Self::init()?;
        self.apply_rules()
    }

    /// Add a port forward rule.
    pub fn add_forward(&mut self, forward: PortForward) -> Result<()> {
        Self::init()?;

        if self.forwards.iter().any(|existing| existing == &forward) {
            return Ok(());
        }

        if let Some(existing) = self.forwards.iter().find(|existing| {
            existing.bind_ip == forward.bind_ip
                && existing.protocol == forward.protocol
                && existing.external_port == forward.external_port
        }) {
            return Err(Error::Network(format!(
                "Port {} {}/{} is already exposed for jail '{}'",
                existing.external_port,
                existing
                    .bind_ip
                    .map_or_else(|| "*".into(), |ip| ip.to_string()),
                existing.protocol,
                existing.jail_name
            )));
        }

        self.forwards.push(forward);
        self.forwards.sort_by(|a, b| {
            a.jail_name
                .cmp(&b.jail_name)
                .then_with(|| a.protocol.cmp(&b.protocol))
                .then_with(|| a.external_port.cmp(&b.external_port))
        });
        self.persist()?;
        self.apply_rules()
    }

    /// Remove port forwards for a jail.
    pub fn remove_jail_forwards(&mut self, jail_name: &str) -> Result<()> {
        if !self.forwards.iter().any(|f| f.jail_name == jail_name) {
            return Ok(());
        }

        Self::init()?;
        self.forwards
            .retain(|forward| forward.jail_name != jail_name);
        self.persist()?;
        self.apply_rules()
    }

    /// List current port forwards.
    pub fn list_forwards(&self) -> &[PortForward] {
        &self.forwards
    }

    /// Get forwards for a specific jail.
    pub fn get_jail_forwards(&self, jail_name: &str) -> Vec<&PortForward> {
        self.forwards
            .iter()
            .filter(|forward| forward.jail_name == jail_name)
            .collect()
    }

    fn persist(&self) -> Result<()> {
        let Some(path) = self.state_path.as_ref() else {
            return Ok(());
        };

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                Error::Network(format!("Failed to create port-forward state dir: {e}"))
            })?;
        }

        write_forwards(path, &self.forwards)
    }

    /// Load the `blackship` anchor: port forwards, then the reference to the
    /// per-jail drain anchors. PF's `blackship/*` wildcard in `pf.conf` is
    /// one level deep and never reaches `blackship/drain/<jail>`.
    fn apply_rules(&self) -> Result<()> {
        pfctl_stdin(PF_ANCHOR, &self.anchor_ruleset()?)
    }

    fn anchor_ruleset(&self) -> Result<String> {
        let mut rules = String::new();
        for forward in &self.forwards {
            rules.push_str(&forward.to_pf_rule()?);
            rules.push('\n');
        }
        rules.push_str(DRAIN_ANCHOR_REFERENCE);
        rules.push('\n');
        Ok(rules)
    }
}

fn read_forwards(path: &Path) -> Result<Vec<PortForward>> {
    if !path.exists() {
        return Ok(Vec::new());
    }

    let state: PortForwardFile = crate::atomic::read_toml(path, "port-forward state")?;
    Ok(state.forwards)
}

fn write_forwards(path: &Path, forwards: &[PortForward]) -> Result<()> {
    crate::atomic::write_toml_atomic(
        path,
        &PortForwardFile {
            forwards: forwards.to_vec(),
        },
        "port-forward state",
    )
}

#[cfg(test)]
impl BulkheadManager {
    /// Create an in-memory bulkhead manager.
    pub fn new() -> Self {
        Self::default()
    }
}

#[cfg(test)]
mod tests;