c4ba7cf3fee647bdeda6060d99cb9b5ae64f3cd7
[sfa.git] / util / geniserver.py
1 ##
2 # This module implements a general-purpose server layer for geni.
3 # The same basic server should be usable on the registry, component, or
4 # other interfaces.
5 #
6 # TODO: investigate ways to combine this with existing PLC server?
7 ##
8
9 import SimpleXMLRPCServer
10
11 import sys
12 import traceback
13 import threading
14 import SocketServer
15 import BaseHTTPServer
16 import SimpleHTTPServer
17 import SimpleXMLRPCServer
18
19 from excep import *
20 from cert import *
21 from credential import *
22
23 import socket, os
24 from OpenSSL import SSL
25
26 ##
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
30
31 def verify_callback(conn, x509, err, depth, preverify):
32     # if the cert has been preverified, then it is ok
33     if preverify:
34        #print "  preverified"
35        return 1
36
37     # we're only passing single certificates, not chains
38     if depth > 0:
39        #print "  depth > 0 in verify_callback"
40        return 0
41
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)
47
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
50     # and ignore them
51
52     # allow self-signed certificates
53     if err == 18:
54        #print "  X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT"
55        return 1
56
57     # allow certs that don't have an issuer
58     if err == 20:
59        #print "  X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY"
60        return 1
61
62     # allow certs that are untrusted
63     if err == 21:
64        #print "  X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE"
65        return 1
66
67     # allow certs that are untrusted
68     if err == 27:
69        #print "  X509_V_ERR_CERT_UNTRUSTED"
70        return 1
71
72     print "  error", err, "in verify_callback"
73
74     return 0\r
75
76 ##
77 # Taken from the web (XXX find reference). Implements an HTTPS xmlrpc server
78
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.
82
83         It it very similar to SimpleXMLRPCServer but it uses HTTPS for transporting XML data.
84         """
85         self.logRequests = logRequests
86
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,
95                                                         self.socket_type))
96         self.server_bind()
97         self.server_activate()
98
99     # _dispatch
100     #
101     # Convert an exception on the server to a full stack trace and send it to
102     # the client.
103
104     def _dispatch(self, method, params):
105         try:
106             return SimpleXMLRPCServer.SimpleXMLRPCDispatcher._dispatch(self, method, params)
107         except:
108             # can't use format_exc() as it is not available in jython yet
109             # (evein in trunk).
110             type, value, tb = sys.exc_info()
111             raise xmlrpclib.Fault(1,''.join(traceback.format_exception(type, value, tb)))
112
113 ##
114 # taken from the web (XXX find reference). Implents HTTPS xmlrpc request handler
115
116 class SecureXMLRpcRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
117     """Secure XML-RPC request handler class.
118
119     It it very similar to SimpleXMLRPCRequestHandler but it uses HTTPS for transporting XML data.
120     """
121     def setup(self):
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)
125
126     def do_POST(self):
127         """Handles the HTTPS POST request.
128
129         It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
130         """
131
132         try:
133             # get arguments
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)
142                 )
143         except: # This should only happen if the module is buggy
144             # internal error, report as HTTP server error
145             self.send_response(500)
146
147             self.end_headers()
148         else:
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)))
153             self.end_headers()
154             self.wfile.write(response)
155
156             # shut down the connection
157             self.wfile.flush()
158             self.connection.shutdown() # Modified here!
159
160 ##
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.
166
167 class GeniServer(threading.Thread):
168
169     ##
170     # Create a new GeniServer object.
171     #
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)
177
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()
184
185     ##
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.
190
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()
195
196         # make sure the client_gid is not blank
197         if not self.client_gid:
198             raise MissingCallerGID(self.client_cred.get_subject())
199
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())
204
205         # make sure the client is allowed to perform the operation
206         if not self.client_cred.can_perform(operation):
207             raise InsufficientRights(operation)
208
209         if self.trusted_cert_list:
210             self.client_cred.verify_chain(self.trusted_cert_list)
211             if self.client_gid:
212                 self.client_gid.verify_chain(self.trusted_cert_list)
213             if self.object_gid:
214                 self.object_gid.verify_chain(self.trusted_cert_list)
215
216     ##
217     # Register functions that will be served by the XMLRPC server. This
218     # function should be overrided by each descendant class.
219
220     def register_functions(self):
221         self.server.register_function(self.noop)
222
223     ##
224     # Sample no-op server function. The no-op function decodes the credential
225     # that was passed to it.
226
227     def noop(self, cred, anything):
228         self.decode_authentication(cred)
229
230         return anything
231
232     ##
233     # Execute the server, serving requests forever. 
234
235     def run(self):
236         self.server.serve_forever()
237
238