Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/rainbow/rainbow/inject.py
blob: 2d15ada6221e8a60e1ba464645906b353b5612e1 (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
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
import os
from os import R_OK, W_OK, X_OK, fork, symlink, unlink, O_CREAT, O_EXCL, readlink, chown, chmod
from os import setgroups, setgid, setuid, chdir, umask, execvpe, waitpid, WEXITSTATUS
from os import getpid, getuid, _exit, rename
from os.path import join, basename, realpath, lexists, islink
from subprocess import check_call, Popen, PIPE
from stat import S_IFDIR
from tempfile import mkdtemp, mkstemp
from grp import getgrnam
import resource

from rainbow.util import Checker, mount, make_dirs, get_fds, read_envdir

def strace(log, argv, env):
    log(1, 'applying strace')
    args = ['/usr/bin/strace', '-f']
    for k, v in env.iteritems():
        args.append('-E')
        args.append('%s=%s' % (k, v))
    args.extend(argv)

    return args, {}

def reserve_elt(pool_dir, elt, max_elt, incr, elt_name):
    fd = None
    while elt < max_elt:
        try:
            fd = os.open(join(pool_dir, str(elt)), O_EXCL | O_CREAT, 0600)
            os.close(fd)
            break
        except OSError:
            elt += incr
    if fd is None:
        raise RuntimeError("No " + elt_name + " available.")
    return elt

def reserve_credentials(log, spool, data_id, pset):
    # Pick a gid for yourself.
    gid = reserve_elt(join(spool, 'gid_pool'), 10001, 65534, 2, 'gids')

    # Then try to atomically symlink the gid you picked to 'name' in gid_dir.
    # If you succeed, then you have the right gid.
    # If you fail, someone else has the right gid so release yours and use theirs.
    name_path = join(spool, 'bundle_id_to_gid', data_id)
    gid_path = join(spool, 'gid_pool', str(gid))
    try:
        symlink(gid_path, name_path)
    except OSError:
        unlink(gid_path)
        gid = int(basename(realpath(name_path)))

    # Decide whether to reserve a new (even) uid or to set uid <- gid and reserve that.
    uid = pset.has_permission('constant-uid') and gid or reserve_elt(join(spool, 'uid_pool'), 10000, 65534, 2, 'uids')
    open(join(spool, 'uid_pool', str(gid)), 'w').close()
    log(1, 'reserved credentials (%d, %d)', uid, gid)

    path = join(spool, 'uid_to_gid', str(uid))
    if not lexists(path):
        symlink(str(gid), path)
    else:
        assert islink(path) and readlink(path) == str(gid)

    return (uid, gid)

def grab_home(log, spool, data_id, uid, gid, owner_gid):
    home = join(spool, 'uid_to_home_dir', str(uid))
    make_dirs(home, uid, owner_gid, 0770)
    chown(home, uid, owner_gid)
    # Per discussion with Bert Freudenberg, set the setgid bit on $SAR/instance
    # (i.e. $HOME) so that Sugar can better write inside it. <MS>
    chmod(home, 02770)
    return home

def configure_home(spool, owner_uid, owner_gid, uid, gid, home):
    # Beware of CONSTANT_UID + instance==home: the instance dir may already exist.
    path = join(spool, 'uid_to_instance_dir', str(uid))
    if not lexists(path):
        symlink(home, path)

    if not lexists(join(home, 'instance')):
        symlink('.', join(home, 'instance'))

    path = join(spool, 'gid_to_data_dir', str(gid))
    make_dirs(path, owner_uid, gid, 0770)
    chown(path, owner_uid, gid)
    chmod(path, 0770)
    if not lexists(join(home, 'data')):
        symlink(path, join(home, 'data'))

    #XXX: ARGH pippy. <MS>
    make_dirs(join(home, 'tmp'), uid, gid, 0700)
    mount('tmpfs', join(home, 'tmp'), 'tmpfs', 0, '')

def mount_fsen(log, home):
    log(1, 'Mounting tmpfsen on /tmp and /var/tmp.')
    #XXX: Kills X socket. :( <MS>
    #mount('tmpfs', '/tmp', 'tmpfs', 0, '')
    mount('tmpfs', '/var/tmp', 'tmpfs', 0, '')

def run_assistant(log, assistant, env, owner_uid, owner_gid, uid, groups, safe_fds):
    if assistant:
        envdir = None
        try:
            envdir = mkdtemp()
            chown(envdir, owner_uid, owner_gid)
            pid = fork()
        except:
            if envdir: check_call(['/bin/rm', '-rf', envdir])
            raise
        else:
            if not pid:
                log(1, 'Dropping privilege to run assistant.')
                setgroups(groups)
                setgid(owner_gid)
                setuid(owner_uid)
                log(1, 'Closing fds.')
                for fd in get_fds():
                    if fd not in safe_fds:
                        try: os.close(fd) # propagate failure from EIO or EBADF.
                        except: pass
                log(1, 'Running assistant.')
                assistant_argv = [assistant, '-v', '-v', '-v', '-u', str(uid), '-e', envdir]
                log(1, '%r %r', assistant_argv, env)
                execvpe(assistant_argv[0], assistant_argv, env)
                _exit(55)
            else:
                try:
                    pid, status = waitpid(pid, 0)
                    log(1, 'Assistant returned %d.', status)
                    assert not WEXITSTATUS(status)
                    return read_envdir(envdir)
                finally:
                    log(1, 'pid %d  uid %d', getpid(), getuid())
                    if envdir: check_call(['/bin/rm', '-rf', envdir])

def launch(log, home, uid, gid, groups, argv, env, cwd, pset, safe_fds):
    # Set appropriate group membership(s), depending on requested permissions
    log(1, 'dropping privilege to (%d, %d, %r)', uid, gid, groups)
    setgroups(groups)
    setgid(gid)
    setuid(uid)

    # Limit various resources
    # Must be done *after* setting uid/gid
    # This should come from the permissions.info file, but this is OK
    #   for now.
    try:
        def set_limit(lim_name, unix_name):
            p = pset.permission_params('lim_' + lim_name)
            if p != None:
                x = int(float(p[0]))
                y = int(float(x*1.10))
                log(1, 'Setting RLIMIT_%s to %d,%d', unix_name, x, y)
                resource.setrlimit(getattr(resource, 'RLIMIT_'+unix_name), (x,y))

        set_limit('nofile', 'NOFILE')
        set_limit('fsize', 'FSIZE')
        set_limit('mem', 'AS')
        set_limit('nproc', 'NPROC')

    except:
        pass # Why would we be throwing exceptions when setting rlimits? <MS>

    log(1, 'chdir to %s' % cwd)
    chdir(cwd)

    log(1, 'umask(0)')
    umask(0)

    if pset.has_permission('strace'):
        argv, env = strace(log, argv, env)

    log(1, 'about to execve\nargv: %s\nenv: %s', argv, env)
    log(1, 'closing all fds but %s', safe_fds)
    for fd in get_fds():
        if fd not in safe_fds:
            try: os.close(fd) # propagate failure from EIO or EBADF.
            except: pass

    execvpe(argv[0], argv, env)

def check_data_id(data_id):
    # XXX: How do I figure out what MAX_PATH_LEN is in python? <MS>
    # XXX: How long are GECOS fields permitted to be? <MS>
    assert data_id and '\0' not in data_id and len(data_id) < 128

def check_argv(argv):
    assert argv

def check_cwd(uid, gid, cwd):
    ck = Checker(cwd, uid, gid)
    assert ck.positive(R_OK | X_OK, S_IFDIR)

def check_spool(spool, owner_uid, owner_gid):
    make_dirs(spool, 0, 0, 0755)
    spool_dirs = ('uid_pool', 'gid_pool', 'uid_to_gid', 'bundle_id_to_gid',
                  'uid_to_instance_dir', 'gid_to_data_dir', 'uid_to_home_dir',
                  'xephyr_display_pool', 'uid_to_xephyr_cookie',
                  'uid_to_xephyr_display', 'uid_to_xephyr_auth')
    for frag in spool_dirs:
        make_dirs(join(spool, frag), 0, 0, 0755)
        ck = Checker(join(spool, frag), owner_uid, owner_gid)
        assert ck.positive(R_OK | X_OK, S_IFDIR)

def check_owner(owner_uid, owner_gid):
    return True

def check_home_dirs(uid, gid, home):
    for frag in ('instance', 'data', 'tmp'):
        ck = Checker(join(home, frag), uid, gid)
        assert ck.positive(R_OK | W_OK | X_OK, S_IFDIR)

def check_home(uid, gid, home):
    ck = Checker(home, uid, gid)
    assert ck.positive(R_OK | W_OK | X_OK, S_IFDIR)

def configure_groups(groups, gid, pset):
    groups.insert(0, gid)
    if pset.has_permission("audio"): groups.append(getgrnam("audio").gr_gid)
    if pset.has_permission("video"): groups.append(getgrnam("video").gr_gid)
    if pset.has_permission("serial"): groups.append(getgrnam("uucp").gr_gid)
    return list(set(groups))

def configure_xephyr(log, spool, owner_gid, uid, env, safe_fds):
    # XXX: MUST CHECK RETURN VALUES on subprocesses!!!!!
    # XXX: I shouldn't be running these subprocesses as uid 0.
    # XXX: Must get env, fds right!!!!
    cookie = Popen(["mcookie"], stdout=PIPE).communicate()[0]
    symlink(cookie, join(spool, 'uid_to_xephyr_cookie', str(uid)))
    display = reserve_elt(join(spool, 'xephyr_display_pool'), 100, 10000, 2, 'displays')
    symlink(str(display), join(spool, 'uid_to_xephyr_display', str(uid)))

    fd, name = mkstemp(prefix='tmp', dir=join(spool, 'uid_to_xephyr_auth'))
    os.close(fd)
    Popen(["xauth", "-f", name], stdin=PIPE).communicate("add :%d . %s\n" % (display, cookie))
    auth_path = join(spool, 'uid_to_xephyr_auth', str(uid))
    rename(name, auth_path)
    chmod(auth_path, 0640)
    chown(auth_path, 0, owner_gid)

    Popen(["Xephyr", "-screen", "800x600x24", "-auth", auth_path, "-reset", "-terminate", ":%d" % display])

    newenv = {'DISPLAY' : ':%d' % display, 'XAUTHORITY' : auth_path}
    return newenv

def inject(log, spool, env, argv, cwd, pset, safe_fds, owner_uid, owner_gid,
           groups, data_id, assistant):
    # Note: exceptions are intended to bubble up to the caller and should
    # terminate execution.
    check_data_id(data_id)
    check_argv(argv)
    check_owner(owner_uid, owner_gid)

    check_spool(spool, owner_uid, owner_gid)

    uid, gid = reserve_credentials(log, spool, data_id, pset)
    home = grab_home(log, spool, data_id, uid, gid, owner_gid)
    configure_home(spool, owner_uid, owner_gid, uid, gid, home)

    if cwd is None:
        cwd = home
    check_cwd(uid, gid, cwd)
    check_home_dirs(uid, gid, home)
    check_home_dirs(owner_uid, owner_gid, home)
    check_home(uid, gid, home)

    groups = configure_groups(groups, gid, pset)
    env_updates = configure_xephyr(log, spool, owner_gid, uid, env, safe_fds)
    if env_updates: env.update(env_updates)
    env_updates = run_assistant(log, assistant, env, owner_uid, owner_gid, uid, groups, safe_fds)
    if env_updates: env.update(env_updates)

    mount_fsen(log, home)

    launch(log, home, uid, gid, groups, argv, env, cwd, pset, safe_fds)