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
use std::collections::HashMap;
use std::net;
use std::path;

use param;
use rctl;
use sys;
use JailError;
use RunningJail;

#[cfg(feature = "serialize")]
use serde::Serialize;

use std::convert::TryFrom;
use std::fmt;

/// Represent a stopped jail including all information required to start it
#[derive(Clone, PartialEq, Eq, Debug)]
#[cfg(target_os = "freebsd")]
#[cfg_attr(feature = "serialize", derive(Serialize))]
pub struct StoppedJail {
    /// The path of root file system of the jail
    pub path: Option<path::PathBuf>,

    /// The jail name
    pub name: Option<String>,

    /// The jail hostname
    pub hostname: Option<String>,

    /// A hashmap of jail parameters and their values
    pub params: HashMap<String, param::Value>,

    /// A list of IP (v4 and v6) addresses to be assigned to this jail
    pub ips: Vec<net::IpAddr>,

    /// A list of resource limits
    pub limits: Vec<(rctl::Resource, rctl::Limit, rctl::Action)>,
}

#[cfg(target_os = "freebsd")]
impl Default for StoppedJail {
    fn default() -> StoppedJail {
        trace!("StoppedJail::default()");
        StoppedJail {
            path: None,
            name: None,
            hostname: None,
            params: HashMap::new(),
            ips: vec![],
            limits: vec![],
        }
    }
}

impl TryFrom<RunningJail> for StoppedJail {
    type Error = JailError;

    fn try_from(running: RunningJail) -> Result<StoppedJail, Self::Error> {
        running.stop()
    }
}

#[cfg(target_os = "freebsd")]
impl StoppedJail {
    /// Create a new Jail instance given a path.
    ///
    /// # Examples
    ///
    /// ```
    /// use jail::StoppedJail;
    ///
    /// let j = StoppedJail::new("/rescue");
    /// ```
    pub fn new<P: Into<path::PathBuf> + fmt::Debug>(path: P) -> StoppedJail {
        trace!("StoppedJail::new(path={:?})", path);
        let mut ret: StoppedJail = Default::default();
        ret.path = Some(path.into());
        ret
    }

    /// Start the jail
    ///
    /// This will call [jail_create](fn.jail_create.html) internally.
    /// This will consume the [StoppedJail](struct.StoppedJail.html) and return
    /// a Result<[RunningJail](struct.RunningJail.html),Error>.
    ///
    /// Examples
    ///
    /// ```
    /// use jail::StoppedJail;
    ///
    /// let stopped = StoppedJail::new("/rescue");
    /// let running = stopped.start().unwrap();
    /// # running.kill();
    /// ```
    pub fn start(self: StoppedJail) -> Result<RunningJail, JailError> {
        trace!("StoppedJail::start({:?})", self);
        let path = match self.path {
            None => return Err(JailError::PathNotGiven),
            Some(ref p) => p.clone(),
        };

        // If we don't have a name, we can't have RCTL rules...
        if self.name.is_none() && !self.limits.is_empty() {
            return Err(JailError::UnnamedButLimited);
        }

        let mut params = self.params.clone();

        // Set the IP Addresses
        params.insert(
            "ip4.addr".into(),
            param::Value::Ipv4Addrs(
                self.ips
                    .iter()
                    .filter(|ip| ip.is_ipv4())
                    .map(|ip| match ip {
                        net::IpAddr::V4(ip4) => *ip4,
                        _ => panic!("unreachable"),
                    })
                    .collect(),
            ),
        );

        params.insert(
            "ip6.addr".into(),
            param::Value::Ipv6Addrs(
                self.ips
                    .iter()
                    .filter(|ip| ip.is_ipv6())
                    .map(|ip| match ip {
                        net::IpAddr::V6(ip6) => *ip6,
                        _ => panic!("unreachable"),
                    })
                    .collect(),
            ),
        );

        if let Some(ref name) = self.name {
            params.insert("name".into(), param::Value::String(name.clone()));
        }

        if let Some(ref hostname) = self.hostname {
            params.insert(
                "host.hostname".into(),
                param::Value::String(hostname.clone()),
            );
        }

        let ret = sys::jail_create(&path, params).map(RunningJail::from_jid_unchecked)?;

        // Set resource limits
        if !self.limits.is_empty() {
            let subject = rctl::Subject::jail_name(self.name.expect(
                "Unreachable: Should have thrown \
                 JailError::UnnamedButLimited",
            ));
            for (resource, limit, action) in self.limits {
                let rule = rctl::Rule {
                    subject: subject.clone(),
                    resource,
                    limit,
                    action,
                };

                rule.apply().map_err(JailError::RctlError)?;
            }
        }

        Ok(ret)
    }

