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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
|
# IVLE - Informatics Virtual Learning Environment
# Copyright (C) 2007-2008 The University of Melbourne
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# Module: MakeUser
# Author: Matt Giuca
# Date: 1/2/2008
# Allows creation of users. This sets up the following:
# * User's jail and home directory within the jail.
# * Subversion repository (TODO)
# * Check out Subversion workspace into jail (TODO)
# * Database details for user
# * Unix user account
# TODO: Sanitize login name and other fields.
# Users must not be called "temp" or "template".
# TODO: When creating a new home directory, chown it to its owner
# TODO: In chown_to_webserver:
# Do not call os.system("chown www-data") - use Python lib
# and use the web server uid given in conf. (Several places).
import md5
import os
import stat
import shutil
import time
import uuid
import warnings
import filecmp
import logging
import ivle.conf
import ivle.pulldown_subj
from ivle.database import ProjectGroup
def chown_to_webserver(filename):
"""
Chowns a file so the web server user owns it.
(This is useful in setting up Subversion conf files).
Assumes root.
"""
try:
os.system("chown -R www-data:www-data %s" % filename)
except:
pass
def make_svn_repo(path, throw_on_error=True):
"""Create a Subversion repository at the given path.
"""
try:
res = os.system("svnadmin create '%s'" % path)
if res != 0 and throw_on_error:
raise Exception("Cannot create repository: %s" % path)
except Exception, exc:
print repr(exc)
if throw_on_error:
raise
chown_to_webserver(path)
def rebuild_svn_config(store):
"""Build the complete SVN configuration file.
"""
users = store.find(ivle.database.User)
groups = {}
for u in users:
role = str(u.role)
if role not in groups:
groups[role] = []
groups[role].append(u.login)
f = open(ivle.conf.svn_conf + ".new", "w")
f.write("# IVLE SVN Repositories Configuration\n")
f.write("# Auto-generated on %s\n" % time.asctime())
f.write("\n")
f.write("[groups]\n")
for (g,ls) in groups.iteritems():
f.write("%s = %s\n" % (g, ",".join(ls)))
f.write("\n")
for u in users:
f.write("[%s:/]\n" % u.login)
f.write("%s = rw\n" % u.login)
#f.write("@tutor = r\n")
#f.write("@lecturer = rw\n")
#f.write("@admin = rw\n")
f.write("\n")
f.close()
os.rename(ivle.conf.svn_conf + ".new", ivle.conf.svn_conf)
chown_to_webserver(ivle.conf.svn_conf)
def rebuild_svn_group_config(store):
"""Build the complete SVN configuration file for groups
"""
f = open(ivle.conf.svn_group_conf + ".new", "w")
f.write("# IVLE SVN Group Repositories Configuration\n")
f.write("# Auto-generated on %s\n" % time.asctime())
f.write("\n")
for group in store.find(ProjectGroup):
offering = group.project_set.offering
reponame = "_".join([offering.subject.short_name,
offering.semester.year,
offering.semester.semester,
group.name])
f.write("[%s:/]\n"%reponame)
for user in group.members:
f.write("%s = rw\n" % user.login)
f.write("\n")
f.close()
os.rename(ivle.conf.svn_group_conf + ".new", ivle.conf.svn_group_conf)
chown_to_webserver(ivle.conf.svn_group_conf)
def make_svn_auth(store, login, throw_on_error=True):
"""Setup svn authentication for the given user.
Uses the given DB store object. Does not commit to the db.
"""
passwd = md5.new(uuid.uuid4().bytes).digest().encode('hex')
if os.path.exists(ivle.conf.svn_auth_ivle):
create = ""
else:
create = "c"
user = ivle.database.User.get_by_login(store, login)
user.svn_pass = unicode(passwd)
res = os.system("htpasswd -%smb %s %s %s" % (create,
ivle.conf.svn_auth_ivle,
login, passwd))
if res != 0 and throw_on_error:
raise Exception("Unable to create ivle-auth for %s" % login)
# Make sure the file is owned by the web server
if create == "c":
chown_to_webserver(ivle.conf.svn_auth_ivle)
return passwd
def generate_manifest(basedir, targetdir, parent=''):
""" From a basedir and a targetdir work out which files are missing or out
of date and need to be added/updated and which files are redundant and need
to be removed.
parent: This is used for the recursive call to track the relative paths
that we have decended.
"""
cmp = filecmp.dircmp(basedir, targetdir)
# Add all new files and files that have changed
to_add = [os.path.join(parent,x) for x in (cmp.left_only + cmp.diff_files)]
# Remove files that are redundant
to_remove = [os.path.join(parent,x) for x in cmp.right_only]
# Recurse
for d in cmp.common_dirs:
newbasedir = os.path.join(basedir, d)
newtargetdir = os.path.join(targetdir, d)
newparent = os.path.join(parent, d)
(sadd,sremove) = generate_manifest(newbasedir, newtargetdir, newparent)
to_add += sadd
to_remove += sremove
return (to_add, to_remove)
def make_jail(user, force=True):
"""Creates a new user's jail space, in the jail directory as configured in
conf.py.
This only creates things within /home - everything else is expected to be
part of another UnionFS branch.
Returns the path to the user's home directory.
Chowns the user's directory within the jail to the given UID.
force: If false, exception if jail already exists for this user.
If true (default), overwrites it, but preserves home directory.
"""
# MUST run as root or some of this may fail
if os.getuid() != 0:
raise Exception("Must run make_jail as root")
# tempdir is for putting backup homes in
tempdir = os.path.join(ivle.conf.jail_base, '__temp__')
if not os.path.exists(tempdir):
os.makedirs(tempdir)
elif not os.path.isdir(tempdir):
os.unlink(tempdir)
os.mkdir(tempdir)
userdir = os.path.join(ivle.conf.jail_src_base, user.login)
homedir = os.path.join(userdir, 'home')
userhomedir = os.path.join(homedir, user.login) # Return value
if os.path.exists(userdir):
if not force:
raise Exception("User's jail already exists")
# User jail already exists. Blow it away but preserve their home
# directory. It should be all that is there anyway, but you never
# know!
# Ignore warnings about the use of tmpnam
warnings.simplefilter('ignore')
homebackup = os.tempnam(tempdir)
warnings.resetwarnings()
# Note: shutil.move does not behave like "mv" - it does not put a file
# into a directory if it already exists, just fails. Therefore it is
# not susceptible to tmpnam symlink attack.
shutil.move(homedir, homebackup)
shutil.rmtree(userdir)
os.makedirs(homedir)
shutil.move(homebackup, homedir)
# Change the ownership of all the files to the right unixid
logging.debug("chown %s's home directory files to uid %d"
%(user.login, user.unixid))
os.chown(userhomedir, user.unixid, user.unixid)
for root, dirs, files in os.walk(userhomedir):
for fsobj in dirs + files:
os.chown(os.path.join(root, fsobj), user.unixid, user.unixid)
else:
# No user jail exists
# Set up the user's home directory
os.makedirs(userhomedir)
# Chown (and set the GID to the same as the UID).
os.chown(userhomedir, user.unixid, user.unixid)
# Chmod to rwxr-xr-x (755)
os.chmod(userhomedir, 0755)
make_conf_py(user.login, userdir, ivle.conf.jail_system, user.svn_pass)
make_etc_passwd(user.login, userdir, ivle.conf.jail_system, user.unixid)
return userhomedir
def make_conf_py(username, user_jail_dir, staging_dir, svn_pass):
"""
Creates (overwriting any existing file, and creating directories) a
file ${python_site_packages}/ivle/conf/conf.py in a given user's jail.
username: Username.
user_jail_dir: User's jail dir, ie. ivle.conf.jail_base + username
staging_dir: The dir with the staging copy of the jail. (With the
template conf.py file).
svn_pass: As with make_jail. User's SVN password, but if not supplied,
will look up in the DB.
"""
template_conf_path = os.path.join(staging_dir,
ivle.conf.python_site_packages[1:], "ivle/conf/conf.py")
conf_path = os.path.join(user_jail_dir,
ivle.conf.python_site_packages[1:], "ivle/conf/conf.py")
os.makedirs(os.path.dirname(conf_path))
# Read the contents of the template conf file
try:
template_conf_file = open(template_conf_path, "r")
template_conf_data = template_conf_file.read()
template_conf_file.close()
except:
# Couldn't open template conf.py for some reason
# Just treat it as empty file
template_conf_data = ("# Warning: Problem building config script.\n"
"# Could not find template conf.py file.\n")
conf_file = open(conf_path, "w")
conf_file.write(template_conf_data)
conf_file.write("\n# The login name for the owner of the jail\n")
conf_file.write("login = %s\n" % repr(username))
conf_file.write("\n")
conf_file.write("# The subversion-only password for the owner of "
"the jail\n")
conf_file.write("svn_pass = %s\n" % repr(svn_pass))
conf_file.close()
# Make this file world-readable
# (chmod 644 conf_path)
os.chmod(conf_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP
| stat.S_IROTH)
def make_etc_passwd(username, user_jail_dir, template_dir, unixid):
"""
Creates /etc/passwd in the given user's jail. This will be identical to
that in the template jail, except for the added entry for this user.
"""
template_passwd_path = os.path.join(template_dir, "etc/passwd")
passwd_path = os.path.join(user_jail_dir, "etc/passwd")
passwd_dir = os.path.dirname(passwd_path)
if not os.path.exists(passwd_dir):
os.makedirs(passwd_dir)
shutil.copy(template_passwd_path, passwd_path)
passwd_file = open(passwd_path, 'a')
passwd_file.write('%s:x:%d:%d::/home/%s:/bin/bash'
% (username, unixid, unixid, username))
passwd_file.close()
def mount_jail(login):
# This is where we'll mount to...
destdir = os.path.join(ivle.conf.jail_base, login)
# ... and this is where we'll get the user bits.
srcdir = os.path.join(ivle.conf.jail_src_base, login)
try:
if not os.path.exists(destdir):
os.mkdir(destdir)
if os.system('/bin/mount -t aufs -o dirs=%s:%s=ro none %s'
% (srcdir, ivle.conf.jail_system, destdir)) == 0:
logging.info("mounted user %s's jail." % login)
else:
logging.error("failed to mount user %s's jail!" % login)
except Exception, message:
logging.warning(str(message))
|