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 # XXX SMBAKER: I don't know what this error is, but it's being returned
55 #print " X509_V_ERR_CERT_NOT_YET_VALID"
58 # allow self-signed certificates
60 #print " X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT"
63 # allow certs that don't have an issuer
65 #print " X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY"
68 # allow certs that are untrusted
70 #print " X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE"
73 # allow certs that are untrusted
75 #print " X509_V_ERR_CERT_UNTRUSTED"
78 print " error", err, "in verify_callback"
83 # Taken from the web (XXX find reference). Implements an HTTPS xmlrpc server
85 class SecureXMLRPCServer(BaseHTTPServer.HTTPServer,SimpleXMLRPCServer.SimpleXMLRPCDispatcher):
86 def __init__(self, server_address, HandlerClass, key_file, cert_file, logRequests=True):
87 """Secure XML-RPC server.
89 It it very similar to SimpleXMLRPCServer but it uses HTTPS for transporting XML data.
91 self.logRequests = logRequests
93 SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self, True, None)
94 SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
95 ctx = SSL.Context(SSL.SSLv23_METHOD)
96 ctx.use_privatekey_file(key_file)
97 ctx.use_certificate_file(cert_file)
98 ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)
99 ctx.set_app_data(self)
100 self.socket = SSL.Connection(ctx, socket.socket(self.address_family,
103 self.server_activate()
107 # Convert an exception on the server to a full stack trace and send it to
110 def _dispatch(self, method, params):
112 return SimpleXMLRPCServer.SimpleXMLRPCDispatcher._dispatch(self, method, params)
114 # can't use format_exc() as it is not available in jython yet
116 type, value, tb = sys.exc_info()
117 raise xmlrpclib.Fault(1,''.join(traceback.format_exception(type, value, tb)))
120 # taken from the web (XXX find reference). Implents HTTPS xmlrpc request handler
122 class SecureXMLRpcRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
123 """Secure XML-RPC request handler class.
125 It it very similar to SimpleXMLRPCRequestHandler but it uses HTTPS for transporting XML data.
128 self.connection = self.request
129 self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
130 self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
133 """Handles the HTTPS POST request.
135 It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
140 data = self.rfile.read(int(self.headers["content-length"]))
141 # In previous versions of SimpleXMLRPCServer, _dispatch
142 # could be overridden in this class, instead of in
143 # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
144 # check to see if a subclass implements _dispatch and dispatch
145 # using that method if present.
146 response = self.server._marshaled_dispatch(
147 data, getattr(self, '_dispatch', None)
149 except: # This should only happen if the module is buggy
150 # internal error, report as HTTP server error
151 self.send_response(500)
155 # got a valid XML RPC response
156 self.send_response(200)
157 self.send_header("Content-type", "text/xml")
158 self.send_header("Content-length", str(len(response)))
160 self.wfile.write(response)
162 # shut down the connection
164 self.connection.shutdown() # Modified here!
167 # Implements an HTTPS XML-RPC server. Generally it is expected that GENI
168 # functions will take a credential string, which is passed to
169 # decode_authentication. Decode_authentication() will verify the validity of
170 # the credential, and verify that the user is using the key that matches the
171 # GID supplied in the credential.
173 class GeniServer(threading.Thread):
176 # Create a new GeniServer object.
178 # @param ip the ip address to listen on
179 # @param port the port to listen on
180 # @param key_file private key filename of registry
181 # @param cert_file certificate filename containing public key
182 # (could be a GID file)
184 def __init__(self, ip, port, key_file, cert_file):
185 threading.Thread.__init__(self)
186 self.key = Keypair(filename = key_file)
187 self.cert = Certificate(filename = cert_file)
188 self.server = SecureXMLRPCServer((ip, port), SecureXMLRpcRequestHandler, key_file, cert_file)
189 self.trusted_cert_list = None
190 self.register_functions()
193 # Decode the credential string that was submitted by the caller. Several
194 # checks are performed to ensure that the credential is valid, and that the
195 # callerGID included in the credential matches the caller that is
196 # connected to the HTTPS connection.
198 def decode_authentication(self, cred_string, operation):
199 self.client_cred = Credential(string = cred_string)
200 self.client_gid = self.client_cred.get_gid_caller()
201 self.object_gid = self.client_cred.get_gid_object()
203 # make sure the client_gid is not blank
204 if not self.client_gid:
205 raise MissingCallerGID(self.client_cred.get_subject())
207 # make sure the client_gid matches client's certificate
208 peer_cert = self.server.peer_cert
209 if not peer_cert.is_pubkey(self.client_gid.get_pubkey()):
210 raise ConnectionKeyGIDMismatch(self.client_gid.get_subject())
212 # make sure the client is allowed to perform the operation
214 if not self.client_cred.can_perform(operation):
215 raise InsufficientRights(operation)
217 if self.trusted_cert_list:
218 self.client_cred.verify_chain(self.trusted_cert_list)
220 self.client_gid.verify_chain(self.trusted_cert_list)
222 self.object_gid.verify_chain(self.trusted_cert_list)
225 # Register functions that will be served by the XMLRPC server. This
226 # function should be overrided by each descendant class.
228 def register_functions(self):
229 self.server.register_function(self.noop)
232 # Sample no-op server function. The no-op function decodes the credential
233 # that was passed to it.
235 def noop(self, cred, anything):
236 self.decode_authentication(cred)
241 # Execute the server, serving requests forever.
244 self.server.serve_forever()