2 # This module implements a general-purpose server layer for geni.
3 # The same basic server should be usable on the registry, component, or
6 # TODO: investigate ways to combine this with existing PLC server?
9 import SimpleXMLRPCServer
16 import SimpleHTTPServer
17 import SimpleXMLRPCServer
21 from credential import *
24 from OpenSSL import SSL
27 # Verification callback for pyOpenSSL. We do our own checking of keys because
28 # we have our own authentication spec. Thus we disable several of the normal
29 # prohibitions that OpenSSL places on certificates
31 def verify_callback(conn, x509, err, depth, preverify):
32 # if the cert has been preverified, then it is ok
37 # we're only passing single certificates, not chains
39 #print " depth > 0 in verify_callback"
42 # create a Certificate object and load it from the client's x509
43 ctx = conn.get_context()
44 server = ctx.get_app_data()
45 server.peer_cert = Certificate()
46 server.peer_cert.load_from_pyopenssl_x509(x509)
48 # the certificate verification done by openssl checks a number of things
49 # that we aren't interested in, so we look out for those error messages
52 # allow self-signed certificates
54 #print " X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT"
57 # allow certs that don't have an issuer
59 #print " X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY"
62 # allow certs that are untrusted
64 #print " X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE"
67 # allow certs that are untrusted
69 #print " X509_V_ERR_CERT_UNTRUSTED"
72 print " error", err, "in verify_callback"
77 # Taken from the web (XXX find reference). Implements an HTTPS xmlrpc server
79 class SecureXMLRPCServer(BaseHTTPServer.HTTPServer,SimpleXMLRPCServer.SimpleXMLRPCDispatcher):
80 def __init__(self, server_address, HandlerClass, key_file, cert_file, logRequests=True):
81 """Secure XML-RPC server.
83 It it very similar to SimpleXMLRPCServer but it uses HTTPS for transporting XML data.
85 self.logRequests = logRequests
87 SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self, True, None)
88 SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
89 ctx = SSL.Context(SSL.SSLv23_METHOD)
90 ctx.use_privatekey_file(key_file)
91 ctx.use_certificate_file(cert_file)
92 ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)
93 ctx.set_app_data(self)
94 self.socket = SSL.Connection(ctx, socket.socket(self.address_family,
97 self.server_activate()
101 # Convert an exception on the server to a full stack trace and send it to
104 def _dispatch(self, method, params):
106 return SimpleXMLRPCServer.SimpleXMLRPCDispatcher._dispatch(self, method, params)
108 # can't use format_exc() as it is not available in jython yet
110 type, value, tb = sys.exc_info()
111 raise xmlrpclib.Fault(1,''.join(traceback.format_exception(type, value, tb)))
114 # taken from the web (XXX find reference). Implents HTTPS xmlrpc request handler
116 class SecureXMLRpcRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
117 """Secure XML-RPC request handler class.
119 It it very similar to SimpleXMLRPCRequestHandler but it uses HTTPS for transporting XML data.
122 self.connection = self.request
123 self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
124 self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
127 """Handles the HTTPS POST request.
129 It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
134 data = self.rfile.read(int(self.headers["content-length"]))
135 # In previous versions of SimpleXMLRPCServer, _dispatch
136 # could be overridden in this class, instead of in
137 # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
138 # check to see if a subclass implements _dispatch and dispatch
139 # using that method if present.
140 response = self.server._marshaled_dispatch(
141 data, getattr(self, '_dispatch', None)
143 except: # This should only happen if the module is buggy
144 # internal error, report as HTTP server error
145 self.send_response(500)
149 # got a valid XML RPC response
150 self.send_response(200)
151 self.send_header("Content-type", "text/xml")
152 self.send_header("Content-length", str(len(response)))
154 self.wfile.write(response)
156 # shut down the connection
158 self.connection.shutdown() # Modified here!
161 # Implements an HTTPS XML-RPC server. Generally it is expected that GENI
162 # functions will take a credential string, which is passed to
163 # decode_authentication. Decode_authentication() will verify the validity of
164 # the credential, and verify that the user is using the key that matches the
165 # GID supplied in the credential.
167 class GeniServer(threading.Thread):
170 # Create a new GeniServer object.
172 # @param ip the ip address to listen on
173 # @param port the port to listen on
174 # @param key_file private key filename of registry
175 # @param cert_file certificate filename containing public key
176 # (could be a GID file)
178 def __init__(self, ip, port, key_file, cert_file):
179 self.key = Keypair(filename = key_file)
180 self.cert = Certificate(filename = cert_file)
181 self.server = SecureXMLRPCServer((ip, port), SecureXMLRpcRequestHandler, key_file, cert_file)
182 self.trusted_cert_list = None
183 self.register_functions()
186 # Decode the credential string that was submitted by the caller. Several
187 # checks are performed to ensure that the credential is valid, and that the
188 # callerGID included in the credential matches the caller that is
189 # connected to the HTTPS connection.
191 def decode_authentication(self, cred_string, operation):
192 self.client_cred = Credential(string = cred_string)
193 self.client_gid = self.client_cred.get_gid_caller()
194 self.object_gid = self.client_cred.get_gid_object()
196 # make sure the client_gid is not blank
197 if not self.client_gid:
198 raise MissingCallerGID(self.client_cred.get_subject())
200 # make sure the client_gid matches client's certificate
201 peer_cert = self.server.peer_cert
202 if not peer_cert.is_pubkey(self.client_gid.get_pubkey()):
203 raise ConnectionKeyGIDMismatch(self.client_gid.get_subject())
205 # make sure the client is allowed to perform the operation
206 if not self.client_cred.can_perform(operation):
207 raise InsufficientRights(operation)
209 if self.trusted_cert_list:
210 self.client_cred.verify_chain(self.trusted_cert_list)
212 self.client_gid.verify_chain(self.trusted_cert_list)
214 self.object_gid.verify_chain(self.trusted_cert_list)
217 # Register functions that will be served by the XMLRPC server. This
218 # function should be overrided by each descendant class.
220 def register_functions(self):
221 self.server.register_function(self.noop)
224 # Sample no-op server function. The no-op function decodes the credential
225 # that was passed to it.
227 def noop(self, cred, anything):
228 self.decode_authentication(cred)
233 # Execute the server, serving requests forever.
236 self.server.serve_forever()