blackship 0.4.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
//! FFI bindings for FreeBSD jail syscalls
//!
//! This code is adapted from libjail-rs (<https://github.com/fubarnetes/libjail-rs>)
//! Original authors: Fabian Freyer <fabian.freyer@physik.tu-berlin.de>
//! License: BSD-3-Clause
//!
//! Copyright (c) 2018, Fabian Freyer <fabian.freyer@physik.tu-berlin.de>
//! All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions are met:
//!
//! 1. Redistributions of source code must retain the above copyright notice, this
//!    list of conditions and the following disclaimer.
//!
//! 2. Redistributions in binary form must reproduce the above copyright notice,
//!    this list of conditions and the following disclaimer in the documentation
//!    and/or other materials provided with the distribution.
//!
//! 3. Neither the name of the copyright holder nor the names of its
//!    contributors may be used to endorse or promote products derived from
//!    this software without specific prior written permission.

// FFI module: jail_set(2)/jail_get(2)/jail_remove(2) over iovec arrays.
#![allow(unsafe_code)]

use crate::error::Error;
use bitflags::bitflags;

macro_rules! io_err {
    () => {
        Err(Error::Io(std::io::Error::last_os_error()))
    };
}
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::mem;
use std::os::unix::io::FromRawFd;
use std::path::Path;
use std::ptr;

use super::types::ParamValue;

