sslxmlrpc_server.py.in 14.1 KB
Newer Older
1
#!/usr/local/bin/python
2
#
3 4
# EMULAB-COPYRIGHT
# Copyright (c) 2005-2010 University of Utah and the Flux Group.
5 6 7 8
# All rights reserved.
#
import sys
import getopt
Timothy Stack's avatar
 
Timothy Stack committed
9
import os, os.path
10
import pwd
11 12 13 14
import traceback
import syslog
import string

Timothy Stack's avatar
 
Timothy Stack committed
15 16 17 18
import BaseHTTPServer

from SimpleXMLRPCServer import SimpleXMLRPCDispatcher

19
# Testbed specific stuff
Timothy Stack's avatar
 
Timothy Stack committed
20 21 22 23 24
TBPATH = "@prefix@/lib"
if TBPATH not in sys.path:
    sys.path.append(TBPATH)
    pass

25
from libdb        import *
26

Timothy Stack's avatar
 
Timothy Stack committed
27 28 29 30 31 32 33
try:
    from M2Crypto import SSL
    from M2Crypto.SSL import SSLError
except ImportError, e:
    sys.stderr.write("error: The py-m2crypto port is not installed\n")
    sys.exit(1)
    pass
34 35 36 37 38 39 40 41 42 43 44 45 46 47

# When debugging, runs in foreground printing to stdout instead of syslog
debug           = 0

# The port to listen on. We should get this from configure.
PORT            = 3069

# The local address. Using INADDY_ANY for now.
ADDR            = "0.0.0.0"

# The server certificate and the server CS.
server_cert     = "@prefix@/etc/server.pem"
ca_cert         = "@prefix@/etc/emulab.pem"

48 49 50 51 52 53 54
#
# By default, run a wrapper class that includes all off the modules.
# The client can invoke methods of the form experiment.swapexp when
# the server is invoked in this manner.
# 
DEFAULT_MODULE = "EmulabServer"
module         = DEFAULT_MODULE
55

Timothy Stack's avatar
 
Timothy Stack committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69
#
# "Standard" paths for the real and development versions of the software.
#
STD_PATH       = "/usr/testbed"
STD_DEVEL_PATH = "/usr/testbed/devel"

#
# The set of paths that the user is allowed to specify in their request.  The
# path specifies where the 'emulabserver' module will be loaded from.  In
# reality, the path only has an effect on the first request in a persistent
# connection, any subsequent requests will reuse the same module.
#
ALLOWED_PATHS  = [ STD_PATH, "@prefix@" ]

70 71
# syslog facility
LOGFACIL	= "@TBLOGFACIL@"
72

Timothy Stack's avatar
 
Timothy Stack committed
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
##
# Taken from the SimpleXMLRPCServer module in the python installation and
# modified to support persistent connections.
#
class MyXMLRPCRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    """Simple XML-RPC request handler class.

    Handles all HTTP POST requests and attempts to decode them as
    XML-RPC requests.
    """

    ##
    # Change the default protocol so that persistent connections are the norm.
    #
    protocol_version = "HTTP/1.1"

    ##
    # Handle a POST request from the user.  This method was changed from the
    # standard version to not close the 
    #
    def do_POST(self):
        """Handles the HTTP POST request.

        Attempts to interpret all HTTP POST requests as XML-RPC calls,
        which are forwarded to the server's _dispatch method for handling.
        """

        # Update PYTHONPATH with the user's requested path.
Leigh B. Stoller's avatar
Leigh B. Stoller committed
101
        self.server.set_path(self.path, self.client_address)
Timothy Stack's avatar
 
