summaryrefslogtreecommitdiff
path: root/sandboxlib/__init__.py
blob: 8179d7299e636c7971f9f143dc88cb24f50e2503 (plain)
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
# Copyright (C) 2015  Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.


'''sandboxlib module.

This module contains multiple 'executor' backends, which must all provide
the same API. A stub version of the API is defined in this file, with
docstrings that describe the different parameters.

'''


import logging
import os
import platform
import pipes
import subprocess


class ProgramNotFound(Exception):
    pass


def degrade_config_for_capabilities(in_config, warn=True):
    '''Alter settings in 'in_config' that a given backend doesn't support.

    This function is provided for users who want to be flexible about which
    sandbox implementation they use, and who don't mind if not all of the
    isolation that they requested is actually possible.

    This is not a general purpose 'check your config' function. Any unexpected
    keys or values in ``in_config`` will just be ignored.

    If 'warn' is True, each change the function makes is logged using
    warnings.warn().

    '''
    raise NotImplementedError()



# Special value for 'stderr' and 'stdout' parameters to indicate 'capture
# and return the data'.
CAPTURE = subprocess.PIPE

# Special value for 'stderr' parameter to indicate 'forward to stdout'.
STDOUT = subprocess.STDOUT


def run_sandbox(command, cwd=None, env=None,
                filesystem_root='/', filesystem_writable_paths='all',
                mounts='undefined', extra_mounts=None,
                network='undefined',
                stderr=CAPTURE, stdout=CAPTURE):
    '''Run 'command' in a sandboxed environment.

    Parameters:
      - command: the command to run. Pass a list of parameters rather than
            using spaces to separate them, e.g. ['echo', '"Hello world"'].
      - cwd: the working directory of 'command', relative to 'rootfs_path'.
            Defaults to '/' if "rootfs_path" is specified, and the current
            directory of the calling process otherwise.
      - env: environment variables to set
      - filesystem_root: the path to the root of the sandbox. Defaults to '/',
            which doesn't isolate the command from the host filesystem at all.
      - filesystem_writable_paths: defaults to 'all', which allows the command
            to write to anywhere under 'filesystem_root' that the user of the
            calling process could write to. Backends may accept a list of paths
            instead of 'all', and will prevent writes to any files not under a
            path in that whitelist. If 'none' or an empty list is passed, the
            whole file-system will be read-only. The paths should be relative
            to filesystem_root. This will processed /after/ extra_mounts are
            mounted.
      - mounts: configures mount sharing. Defaults to 'undefined', where no
            no attempt is made to isolate mounts. Backends may support
            'isolated' as well.
      - extra_mounts: a list of locations to mount inside 'rootfs_path',
            specified as a list of tuples of (source_path, target_path, type,
            options). The 'type' and 'options' should match what would be
            specified in /etc/fstab, but a backends may support only a limited
            subset of values. The 'target_path' is relative to filesystem_root
            and will be created before mounting if it doesn't exist.
      - network: configures network sharing. Defaults to 'undefined', where
            no attempt is made to either prevent or provide networking
            inside the sandbox. Backends may support 'isolated' and/or other
            values as well.
      - stdout: whether to capture stdout, or redirect stdout to a file handle.
            If set to sandboxlib.CAPTURE, the function will return the stdout
            data, if not, it will return None for that. If stdout=None, the
            data will be discarded -- it will NOT inherit the parent process's
            stdout, unlike with subprocess.Popen(). Set 'stdout=sys.stdout' if
            you want that.
      - stderr: same as stdout

    Returns:
      a tuple of (exit code, stdout output, stderr output).

    '''
    raise NotImplementedError()


def run_sandbox_with_redirection(command, **sandbox_config):
    '''Start a subprocess in a sandbox, redirecting stderr and/or stdout.

    The sandbox_config arguments are the same as the run_command() function.

    This returns just the exit code, because if stdout or stderr are redirected
    those values will be None in any case.

    '''
    raise NotImplementedError()


def executor_for_platform():
    '''Returns an execution module that will work on the current platform.'''

    log = logging.getLogger("sandboxlib")

    backend = None

    if platform.uname()[0] == 'Linux':
        log.info("Linux detected, looking for 'linux-user-chroot'.")
        try:
            program = sandboxlib.linux_user_chroot.linux_user_chroot_program()
            log.info("Found %s, choosing 'linux_user_chroot' module.", program)
            backend = sandboxlib.linux_user_chroot
        except sandboxlib.ProgramNotFound as e:
            log.debug("Did not find 'linux-user-chroot': %s", e)

    if backend is None:
        log.info("Choosing 'chroot' sandbox module.")
        backend = sandboxlib.chroot

    return backend


def validate_extra_mounts(extra_mounts):
    '''Validate and fill in default values for 'extra_mounts' setting.'''
    if extra_mounts == None:
        return []

    new_extra_mounts = []

    for mount_entry in extra_mounts:
        if len(mount_entry) == 3:
            new_mount_entry = list(mount_entry) + ['']
        elif len(mount_entry) == 4:
            new_mount_entry = list(mount_entry)
        else:
            raise AssertionError(
                "Invalid mount entry in 'extra_mounts': %s" % mount_entry)

        if new_mount_entry[0] is None:
            new_mount_entry[0] = ''
            #new_mount_entry[0] = 'none'
        if new_mount_entry[2] is None:
            new_mount_entry[2] = ''
        if new_mount_entry[3] is None:
            new_mount_entry[3] = ''
        new_extra_mounts.append(new_mount_entry)

    return new_extra_mounts



def argv_to_string(argv):
    return ' '.join(map(pipes.quote, argv))


def _run_command(argv, stdout, stderr, cwd=None, env=None):
    '''Wrapper around subprocess.Popen() with common settings.

    This function blocks until the subprocess has terminated.

    Unlike the subprocess.Popen() function, if stdout or stderr are None then
    output is discarded.

    It then returns a tuple of (exit code, stdout output, stderr output).
    If stdout was not equal to subprocess.PIPE, stdout will be None. Same for
    stderr.

    '''
    if stdout is None or stderr is None:
        dev_null = open(os.devnull, 'w')
        stdout = stdout or dev_null
        stderr = stderr or dev_null
    else:
        dev_null = None

    log = logging.getLogger('sandboxlib')
    log.debug('Running: %s', argv_to_string(argv))

    try:
        process = subprocess.Popen(
            argv,
            # The default is to share file descriptors from the parent process
            # to the subprocess, which is rarely good for sandboxing.
            close_fds=True,
            cwd=cwd,
            env=env,
            stdout=stdout,
            stderr=stderr,
        )

        # The 'out' variable will be None unless subprocess.PIPE was passed as
        # 'stdout' to subprocess.Popen(). Same for 'err' and 'stderr'. If
        # subprocess.PIPE wasn't passed for either it'd be safe to use .wait()
        # instead of .communicate(), but if they were then we must use
        # .communicate() to avoid blocking the subprocess if one of the pipes
        # becomes full. It's safe to use .communicate() in all cases.

        out, err = process.communicate()
    finally:
        if dev_null is not None:
            dev_null.close()

    return process.returncode, out, err


# Executors
import sandboxlib.chroot
import sandboxlib.linux_user_chroot

import sandboxlib.load
import sandboxlib.utils