/// Decode a jail errmsg buffer into a String
fn decode_errmsg(errmsg: &[u8; 256]) -> String {
    CStr::from_bytes_until_nul(errmsg)
        .map(|c| c.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// Map `jail_set` result code + errmsg to a Result
fn check_jail_set_result(jid: i32, errmsg: &[u8; 256]) -> Result<i32, Error> {
    match jid {
        e if e < 0 => match errmsg[0] {
            0 => io_err!(),
            _ => Err(Error::JailSet(decode_errmsg(errmsg))),
        },
        _ => Ok(jid),
    }
}

/// Map `jail_get` result code + errmsg to a Result
fn check_jail_get_result(jid: i32, errmsg: &[u8; 256]) -> Result<i32, Error> {
    match jid {
        e if e < 0 => match errmsg[0] {
            0 => io_err!(),
            _ => Err(Error::JailGet(decode_errmsg(errmsg))),
        },
        _ => Ok(jid),
    }
}

/// iovec count as the `u_int` `jail_set(2)`/`jail_get(2)` take.
fn iov_count(jiov: &[libc::iovec]) -> Result<u32, Error> {
    u32::try_from(jiov.len()).map_err(|_| {
        Error::Io(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "too many jail parameters",
        ))
    })
}

/// One iovec; `iov_base` is `void *` by ABI even for read-only buffers.
const fn iov<T>(base: *const T, len: usize) -> libc::iovec {
    libc::iovec {
        iov_base: base.cast_mut().cast(),
        iov_len: len,
    }
}

/// `jail_get` plus result check; `errmsg_ptr` aliases an iovec, so read it only after the call.
fn jail_get_call(jiov: &mut Vec<libc::iovec>, errmsg_ptr: *const [u8; 256]) -> Result<i32, Error> {
    let count = iov_count(jiov)?;
    // SAFETY: jiov buffers are live and writable where jail_get copies back.
    let jid = unsafe { libc::jail_get(jiov.as_mut_ptr(), count, JailFlags::empty().bits()) };
    // SAFETY: live buffer; the kernel's write finished when jail_get returned.
    let errmsg = unsafe { &*errmsg_ptr };
    check_jail_get_result(jid, errmsg)
}

/// NUL-terminated (name, value) byte pairs backing a `jail_set/jail_get` iovec array.
type RawParams = Vec<(Vec<u8>, Vec<u8>)>;

/// Convert a params map into raw bytes suitable for `jail_set/jail_get` iovecs
fn build_raw_params(params: &HashMap<String, ParamValue>) -> Result<RawParams, Error> {
    params
        .iter()
        .map(|(key, value)| {
            Ok((
                CString::new(key.clone())?.into_bytes_with_nul(),
                value.as_bytes()?,
            ))
        })
        .collect()
}

/// Macro to construct iovec structures for jail syscalls
macro_rules! iovec {
    ($key:expr => ($value:expr, $size:expr)) => {
        vec![iovec!($key), iovec!($value, $size)]
    };
    ($key:expr => ()) => {
        vec![iovec!($key), iovec!()]
    };
    ($key:expr => $value:expr) => {
        vec![iovec!($key), iovec!($value)]
    };
    ($key:expr => mut $value:expr) => {
        vec![iovec!($key), iovec!(mut $value)]
    };
    ($value:expr, $size:expr) => {
        iov($value, $size)
    };
    ($name:expr) => {
        iovec!($name.as_ptr(), $name.len())
    };
    (mut $name:expr) => {
        iovec!($name.as_mut_ptr(), $name.len())
    };
    () => {
        iovec!(ptr::null::<libc::c_void>(), 0)
    };
}

bitflags! {
    /// Flags for jail_set syscall
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct JailFlags: i32 {
        /// Create the jail if it doesn't exist
        const CREATE = 0x01;
        /// Update parameters of existing jail
        const UPDATE = 0x02;
        /// Attach to jail upon creation
        const ATTACH = 0x04;
        /// Allow getting a dying jail
        const DYING = 0x08;
        /// Get/set jail in descriptor (FreeBSD 16+)
        const USE_DESC = 0x10;
        /// Find/add jail under descriptor (FreeBSD 16+)
        const AT_DESC = 0x20;
        /// Return a new jail descriptor (FreeBSD 16+)
        const GET_DESC = 0x40;
        /// Return a new owning jail descriptor (FreeBSD 16+)
        const OWN_DESC = 0x80;
    }
}

// Syscall number for FreeBSD 16 jail descriptor removal
const SYS_JAIL_REMOVE_JD: libc::c_int = 598;

/// Create a jail with the given path and parameters
///
/// Returns the jail ID (jid) on success
pub fn jail_create(path: &Path, params: &HashMap<String, ParamValue>) -> Result<i32, Error> {
    let raw_params = build_raw_params(params)?;

    let mut jiov: Vec<libc::iovec> = raw_params
        .iter()
        .flat_map(|(key, value)| iovec!(key => value))
        .collect();

    let pathstr = path
        .to_str()
        .ok_or_else(|| Error::JailSet("Invalid path encoding".into()))?;
    let pathstr = CString::new(pathstr)?.into_bytes_with_nul();

    // Set persist and errmsg
    let mut errmsg = [0u8; 256];
    jiov.append(
        &mut vec![
            iovec!(b"path\0" => pathstr),
            iovec!(b"errmsg\0" => mut errmsg),
            iovec!(b"persist\0" => ()),
        ]
        .into_iter()
        .flatten()
        .collect(),
    );

    let count = iov_count(&jiov)?;
    // SAFETY: every iovec buffer is live; jail_set writes only the mutable errmsg.
    let jid = unsafe { libc::jail_set(jiov[..].as_mut_ptr(), count, JailFlags::CREATE.bits()) };

    check_jail_set_result(jid, &errmsg)
}

/// Update parameters of a running jail (`jail_set` with `JAIL_UPDATE`).
///
/// All-or-nothing: a non-updatable key fails the whole call and the kernel
/// applies none of it.
pub fn jail_update(jid: i32, params: &HashMap<String, ParamValue>) -> Result<(), Error> {
    let raw_params = build_raw_params(params)?;

    let mut jiov: Vec<libc::iovec> = raw_params
        .iter()
        .flat_map(|(key, value)| iovec!(key => value))
        .collect();

    let mut errmsg = [0u8; 256];
    jiov.append(
        &mut vec![
            iovec!(b"jid\0" => (&raw const jid, mem::size_of::<i32>())),
            iovec!(b"errmsg\0" => mut errmsg),
        ]
        .into_iter()
        .flatten()
        .collect(),
    );

    let count = iov_count(&jiov)?;
    // SAFETY: every iovec buffer is live; jail_set writes only the mutable errmsg.
    let ret = unsafe { libc::jail_set(jiov[..].as_mut_ptr(), count, JailFlags::UPDATE.bits()) };

    check_jail_set_result(ret, &errmsg).map(|_| ())
}

/// Get the jail ID from a jail name
///
/// If the name can be parsed as an i32, it's returned directly
pub fn jail_getid(name: &str) -> Result<i32, Error> {
    let mut errmsg = [0u8; 256];

    // Try parsing as number first
    if let Ok(jid) = name.parse::<i32>() {
        return Ok(jid);
    }

    // jail_get copies every parameter back out, the key included.
    let mut name = CString::new(name)?.into_bytes_with_nul();

    let mut jiov: Vec<libc::iovec> = vec![
        iovec!(b"name\0" => mut name),
        iovec!(b"errmsg\0" => mut errmsg),
    ]
    .into_iter()
    .flatten()
    .collect();

    jail_get_call(&mut jiov, &raw const errmsg)
}

pub fn jail_getname(mut jid: i32) -> Result<String, Error> {
    let mut errmsg = [0u8; 256];
    let mut name = [0u8; 256];

    let mut jiov: Vec<libc::iovec> = vec![
        // jail_get writes the key back too.
        iovec!(b"jid\0" => (&raw mut jid, mem::size_of::<i32>())),
        iovec!(b"name\0" => mut name),
        iovec!(b"errmsg\0" => mut errmsg),
    ]
    .into_iter()
    .flatten()
    .collect();

    jail_get_call(&mut jiov, &raw const errmsg)?;

    let len = name.iter().position(|&b| b == 0).unwrap_or(name.len());
    Ok(String::from_utf8_lossy(&name[..len]).into_owned())
}

/// Get the next jail ID after the given one
///
/// Used to iterate through all jails
pub fn jail_nextjid(mut lastjid: i32) -> Result<i32, Error> {
    let mut errmsg = [0u8; 256];

    let mut jiov: Vec<libc::iovec> = vec![
        // jail_get writes the key back too.
        iovec!(b"lastjid\0" => (&raw mut lastjid, mem::size_of::<i32>())),
        iovec!(b"errmsg\0" => mut errmsg),
    ]
    .into_iter()
    .flatten()
    .collect();

    jail_get_call(&mut jiov, &raw const errmsg)
}

/// Remove a jail by its ID
///
/// This will kill all processes in the jail and remove it
pub fn jail_remove(jid: i32) -> Result<(), Error> {
    // SAFETY: integer arg.
    let ret = unsafe { libc::jail_remove(jid) };
    match ret {
        0 => Ok(()),
        -1 => io_err!(),
        _ => Err(Error::JailRemoveFailed),
    }
}

/// Create a jail and return an owning descriptor (FreeBSD 16+)
///
/// Returns (jid, descriptor); dropping the descriptor makes the kernel remove
/// the jail.
pub fn jail_create_with_descriptor(
    path: &Path,
    params: &HashMap<String, ParamValue>,
) -> Result<(i32, JailDescriptor), Error> {
    let raw_params = build_raw_params(params)?;

    let mut jiov: Vec<libc::iovec> = raw_params
        .iter()
        .flat_map(|(key, value)| iovec!(key => value))
        .collect();

    let pathstr = path
        .to_str()
        .ok_or_else(|| Error::JailSet("Invalid path encoding".into()))?;
    let pathstr = CString::new(pathstr)?.into_bytes_with_nul();

    // desc parameter receives the file descriptor
    let mut desc_fd: i32 = -1;
    let mut errmsg = [0u8; 256];

    jiov.append(
        &mut vec![
            iovec!(b"path\0" => pathstr),
            iovec!(b"errmsg\0" => mut errmsg),
            iovec!(b"persist\0" => ()),
            iovec!(b"desc\0" => ((&raw mut desc_fd).cast::<u8>(), mem::size_of::<i32>())),
        ]
        .into_iter()
        .flatten()
        .collect(),
    );

    let flags = JailFlags::CREATE | JailFlags::GET_DESC | JailFlags::OWN_DESC;
    let count = iov_count(&jiov)?;
    // SAFETY: every iovec buffer is live; jail_set writes only errmsg and desc_fd.
    let jid = unsafe { libc::jail_set(jiov[..].as_mut_ptr(), count, flags.bits()) };

    check_jail_set_result(jid, &errmsg)?;
    if desc_fd < 0 {
        return Err(Error::JailSet(
            "jail_set returned success but descriptor fd is negative".into(),
        ));
    }
    // SAFETY: OWN_DESC yields a fresh, non-negative fd nothing else owns.
    let owned_fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(desc_fd) };
    Ok((jid, JailDescriptor { fd: owned_fd }))
}

