pftables_rs/
lib.rs

1//! A small library for managing pf (packet filter) tables on OpenBSD 
2//! via `/dev/pf`
3pub mod bridge;
4pub use bridge::*;
5use std::{fmt, fs, io};
6use std::error::Error;
7
8type Result<T> = std::result::Result<T, PfError>;
9
10#[derive(Debug)]
11pub enum PfError {
12    TranslationError,
13    UnknownAddressFamily,
14    IoctlError(io::Error),
15    Other(String),
16    Unimplemented,
17}
18
19impl fmt::Display for PfError {
20    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
21        use PfError::*;
22        match self {
23            Other(message) => {
24                write!(f, "{}", message)
25            },
26            _ => {
27                write!(f, "{:?}", self)
28            }
29        }
30    }
31}
32
33impl Error for PfError {}
34
35/// A high-level struct representing a pf table containing addresses
36#[derive(Debug, Clone)]
37pub struct PfTable {
38    pub name: String,
39}
40
41impl PfTable {
42    /// Prepares a new `PfTable` with a provided `name`
43    pub fn new(name: &str) -> PfTable {
44        PfTable {
45            name: String::from(name),
46        }
47    }
48
49    /// Asks the kernel for a list of addresses in the table
50    pub fn get_addrs(&self, fd: &fs::File) -> Result<Vec<PfrAddr>> {
51        // Prepare an Ioctl call
52        let mut io = PfIocTable::new(&self.name);
53
54        // Ask the kernel how many entries there are
55        io.fire(&fd, PfIocCommand::GetAddrs)?;
56
57        // Allocate room for number of entries based on returned size
58        io.buffer = vec![PfrAddr::default(); io.size()];
59        io.fire(&fd, PfIocCommand::GetAddrs)?;
60
61        Ok(io.buffer)
62    }
63
64    /// Asks the kernel to add a list of addresses to the table
65    pub fn add_addrs(&self, fd: &fs::File, addrs: Vec<PfrAddr>) 
66        -> Result<()> 
67    {
68        let mut io = PfIocTable::new(&self.name);
69        io.buffer = addrs;
70        io.fire(&fd, PfIocCommand::AddAddrs)
71    }
72
73    /// Asks the kernel to delete a list of addresses from the table
74    pub fn del_addrs(&self, fd: &fs::File, addrs: Vec<PfrAddr>) 
75        -> Result<()> 
76    {
77        let mut io = PfIocTable::new(&self.name);
78        io.buffer = addrs;
79        io.fire(&fd, PfIocCommand::DelAddrs)
80    }
81
82    /// Asks the kernel to remove every address from the table
83    pub fn clr_addrs(&self, fd: &fs::File) -> Result<()> {
84        let mut io = PfIocTable::new(&self.name);
85        io.fire(&fd, PfIocCommand::ClrAddrs)
86    }
87}