fix threading, ignore operation in decode_authentication when it is none
[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     # XXX SMBAKER: I don't know what this error is, but it's being returned
53     # by newer pl nodes.
54     if err == 9:
55        #print "  X509_V_ERR_CERT_NOT_YET_VALID"
56        return 1
57
58     # allow self-signed certificates
59     if err == 18:
60        #print "  X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT"
61        return 1
62
63     # allow certs that don't have an issuer
64     if err == 20:
65        #print "  X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY"
66        return 1
67
68     # allow certs that are untrusted
69     if err == 21:
70        #print "  X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE"
71        return 1
72
73     # allow certs that are untrusted
74     if err == 27:
75        #print "  X509_V_ERR_CERT_UNTRUSTED"
76        return 1
77
78     print "  error", err, "in verify_callback"
79
80     return 0\r
81
82 ##
83 # Taken from the web (XXX find reference). Implements an HTTPS xmlrpc server
84
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.
88
89         It it very similar to SimpleXMLRPCServer but it uses HTTPS for transporting XML data.
90         """
91         self.logRequests = logRequests
92
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,
101                                                         self.socket_type))
102         self.server_bind()
103         self.server_activate()
104
105     # _dispatch
106     #
107     # Convert an exception on the server to a full stack trace and send it to
108     # the client.
109
110     def _dispatch(self, method, params):
111         try:
112             return SimpleXMLRPCServer.SimpleXMLRPCDispatcher._dispatch(self, method, params)
113         except:
114             # can't use format_exc() as it is not available in jython yet
115             # (evein in trunk).
116             type, value, tb = sys.exc_info()
117             raise xmlrpclib.Fault(1,''.join(traceback.format_exception(type, value, tb)))
118
119 ##
120 # taken from the web (XXX find reference). Implents HTTPS xmlrpc request handler
121
122 class SecureXMLRpcRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
123     """Secure XML-RPC request handler class.
124
125     It it very similar to SimpleXMLRPCRequestHandler but it uses HTTPS for transporting XML data.
126     """
127     def setup(self):
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)
131
132     def do_POST(self):
133         """Handles the HTTPS POST request.
134
135         It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
136         """
137
138         try:
139             # get arguments
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)
148                 )
149         except: # This should only happen if the module is buggy
150             # internal error, report as HTTP server error
151             self.send_response(500)
152
153             self.end_headers()
154         else:
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)))
159             self.end_headers()
160             self.wfile.write(response)
161
162             # shut down the connection
163             self.wfile.flush()
164             self.connection.shutdown() # Modified here!
165
166 ##
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.
172
173 class GeniServer(threading.Thread):
174
175     ##
176     # Create a new GeniServer object.
177     #
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)
183
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()
191
192     ##
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.
197
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()
202
203         # make sure the client_gid is not blank
204         if not self.client_gid:
205             raise MissingCallerGID(self.client_cred.get_subject())
206
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())
211
212         # make sure the client is allowed to perform the operation
213         if operation:
214             if not self.client_cred.can_perform(operation):
215                 raise InsufficientRights(operation)
216
217         if self.trusted_cert_list:
218             self.client_cred.verify_chain(self.trusted_cert_list)
219             if self.client_gid:
220                 self.client_gid.verify_chain(self.trusted_cert_list)
221             if self.object_gid:
222                 self.object_gid.verify_chain(self.trusted_cert_list)
223
224     ##
225     # Register functions that will be served by the XMLRPC server. This
226     # function should be overrided by each descendant class.
227
228     def register_functions(self):
229         self.server.register_function(self.noop)
230
231     ##
232     # Sample no-op server function. The no-op function decodes the credential
233     # that was passed to it.
234
235     def noop(self, cred, anything):
236         self.decode_authentication(cred)
237
238         return anything
239
240     ##
241     # Execute the server, serving requests forever. 
242
243     def run(self):
244         self.server.serve_forever()
245
246