/// Remove a jail via its owning descriptor (FreeBSD 16+)
pub fn jail_remove_jd(fd: std::os::fd::BorrowedFd<'_>) -> Result<(), Error> {
    use std::os::unix::io::AsRawFd;
    // SAFETY: integer fd, kept open by the borrow.
    let ret = unsafe { libc::syscall(SYS_JAIL_REMOVE_JD, fd.as_raw_fd()) };
    if ret != 0 {
        return io_err!();
    }
    Ok(())
}

/// Owning jail descriptor (FreeBSD 16+)
///
/// Wraps an owning file descriptor. When dropped, the kernel
/// automatically removes the associated jail.
pub struct JailDescriptor {
    fd: std::os::fd::OwnedFd,
}

impl JailDescriptor {
    /// Get the raw fd for use with kqueue or other operations
    pub fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
        use std::os::unix::io::AsFd;
        self.fd.as_fd()
    }

    /// Get the raw fd number
    pub fn as_raw_fd(&self) -> i32 {
        use std::os::unix::io::AsRawFd;
        self.fd.as_raw_fd()
    }

    /// Explicitly remove the jail via descriptor syscall
    pub fn remove(self) -> Result<(), Error> {
        jail_remove_jd(self.as_fd())?;
        // fd is dropped after this, but jail is already removed
        Ok(())
    }
}

impl std::fmt::Debug for JailDescriptor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use std::os::unix::io::AsRawFd;
        f.debug_struct("JailDescriptor")
            .field("fd", &self.fd.as_raw_fd())
            .finish()
    }
}

/// Iterator over all running jails
pub struct RunningJails {
    lastjid: i32,
}

impl RunningJails {
    pub const fn new() -> Self {
        Self { lastjid: 0 }
    }
}

impl Default for RunningJails {
    fn default() -> Self {
        Self::new()
    }
}

impl Iterator for RunningJails {
    type Item = i32;

    fn next(&mut self) -> Option<Self::Item> {
        match jail_nextjid(self.lastjid) {
            Ok(jid) => {
                self.lastjid = jid;
                Some(jid)
            }
            Err(_) => None,
        }
    }
}