Timothy Stack committed
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

        try:
            # get arguments
            data = self.rfile.read(int(self.headers["content-length"]))
            # In previous versions of SimpleXMLRPCServer, _dispatch
            # could be overridden in this class, instead of in
            # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
            # check to see if a subclass implements _dispatch and dispatch
            # using that method if present.
            response = self.server._marshaled_dispatch(
                    data, getattr(self, '_dispatch', None)
                )
        except: # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            self.send_response(500)
            self.end_headers()
            self.wfile.flush()
        else:
            # got a valid XML RPC response
            self.send_response(200)
            self.send_header("Content-type", "text/xml")
            self.send_header("Content-length", str(len(response)))
            self.end_headers()
            self.wfile.write(response)
            self.wfile.flush()
            pass
        return

    def log_request(self, code='-', size='-'):
        """Selectively log an accepted request."""

        if self.server.logRequests:
            BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size)


137
#
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
# A simple server based on the forking version SSLServer. We fork cause
# we want to change our uid/gid to that of the person on the other end.
# 
class MyServer(SSL.ForkingSSLServer, SimpleXMLRPCDispatcher):
    def __init__(self, debug):
        self.debug         = debug
	self.logRequests   = 0
        self.emulabserver  = None;

	ctx = SSL.Context('sslv23')
	ctx.load_cert(server_cert, server_cert)
	ctx.load_verify_info(ca_cert)
        ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 16)
	ctx.set_allow_unknown_ca(0)
	#ctx.set_info_callback()
Timothy Stack's avatar
 
Timothy Stack committed
153
        
Mike Hibler's avatar
Mike Hibler committed
154 155 156 157 158
        dargs = (self,)
        if sys.version_info[0] >= 2 and sys.version_info[1] >= 5:
            dargs = (self,False,None)
            pass
        SimpleXMLRPCDispatcher.__init__(*dargs)
159
        SSL.SSLServer.__init__(self, (ADDR, PORT),
Timothy Stack's avatar
 
Timothy Stack committed
160
                               MyXMLRPCRequestHandler, ctx)
161 162
	pass

Timothy Stack's avatar
 
Timothy Stack committed
163 164 165 166 167
    ##
    # Log a message to stdout, if in debug mode, otherwise write to syslog.
    #
    # @param msg The message to log.
    #
168 169 170 171 172 173 174 175
    def logit(self, msg):
        if debug:
            print msg
            pass
        else:
            syslog.syslog(syslog.LOG_INFO, msg);
            pass
        return
Timothy Stack's avatar
 
Timothy Stack committed
176 177 178 179 180 181 182 183 184

    ##
    # Updates PYTHONPATH and imports the 'emulabserver' module on its first
    # invocation.  The specified path must be in the ALLOWED_PATHS list and
    # readable by the user, otherwise the request will fail.
    #
    # @param path The path from the POST request, should not include "lib" on
    # the end (e.g. "/usr/testbed")
    #
Leigh B. Stoller's avatar
Leigh B. Stoller committed
185
    def set_path(self, path, client_address):
Timothy Stack's avatar
 
Timothy Stack committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199
        if not self.emulabserver:
            if path not in ALLOWED_PATHS:
                self.logit("Disallowed path: %s" % path)
                raise Exception("Path not allowed: %s" % path)
            path = os.path.join(path, "lib")
            if not os.access(path, os.X_OK):
                self.logit("Path not accessible by user: %s" % path)
                raise Exception("Permission denied: %s" % path)

            if path not in sys.path:
                sys.path.append(path)
                pass
            from emulabserver import EmulabServer
            
Leigh B. Stoller's avatar
Leigh B. Stoller committed
200
            self.emulabserver = EmulabServer(readonly=0,
201 202
                                             clientip=client_address[0],
                                             debug=self.debug)
Timothy Stack's avatar
 
Timothy Stack committed
203 204
            pass
        return
205 206 207 208 209 210 211 212 213 214 215 216 217
    
    #
    # There might be a better arrangement, but the problem is that we
    # do not want to create the server instance until we get a chance
    # to look at the certificate and determine the priv level. See
    # below in process_request(). 
    #
    def _dispatch(self, method, params):
        try:
            meth = getattr(self.emulabserver, method);
        except AttributeError:
            raise Exception('method "%s" is not supported' % method)
        else:
218
            self.logit("Calling method '" + method + "'");