    /// Set the jail name
    ///
    /// # Examples
    ///
    /// ```
    /// # use jail::StoppedJail;
    /// #
    /// let mut stopped = StoppedJail::new("/rescue")
    ///     .name("test_stopped_name");
    ///
    /// assert_eq!(stopped.name, Some("test_stopped_name".to_string()));
    /// ```
    pub fn name<S: Into<String> + fmt::Debug>(mut self: Self, name: S) -> Self {
        trace!("StoppedJail::start({:?}, name={:?})", self, name);
        self.name = Some(name.into());
        self
    }

    /// Set the jail name
    ///
    /// # Examples
    ///
    /// ```
    /// # use jail::StoppedJail;
    /// #
    /// let mut stopped = StoppedJail::new("/rescue")
    /// #   .name("test_stopped_hostname")
    ///     .hostname("example.com");
    ///
    /// assert_eq!(stopped.hostname, Some("example.com".to_string()));
    /// ```
    pub fn hostname<S: Into<String> + fmt::Debug>(mut self: Self, hostname: S) -> Self {
        trace!("StoppedJail::hostname({:?}, hostname={:?})", self, hostname);
        self.hostname = Some(hostname.into());
        self
    }

    /// Set a jail parameter
    ///
    /// # Examples
    ///
    /// ```
    /// # use jail::StoppedJail;
    /// #
    /// use jail::param;
    ///
    /// let mut stopped = StoppedJail::new("/rescue")
    ///     .param("allow.raw_sockets", param::Value::Int(1));
    /// ```
    pub fn param<S: Into<String> + fmt::Debug>(
        mut self: Self,
        param: S,
        value: param::Value,
    ) -> Self {
        trace!(
            "StoppedJail::param({:?}, param={:?}, value={:?})",
            self,
            param,
            value
        );
        self.params.insert(param.into(), value);
        self
    }

    /// Set a resource limit
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate rctl;
    /// # extern crate jail;
    /// # use jail::StoppedJail;
    /// use rctl;
    /// let mut stopped = StoppedJail::new("/rescue").limit(
    ///     rctl::Resource::MemoryUse,
    ///     rctl::Limit::amount_per(100 * 1024 * 1024, rctl::SubjectType::Process),
    ///     rctl::Action::Deny,
    /// );
    pub fn limit(
        mut self,
        resource: rctl::Resource,
        limit: rctl::Limit,
        action: rctl::Action,
    ) -> Self {
        trace!(
            "StoppedJail::limit({:?}, resource={:?}, limit={:?}, action={:?})",
            self,
            resource,
            limit,
            action
        );
        self.limits.push((resource, limit, action));
        self
    }

    /// Add an IP Address
    ///
    /// # Examples
    ///
    /// ```
    /// # use jail::StoppedJail;
    /// # use std::net::IpAddr;
    /// #
    /// let mut stopped = StoppedJail::new("rescue")
    ///     .ip("127.0.1.1".parse().expect("could not parse 127.0.1.1"))
    ///     .ip("fe80::2".parse().expect("could not parse ::1"));
    /// ```
    pub fn ip(mut self: Self, ip: net::IpAddr) -> Self {
        trace!("StoppedJail::ip({:?}, ip={:?})", self, ip);
        self.ips.push(ip);
        self
    }
}