gaol/platform/linux/
misc.rs

1// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! Sandboxing on Linux via miscellaneous kernel features.
12
13use libc;
14use std::io;
15
16pub fn activate() -> Result<(), libc::c_int> {
17    // Disable writing by setting the write limit to zero.
18    let rlimit = libc::rlimit {
19        rlim_cur: 0,
20        rlim_max: 0,
21    };
22    let result = unsafe {
23         libc::setrlimit(libc::RLIMIT_FSIZE, &rlimit)
24    };
25    if result != 0 {
26        return Err(result)
27    }
28
29    // Set a restrictive `umask` so that even if files happened to get written it'd be hard to do
30    // anything with them.
31    unsafe {
32        libc::umask(0);
33    }
34
35    // Disable core dumps and debugging via `PTRACE_ATTACH`.
36    let result = unsafe {
37        libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0)
38    };
39    if result != 0 {
40        return Err(result)
41    }
42
43    // Enter a new session group. (This can fail with -EPERM if we're already the session leader,
44    // which is OK.)
45    unsafe {
46        if libc::setsid() < 0 {
47            let result = io::Error::last_os_error().raw_os_error().unwrap() as i32;
48            if result != libc::EPERM {
49                return Err(result)
50            }
51        }
52    }
53
54    // Clear out the process environment.
55    let result = unsafe {
56        libc::clearenv()
57    };
58    if result == 0 {
59        Ok(())
60    } else {
61        Err(result)
62    }
63}