219 220 221 222
            return apply(meth, params);
        pass

    #
223
    # Get the unix_uid for the user. User must be active. 
224
    #
225 226 227
    def getuserid(self, uuid):
        userQuery = DBQueryFatal("select uid,uid_idx,unix_uid,status "
                                 "  from users "
228 229
                                 "where (uid_uuid=%s or uid=%s) and "
                                 "       status='active'",
230
                                 (uuid, uuid))
231
        
232
        if len(userQuery) == 0:
233
            return (None, None, 0);
234
        
235 236
        if (userQuery[0][3] != "active"):
            return (None, None, -1);
237
        
238
        return (userQuery[0][0], int(userQuery[0][1]), int(userQuery[0][2]))
Timothy Stack's avatar
 
Timothy Stack committed
239 240

    #
241
    # Check if the user is an stud.
Timothy Stack's avatar
 
Timothy Stack committed
242
    #
243 244 245
    def isstuduser(self, uid_idx):
        res = DBQueryFatal("select stud from users where uid_idx=%s",
                           (str(uid_idx),))
Timothy Stack's avatar
 
Timothy Stack committed
246 247 248 249 250

        if len(res) == 0:
            return 0

        return res[0][0]
251
    
252 253 254
    #
    # Check the certificate serial number. 
    #
255
    def checkcert(self, uid_idx, serial):
256
        res = DBQueryFatal("select idx from user_sslcerts "
257
                           "where uid_idx=%s and idx=%s and revoked is null ",
258
                           (str(uid_idx), serial))
259 260 261

        return len(res)
    
262 263 264
    #
    # Get the group list for the user.
    #
265
    def getusergroups(self, uid_idx):
266 267 268 269 270
        result = []
        
        res = DBQueryFatal("select distinct g.gid,g.unix_gid "
                           "  from group_membership as m "
                           "left join groups as g on "
271 272
                           "  g.pid_idx=m.pid_idx and g.gid_idx=m.gid_idx "
                           "where m.uid_idx=%s "
273
                           "order by date_approved asc ",
274
                           (str(uid_idx),))
275 276 277 278 279 280
        
        for group in res:
            result.append(int(group[1]));
            pass
    
        return result
281

282 283 284 285 286 287 288 289
    #
    # Flip to the user that is in the certificate.
    #
    def fliptouser(self, request, client):
        subject = request.get_peer_cert().get_subject()
        if self.debug:
            self.logit(str(subject))
            pass
290 291 292 293 294 295

        #
        # The CN might look like UUID,serial so split it up.
        #
        cnwords = getattr(subject, "CN").split(",")
        self.uuid = cnwords[0]
296 297 298 299
        
        #
        # Must be a valid and non-zero unix_uid from the DB.
        #
300
        (self.uid,self.uid_idx,self.unix_uid) = self.getuserid(self.uuid)
301
        
302 303 304
        if self.unix_uid == 0:
            self.logit('No such user: "%s"' % self.uuid)
            raise Exception('No such user: "%s"' % self.uuid)
305
        
306 307 308 309
        if self.unix_uid == -1:
            self.logit('User "%s,%d" is not active' % (self.uid,self.uid_idx))
            raise Exception('User "%s,%d" is not active' %
                            (self.uid,self.uid_idx))
Timothy Stack's avatar
 
Timothy Stack committed
310

311
        self.stud = self.isstuduser(self.uid_idx)
312
        if self.stud:
313 314 315 316 317 318 319
            try:
                ALLOWED_PATHS.extend(map(lambda x:
                                         os.path.join(STD_DEVEL_PATH, x),
                                         os.listdir(STD_DEVEL_PATH)))
                pass
            except OSError:
                pass
Timothy Stack's avatar
 
Timothy Stack committed
320
            pass
321
        
322
        self.glist = self.getusergroups(self.uid_idx);
323
        if len(self.glist) == 0:
324 325 326
            self.logit('No groups for user: "%s,%d"' % (self.uid,self.uid_idx))
            raise Exception('No groups for user: "%s,%d"' %
                            (self.uid,self.uid_idx))
