def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True): self.logRequests = logRequests SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) class VerifyingRequestHandler(SimpleXMLRPCRequestHandler): # this is the method we must override def parse_request(self): # first, call the original implementation which returns # True if all OK so far if SimpleXMLRPCRequestHandler.parse_request(self): return True return False # Override the normal socket methods with an SSL socket socketserver.BaseServer.__init__(self, addr, VerifyingRequestHandler) self.socket = ssl.wrap_socket( socket.socket(self.address_family, self.socket_type), server_side=True, keyfile=KEYFILE, certfile=CERTFILE, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23, ) if bind_and_activate: self.server_bind() self.server_activate() if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'): flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD) flags |= fcntl.FD_CLOEXEC fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
def __init__(self, host, port): '''create a XML-RPC server Takes two initial inputs: host -- hostname of XML-RPC server host port -- port number for server requests ''' Server.__init__(self) SimpleXMLRPCDispatcher.__init__(self,allow_none=False,encoding=None) self._installSocket(host, port) self._activeProcesses = {} #{ fd : pid }
def __init__(self, host, port): '''create a XML-RPC server Takes two initial inputs: host -- hostname of XML-RPC server host port -- port number for server requests ''' Server.__init__(self) SimpleXMLRPCDispatcher.__init__(self, allow_none=False, encoding=None) self._installSocket(host, port) self._activeProcesses = {} #{ fd : pid }
def __init__(self, dispatch_method, encoding=None): """ Sets up the servlet """ SimpleXMLRPCDispatcher.__init__(self, allow_none=True, encoding=encoding) # Register the system.* functions self.register_introspection_functions() # Make a link to the dispatch method self._dispatch_method = dispatch_method
def __init__(self, dispatch_method, encoding=None): """ Sets up the servlet """ SimpleXMLRPCDispatcher.__init__(self, allow_none=True, encoding=encoding) # Register the system.* functions self.register_introspection_functions() # Make a link to the dispatch method self._dispatch_method = dispatch_method
def __init__(self): SimpleXMLRPCDispatcher.__init__(self, allow_none=False, encoding=None) XMLRPCDocGenerator.__init__(self) def _dumps(obj, *args, **kwargs): kwargs['allow_none'] = self.allow_none kwargs['encoding'] = self.encoding return xmlrpc_client.dumps(obj, *args, **kwargs) self.dumps = _dumps # map of name => (auth, func) self.func_map = {}
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=False): self.logRequests = logRequests SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding, use_builtin_types) socketserver.ThreadingTCPServer.__init__(self, addr, requestHandler, bind_and_activate)
def init_server(self,host,port): dprint("Starting N4D ...") self.core=n4d.server.core.Core.get_core(DEBUG) self.server_host=host self.server_port=port self.handler=N4dServer.N4dCallHandler self.handler.encode_threshold=None self.server=N4dServer.ThreadedXMLRPCServer((host,port),self.handler,DEBUG) #allow_none SimpleXMLRPCDispatcher.__init__(self.server,allow_none=True) self.wrap_ssl() self.server.register_instance(self.core)
def init_secondary_server(self, host, port, ssl_wrapped=False): self.secondary_server_host = host self.secondary_server_port = port self.secondary_handler = N4dServer.N4dCallHandler self.is_secondary_server_secured = ssl_wrapped self.handler.encode_threshold = None self.secondary_server = N4dServer.ThreadedXMLRPCServer( (host, port), self.secondary_handler, DEBUG) SimpleXMLRPCDispatcher.__init__(self.secondary_server, allow_none=True) if ssl_wrapped: self.secondary_server.socket = ssl.wrap_socket( self.secondary_server.socket, N4dServer.N4D_KEYFILE, N4dServer.N4D_CERTFILE) self.secondary_server.register_instance(self.core)
def __init__(self, addr, ca_file, cert_key_file, requestHandler=XMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, crl_file_url=None): """Overriding __init__ method of the SimpleXMLRPCServer The method is a copy, except for the TCPServer __init__ call, which is rewritten using TLS, and the certfile argument which is required for TLS """ import socketserver self.logRequests = logRequests self.crl_file_url = crl_file_url SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) socketserver.BaseServer.__init__(self, addr, requestHandler) self.socket = ssl.wrap_socket(socket.socket( self.address_family, self.socket_type), server_side=True, certfile=cert_key_file, ca_certs=ca_file, cert_reqs=ssl.CERT_REQUIRED, ssl_version=PROTOCOL) if bind_and_activate: self.server_bind() self.server_activate() # [Bug #1222790] If possible, set close-on-exec flag; if a # method spawns a subprocess, the subprocess shouldn't have # the listening socket open. try: import fcntl except ImportError: pass else: if hasattr(fcntl, 'FD_CLOEXEC'): flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD) flags |= fcntl.FD_CLOEXEC fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
def __init__(self, section=None, configfile=None): super(XmlRpcBot, self).__init__(section, configfile) self.cfg['authorized_users'] = None allow_none = False encoding = None # SimpleXMLRPCDispatcher is still an "old-style" class, # so super doesn't work right # # further ick, this is an 'internal' class so signature changed # between python2.4 and python2.5 if sys.version_info[0] == 2 and sys.version_info[1] > 4: # python 2.5 version SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) else: # python 2.3, 2.4 version SimpleXMLRPCDispatcher.__init__(self) self.authorized_users = None
def __init__(self, section=None, configfile=None): super(XmlRpcBot, self).__init__(section, configfile) self.cfg['authorized_users'] = None allow_none = False encoding = None # SimpleXMLRPCDispatcher is still an "old-style" class, # so super doesn't work right # # further ick, this is an 'internal' class so signature changed # between python2.4 and python2.5 if sys.version_info[0] == 2 and sys.version_info[1] > 4: # python 2.5 version SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) else: # python 2.3, 2.4 version SimpleXMLRPCDispatcher.__init__(self) self.authorized_users = None
def __init__(self, addr, certfile, keyfile=None, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, ssl_version=ssl.PROTOCOL_TLSv1): self.logRequests = logRequests # create an SSL context self.context = ssl.SSLContext(ssl_version) self.context.load_cert_chain(certfile=certfile, keyfile=keyfile) SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) # call TCPServer constructor socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'): flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD) flags |= fcntl.FD_CLOEXEC fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
def __init__(self, addr, ca_file, cert_key_file, requestHandler=XMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, crl_file_url=None): """Overriding __init__ method of the SimpleXMLRPCServer The method is a copy, except for the TCPServer __init__ call, which is rewritten using TLS, and the certfile argument which is required for TLS """ import socketserver self.logRequests = logRequests self.crl_file_url = crl_file_url SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) socketserver.BaseServer.__init__(self, addr, requestHandler) self.socket = ssl.wrap_socket( socket.socket(self.address_family, self.socket_type), server_side=True, certfile=cert_key_file, ca_certs=ca_file, cert_reqs=ssl.CERT_REQUIRED, ssl_version=PROTOCOL) if bind_and_activate: self.server_bind() self.server_activate() # [Bug #1222790] If possible, set close-on-exec flag; if a # method spawns a subprocess, the subprocess shouldn't have # the listening socket open. try: import fcntl except ImportError: pass else: if hasattr(fcntl, 'FD_CLOEXEC'): flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD) flags |= fcntl.FD_CLOEXEC fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
def __init__(self, addr, useSSL=False, logRequests=False, allow_none=False, encoding=None): """:param addr: the (server address,port)-tuple) :param logRequests: patched thru to the base class""" certfile = config().get("Network", "personalSSLCertificate") keyfile = config().get("Network", "privateSSLKey") self.useSSL = useSSL if self.useSSL and not path.exists(certfile): warning( "No certficate file", certfile, "exists. Therefor no SSL-connection for the FoamServer possible\n", "To generate a private key:\n", (" openssl genrsa -out %s 2048" % keyfile), "\nThen generate the cerificate that is valid for 3 years with \n", (" openssl req -new -x509 -key %s -out %s -days 1095" % (keyfile, certfile))) self.useSSL = False self.authOK = True if self.useSSL: try: import ssl if PY3: import socketserver else: import SocketServer as socketserver import socket except ImportError: warning("Problem with the imports. Dropping SSL-support") self.useSSL = False if self.useSSL: self.logRequests = logRequests SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) class VerifyingRequestHandler(SimpleXMLRPCRequestHandler): ''' Request Handler that verifies username and security token to XML RPC server in HTTP URL sent by client. ''' # this is the method we must override def parse_request(self): # first, call the original implementation which returns # True if all OK so far if SimpleXMLRPCRequestHandler.parse_request(self): # next we authenticate if self.authenticate(self.headers): return True else: # if authentication fails, tell the client self.send_error(401, 'Authentication failed') return False def authenticate(self, headers): from base64 import b64decode # Confirm that Authorization header is set to Basic authHeader = headers.get('Authorization') if authHeader is None: return True (basic, _, encoded) = authHeader.partition(' ') assert basic == 'Basic', 'Only basic authentication supported' # Encoded portion of the header is a string # Need to convert to bytestring encodedByteString = encoded.encode() # Decode Base64 byte String to a decoded Byte String decodedBytes = b64decode(encodedByteString) # Convert from byte string to a regular String decodedString = decodedBytes.decode() # Get the username and password from the string (username, _, password) = decodedString.partition(':') # Check that username and password match internal global dictionary self.server.authOK = auth.checkAuthentication( username, password) return True # Override the normal socket methods with an SSL socket socketserver.BaseServer.__init__(self, addr, VerifyingRequestHandler) try: self.socket = ssl.wrap_socket( socket.socket(self.address_family, self.socket_type), server_side=True, keyfile=keyfile, certfile=certfile, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23, ) self.server_bind() self.server_activate() except socket.error as e: warning("Socket error", e) raise e else: SimpleXMLRPCServer.__init__(self, addr, logRequests=logRequests)
def __init__(self, ip, port, keyFile=DEFAULTKEYFILE, certFile=DEFAULTCERTFILE, logRequests=True): self.logRequests = logRequests class VerifyingRequestHandler(SimpleXMLRPCRequestHandler): def setup(myself): myself.connection = myself.request myself.rfile = socket.socket.makefile(myself.request, "rb", myself.rbufsize) myself.wfile = socket.socket.makefile(myself.request, "wb", myself.wbufsize) def address_string(myself): "getting 'FQDN' from host seems to stall on some ip addresses, so... just (quickly!) return raw host address" host, port = myself.client_address #return socket.getfqdn(host) return host def do_POST(myself): """Handles the HTTPS POST request. It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly. """ try: # get arguments data = myself.rfile.read( int(myself.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 = myself.server._marshaled_dispatch( data, getattr(myself, '_dispatch', None)) except Exception as info: # This should only happen if the module is buggy print("ERROR do_POST: ", info) print("Traceback follows:", traceback.print_exc()) # internal error, report as HTTP server error myself.send_response(500) myself.end_headers() else: # got a valid XML RPC response myself.send_response(200) myself.send_header("Content-type", "text/xml") myself.send_header("Content-length", str(len(response))) myself.end_headers() myself.wfile.write(response) # shut down the connection myself.wfile.flush() myself.connection.shutdown() # Modified here! def do_GET(myself): """Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. """ # Check that the path is legal if not myself.is_rpc_path_valid(): myself.report_404() return response = myself.server.generate_html_documentation() myself.send_response(200) myself.send_header("Content-type", "text/html") myself.send_header("Content-length", str(len(response))) myself.end_headers() myself.wfile.write(response) # shut down the connection myself.wfile.flush() myself.connection.shutdown() # Modified here! def report_404(myself): # Report a 404 error myself.send_response(404) response = 'No such page' myself.send_header("Content-type", "text/plain") myself.send_header("Content-length", str(len(response))) myself.end_headers() myself.wfile.write(response) # shut down the connection myself.wfile.flush() myself.connection.shutdown() # Modified here! def parse_request(myself): if SimpleXMLRPCRequestHandler.parse_request(myself): basic, foo, encoded = myself.headers.get( 'Authorization').partition(' ') username, foo, password = b64decode(encoded).decode( 'UTF-8').partition(':') if username == 'admin': return True else: myself.send_error(401, 'Authentication failed') return False SimpleXMLRPCDispatcher.__init__(self, False, None) BaseServer.__init__(self, (ip, port), VerifyingRequestHandler) # SSL socket stuff ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_privatekey_file(keyFile) ctx.use_certificate_file(certFile) self.socket = SSL.Connection( ctx, socket.socket(self.address_family, self.socket_type)) self.server_bind() self.server_activate() self.funcs = {} self.register_introspection_functions() self.register_instance(Services()) # requests count and condition, to allow for keyboard quit via CTL-C self.requests = 0 self.rCondition = Condition()
def __init__(self, addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True): """Overriding __init__ method of the SimpleXMLRPCServer The method is an exact copy, except the TCPServer __init__ call, which is rewritten using TLS """ self.logRequests = logRequests SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) """This is the modified part. Original code was: socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) which executed: def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): BaseServer.__init__(self, server_address, RequestHandlerClass) self.socket = socket.socket(self.address_family, self.socket_type) if bind_and_activate: self.server_bind() self.server_activate() """ class VerifyingRequestHandler(SimpleXMLRPCRequestHandler): ''' Request Handler that verifies username and password passed to XML RPC server in HTTP URL sent by client. ''' # this is the method we must override def parse_request(self): # first, call the original implementation which returns # True if all OK so far if SimpleXMLRPCRequestHandler.parse_request(self): # next we authenticate if self.authenticate(self.headers): return True else: # if authentication fails, tell the client self.send_error(401, 'Authentication failed') return False def authenticate(self, headers): from base64 import b64decode # Confirm that Authorization header is set to Basic (basic, _, encoded) = headers.get('Authorization').partition(' ') assert basic == 'Basic', 'Only basic authentication supported' # Encoded portion of the header is a string # Need to convert to bytestring encodedByteString = encoded.encode() # Decode Base64 byte String to a decoded Byte String decodedBytes = b64decode(encodedByteString) # Convert from byte string to a regular String decodedString = decodedBytes.decode() # Get the username and password from the string (username, _, password) = decodedString.partition(':') # Check that username and password match internal global dictionary if dissomniagLive.getIdentity().authServer(username, password): return True else: return False # Override the normal socket methods with an SSL socket socketserver.BaseServer.__init__(self, addr, VerifyingRequestHandler) self.socket = ssl.wrap_socket( socket.socket(self.address_family, self.socket_type), server_side=True, keyfile=dissomniagLive.config.sslPrivateKey, certfile=dissomniagLive.config.sslCertFile, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23, ) if bind_and_activate: self.server_bind() self.server_activate() """End of modified part""" # [Bug #1222790] If possible, set close-on-exec flag; if a # method spawns a subprocess, the subprocess shouldn't have # the listening socket open. if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'): flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD) flags |= fcntl.FD_CLOEXEC fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
def __init__(self, addr, requestHandler = SimpleXMLRPCRequestHandler, logRequests = True, allow_none = False, encoding = None, bind_and_activate = True): """Overriding __init__ method of the SimpleXMLRPCServer The method is an exact copy, except the TCPServer __init__ call, which is rewritten using TLS """ self.logRequests = logRequests SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) """This is the modified part. Original code was: socketserver.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) which executed: def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True): BaseServer.__init__(self, server_address, RequestHandlerClass) self.socket = socket.socket(self.address_family, self.socket_type) if bind_and_activate: self.server_bind() self.server_activate() """ class VerifyingRequestHandler(SimpleXMLRPCRequestHandler): ''' Request Handler that verifies username and password passed to XML RPC server in HTTP URL sent by client. ''' # this is the method we must override def parse_request(self): # first, call the original implementation which returns # True if all OK so far if SimpleXMLRPCRequestHandler.parse_request(self): # next we authenticate if self.authenticate(self.headers): return True else: # if authentication fails, tell the client self.send_error(401, 'Authentication failed') return False def authenticate(self, headers): from base64 import b64decode # Confirm that Authorization header is set to Basic (basic, _, encoded) = headers.get('Authorization').partition(' ') assert basic == 'Basic', 'Only basic authentication supported' # Encoded portion of the header is a string # Need to convert to bytestring encodedByteString = encoded.encode() # Decode Base64 byte String to a decoded Byte String decodedBytes = b64decode(encodedByteString) # Convert from byte string to a regular String decodedString = decodedBytes.decode() # Get the username and password from the string (username, _, password) = decodedString.partition(':') # Check that username and password match internal global dictionary if dissomniagLive.getIdentity().authServer(username, password): return True else: return False # Override the normal socket methods with an SSL socket socketserver.BaseServer.__init__(self, addr, VerifyingRequestHandler) self.socket = ssl.wrap_socket( socket.socket(self.address_family, self.socket_type), server_side = True, keyfile = dissomniagLive.config.sslPrivateKey, certfile = dissomniagLive.config.sslCertFile, cert_reqs = ssl.CERT_NONE, ssl_version = ssl.PROTOCOL_SSLv23, ) if bind_and_activate: self.server_bind() self.server_activate() """End of modified part""" # [Bug #1222790] If possible, set close-on-exec flag; if a # method spawns a subprocess, the subprocess shouldn't have # the listening socket open. if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'): flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD) flags |= fcntl.FD_CLOEXEC fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
def __init__(self, ip, port, keyFile=DEFAULTKEYFILE, certFile=DEFAULTCERTFILE, logRequests=True): self.logRequests = logRequests class VerifyingRequestHandler(SimpleXMLRPCRequestHandler): def setup(myself): myself.connection = myself.request myself.rfile = socket.socket.makefile(myself.request, "rb", myself.rbufsize) myself.wfile = socket.socket.makefile(myself.request, "wb", myself.wbufsize) def address_string(myself): "getting 'FQDN' from host seems to stall on some ip addresses, so... just (quickly!) return raw host address" host, port = myself.client_address #return socket.getfqdn(host) return host def do_POST(myself): """Handles the HTTPS POST request. It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly. """ try: # get arguments data = myself.rfile.read(int(myself.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 = myself.server._marshaled_dispatch(data, getattr(myself, '_dispatch', None)) except Exception as info: # This should only happen if the module is buggy print ("ERROR do_POST: ", info) print ("Traceback follows:", traceback.print_exc()) # internal error, report as HTTP server error myself.send_response(500) myself.end_headers() else: # got a valid XML RPC response myself.send_response(200) myself.send_header("Content-type", "text/xml") myself.send_header("Content-length", str(len(response))) myself.end_headers() myself.wfile.write(response) # shut down the connection myself.wfile.flush() myself.connection.shutdown() # Modified here! def do_GET(myself): """Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation. """ # Check that the path is legal if not myself.is_rpc_path_valid(): myself.report_404() return response = myself.server.generate_html_documentation() myself.send_response(200) myself.send_header("Content-type", "text/html") myself.send_header("Content-length", str(len(response))) myself.end_headers() myself.wfile.write(response) # shut down the connection myself.wfile.flush() myself.connection.shutdown() # Modified here! def report_404(myself): # Report a 404 error myself.send_response(404) response = 'No such page' myself.send_header("Content-type", "text/plain") myself.send_header("Content-length", str(len(response))) myself.end_headers() myself.wfile.write(response) # shut down the connection myself.wfile.flush() myself.connection.shutdown() # Modified here! def parse_request(myself): if SimpleXMLRPCRequestHandler.parse_request(myself): basic, foo, encoded = myself.headers.get('Authorization').partition(' ') username, foo, password = b64decode(encoded).decode('UTF-8').partition(':') if username == 'admin': return True else: myself.send_error(401, 'Authentication failed') return False SimpleXMLRPCDispatcher.__init__(self, False, None) BaseServer.__init__(self, (ip, port), VerifyingRequestHandler) # SSL socket stuff ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.use_privatekey_file(keyFile) ctx.use_certificate_file(certFile) self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type)) self.server_bind() self.server_activate() self.funcs = {} self.register_introspection_functions() self.register_instance(Services()) # requests count and condition, to allow for keyboard quit via CTL-C self.requests = 0 self.rCondition = Condition()
def __init__(self,addr,useSSL=False,logRequests=False, allow_none=False, encoding=None): """:param addr: the (server address,port)-tuple) :param logRequests: patched thru to the base class""" certfile=config().get("Network","personalSSLCertificate") keyfile=config().get("Network","privateSSLKey") self.useSSL=useSSL if self.useSSL and not path.exists(certfile): warning("No certficate file",certfile, "exists. Therefor no SSL-connection for the FoamServer possible\n", "To generate a private key:\n", (" openssl genrsa -out %s 2048" % keyfile), "\nThen generate the cerificate that is valid for 3 years with \n", (" openssl req -new -x509 -key %s -out %s -days 1095" % (keyfile,certfile))) self.useSSL=False self.authOK=True if self.useSSL: try: import ssl if PY3: import socketserver else: import SocketServer as socketserver import socket except ImportError: warning("Problem with the imports. Dropping SSL-support") self.useSSL=False if self.useSSL: self.logRequests = logRequests SimpleXMLRPCDispatcher.__init__(self, allow_none, encoding) class VerifyingRequestHandler(SimpleXMLRPCRequestHandler): ''' Request Handler that verifies username and security token to XML RPC server in HTTP URL sent by client. ''' # this is the method we must override def parse_request(self): # first, call the original implementation which returns # True if all OK so far if SimpleXMLRPCRequestHandler.parse_request(self): # next we authenticate if self.authenticate(self.headers): return True else: # if authentication fails, tell the client self.send_error(401, 'Authentication failed') return False def authenticate(self, headers): from base64 import b64decode # Confirm that Authorization header is set to Basic authHeader=headers.get('Authorization') if authHeader is None: return True (basic, _, encoded) = authHeader.partition(' ') assert basic == 'Basic', 'Only basic authentication supported' # Encoded portion of the header is a string # Need to convert to bytestring encodedByteString = encoded.encode() # Decode Base64 byte String to a decoded Byte String decodedBytes = b64decode(encodedByteString) # Convert from byte string to a regular String decodedString = decodedBytes.decode() # Get the username and password from the string (username, _, password) = decodedString.partition(':') # Check that username and password match internal global dictionary self.server.authOK=auth.checkAuthentication(username,password) return True # Override the normal socket methods with an SSL socket socketserver.BaseServer.__init__(self, addr, VerifyingRequestHandler) try: self.socket = ssl.wrap_socket( socket.socket(self.address_family, self.socket_type), server_side=True, keyfile=keyfile, certfile=certfile, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_SSLv23, ) self.server_bind() self.server_activate() except socket.error as e: warning("Socket error",e) raise e else: SimpleXMLRPCServer.__init__(self,addr,logRequests=logRequests)