327

328 329
        self.logit("Connect from %s: %s,%d %s" %
                   (client[0], self.uid, self.uid_idx, str(self.glist)))
330
        
331 332 333 334 335 336 337
        #
        # Check the certificate serial number. At the moment, the serial
        # must match a certificate that is in the DB for that user. This
        # is my crude method of certificate revocation. 
        #
        serial = request.get_peer_cert().get_serial_number()
        
338
        if self.checkcert(self.uid_idx, serial) == 0:
339 340 341
            self.logit('No such cert with serial "%s"' % serial)
            raise Exception('No such cert with serial "%s"' % serial)
        
342 343 344
        try:
            os.setgid(self.glist[0])
            os.setgroups(self.glist)
345 346
            os.setuid(self.unix_uid)
            pwddb = pwd.getpwuid(self.unix_uid);
347

348
            os.environ["HOME"]    = pwddb[5];
349 350
            os.environ["USER"]    = self.uid;
            os.environ["LOGNAME"] = self.uid;
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
            pass
        except:
            traceback.print_exc()
            os._exit(1)
            pass
        pass

    #
    # XXX - The builtin process_request() method for ForkingMixIn is
    # broken; it closes the "request" in the parent which shuts down
    # the ssl connection. So, I have moved the close_request into the
    # child where it should be, and in the parent I close the socket
    # by reaching into the Connection() class.
    # 
    # In any event, I need to do some other stuff in the child before we
    # actually handle the request. 
    # 
    def process_request(self, request, client_address):
        """Fork a new subprocess to process the request."""
        self.collect_children()
        pid = os.fork()
        if pid:
            # Parent process
            if self.active_children is None:
                self.active_children = []
            self.active_children.append(pid)
            request.socket.close()
            return
        else:
            # Child process.
            # This must never return, hence os._exit()!
            try:
                self.fliptouser(request, client_address);
Timothy Stack's avatar
 
Timothy Stack committed
384 385 386 387

                # Remove the old path since the user can request a different
                # one.
                sys.path.remove(TBPATH)
388 389 390 391 392 393 394 395 396 397 398 399 400
                self.finish_request(request, client_address)
                self.close_request(request)
                self.logit("request finished");
                os._exit(0)
            except:
                try:
                    self.handle_error(request, client_address)
                finally:
                    os._exit(1)

    def verify_request(self, request, client_address):
        return True

401 402
    pass

403 404 405 406 407 408 409 410 411 412
#
# Check for debug flag.
# 
if len(sys.argv) > 1 and sys.argv[1] == "-d":
    debug = 1
    pass

#
# Daemonize when not running in debug mode.
#
413 414
if not debug:
    #
Timothy Stack's avatar
 
Timothy Stack committed
415
    # Connect to syslog.
416 417
    #
    syslog.openlog("sslxmlrpc", syslog.LOG_PID,
Timothy Stack's avatar
 
Timothy Stack committed
418
                   getattr(syslog, "LOG_" + string.upper(LOGFACIL)))
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    syslog.syslog(syslog.LOG_INFO, "SSL XMLRPC server starting up");

    #
    # Daemonize. We redirect our output into a log file cause I have no
    # idea what is going to use plain print. 
    #
    try:
        fp = open("@prefix@/log/sslxmlrpc_server.log", "a");
        sys.stdout = fp
        sys.stderr = fp
        sys.stdin.close();
        pass
    except:
        print "Could not open log file for append"
        sys.exit(1);
        pass

    pid = os.fork()
    if pid:
        os.system("echo " + str(pid) + " > /var/run/sslxmlrpc_server.pid")
        sys.exit(0)
        pass
    os.setsid();
442 443 444
    pass

#
445 446 447
# Create the server and serve forever. We register the instance above
# when we process the request cause we want to look at the cert before
# we decide on the priv level. 
448
# 
449 450 451
server = MyServer(debug)
while 1:
    server.handle_request()