def run(self): """Listen to sockets and put received packets in raw data queue for later operations. Input: none Output: none """ # since this method is assigned to thread we have to catch all exceptions # by ourselves try: info ('--- Started Listen thread ---') # poll packets and put them onto rawpacket sync queue while self.threadMayRun: for (socknum, event) in self.server.pollobj.poll(1000): if event != select.POLLIN: logger.addUnrestrictedThread() error ("unexpected event!") logger.rmUnrestrictedThread() continue # receive packet (sock, socktype) = self.server.fdmap[socknum] (data, addr) = sock.recvfrom(MAXPACKETSZ) # process the raw packet if addr[0] in self.server.hosts and self.server.hosts[addr[0]].enableLogging: logger.addUnrestrictedThread() self.ProcessPacket(data, addr, sock, socktype) logger.rmUnrestrictedThread() except: logger.addUnrestrictedThread() misc.printException() error ('Error in listen thread') logger.rmUnrestrictedThread()
def execute(self, query, verbose=True): """Prepare and execute query Input: (string) query, (bool) be verbose and print some useful info Output: (bool) True if query execution was succssful, False if not """ ret = False # return value if (not query): return ret if (verbose): self.displayHandlerName() debug('db>> QUERY: ', query) # execute query self.lock.acquire() try: self._cursor.execute(query) except: error('db>>ERROR: Could not execute query: ', query) misc.printException() else: ret = True self.lock.release() return ret
def execAccountingModules(received): """Execute all accounting modules in [reconfigured order Input: (dict) data received from client; (dict) internal parameters; (dict) reply items; Output: (bool) True - success; False - failure """ moduleStatus = MODULE_OK for i in xrange(len(acctModules)): module = acctModules[i] if moduleStatus == MODULE_OK and module.accountingCapable: # prepare and print log message modstr = '### Accounting module "%s" ###' % module.name framestr = ('#' * len(modstr)) info('%s\n%s\n%s' % (framestr, modstr, framestr)) # execute accounting function. # consider that function failed only if it raised an exception try: dictItemsToLists(received) module.acct_funct(received) except: misc.printException() moduleStatus = MODULE_FAILED # exit cycle if any module failed else: break debug('--- Module %s results ---' % module.name) debug('Status: ', getModuleStatusName(moduleStatus)) # return module execution result return moduleStatus
def execute(self, query, verbose = True): """Prepare and execute query Input: (string) query, (bool) be verbose and print some useful info Output: (bool) True if query execution was succssful, False if not """ ret = False # return value if (not query): return ret if (verbose): self.displayHandlerName() debug ('db>> QUERY: ', query) # execute query self.lock.acquire() try: self._cursor.execute(query) except: error ('db>>ERROR: Could not execute query: ', query) misc.printException() else: ret = True self.lock.release() return ret
def importModule(moduleName, path = None): """Import module in current namespace. Input: (string) module name, (string) path to module dir Output: (module) imported module """ mod = None try: # import server module servMod = __import__('bsdradius.serverModules', globals(), locals(), [moduleName]) if hasattr(servMod, moduleName): mod = getattr(servMod, moduleName) except: misc.printException() raise ImportError, 'Can not load system module: %s' % moduleName # import user module if not mod: if path == None: raise ImportError, "Can load module %s. Module not found between system \ modules but user module search path not supplied" % moduleName try: fp, pathname, description = imp.find_module(moduleName, [path]) mod = imp.load_module(moduleName, fp, pathname, description) except: misc.printException() raise ImportError, "Can not load user module: %s" % moduleName return mod
def authenticateRadius(self, response, digestAttributes = []): """Check the response for this method with attributes received from NAS. Input: (string) check method, (string) uri, (list) unparsed Digest-Attributes Output: (tuple) result: (bool) status, True - OK, False - Failure (tuple) Digest-Attributes """ # set up and parse received data try: self._parseDigestAttributes(digestAttributes) except: printException() return False required = ['realm', 'method', 'uri'] for attr in required: if attr not in self.params: error('Can not find parameter "%s" in self.params' % key) return False # HACK: put attributes in correct places self.params['response'] = response self.realm = self.params['realm'] self.method = self.params.pop('method') self.uri = self.params.pop('uri') # perform authorization try: if self._authenticate(): return True else: return False except: printException() return False
def execAccountingModules(received): """Execute all accounting modules in [reconfigured order Input: (dict) data received from client; (dict) internal parameters; (dict) reply items; Output: (bool) True - success; False - failure """ moduleStatus = MODULE_OK for i in xrange(len(acctModules)): module = acctModules[i] if moduleStatus == MODULE_OK and module.accountingCapable: # prepare and print log message modstr = '### Accounting module "%s" ###' % module.name framestr = ('#' * len(modstr)) info ('%s\n%s\n%s' % (framestr, modstr, framestr)) # execute accounting function. # consider that function failed only if it raised an exception try: dictItemsToLists(received) module.acct_funct(received) except: misc.printException() moduleStatus = MODULE_FAILED # exit cycle if any module failed else: break debug ('--- Module %s results ---' % module.name) debug ('Status: ', getModuleStatusName(moduleStatus)) # return module execution result return moduleStatus
def run(self): """Listen to sockets and put received packets in raw data queue for later operations. Input: none Output: none """ # since this method is assigned to thread we have to catch all exceptions # by ourselves try: info('--- Started Listen thread ---') # poll packets and put them onto rawpacket sync queue while self.threadMayRun: for (socknum, event) in self.server.pollobj.poll(1000): if event != select.POLLIN: logger.addUnrestrictedThread() error("unexpected event!") logger.rmUnrestrictedThread() continue # receive packet (sock, socktype) = self.server.fdmap[socknum] (data, addr) = sock.recvfrom(MAXPACKETSZ) # process the raw packet if addr[0] in self.server.hosts and self.server.hosts[ addr[0]].enableLogging: logger.addUnrestrictedThread() self.ProcessPacket(data, addr, sock, socktype) logger.rmUnrestrictedThread() except: logger.addUnrestrictedThread() misc.printException() error('Error in listen thread') logger.rmUnrestrictedThread()
def importModule(moduleName, path=None): """Import module in current namespace. Input: (string) module name, (string) path to module dir Output: (module) imported module """ mod = None try: # import server module servMod = __import__('bsdradius.serverModules', globals(), locals(), [moduleName]) if hasattr(servMod, moduleName): mod = getattr(servMod, moduleName) except: misc.printException() raise ImportError, 'Can not load system module: %s' % moduleName # import user module if not mod: if path == None: raise ImportError, "Can load module %s. Module not found between system \ modules but user module search path not supplied" % moduleName try: fp, pathname, description = imp.find_module(moduleName, [path]) mod = imp.load_module(moduleName, fp, pathname, description) except: misc.printException() raise ImportError, "Can not load user module: %s" % moduleName return mod
def authenticateRadius(self, response, digestAttributes=[]): """Check the response for this method with attributes received from NAS. Input: (string) check method, (string) uri, (list) unparsed Digest-Attributes Output: (tuple) result: (bool) status, True - OK, False - Failure (tuple) Digest-Attributes """ # set up and parse received data try: self._parseDigestAttributes(digestAttributes) except: printException() return False required = ['realm', 'method', 'uri'] for attr in required: if attr not in self.params: error('Can not find parameter "%s" in self.params' % key) return False # HACK: put attributes in correct places self.params['response'] = response self.realm = self.params['realm'] self.method = self.params.pop('method') self.uri = self.params.pop('uri') # perform authorization try: if self._authenticate(): return True else: return False except: printException() return False
def run(self): """Thread that does the actual job of processing RADIUS packets""" # since this method is assigned to thread we have to catch all exceptions # by ourselves try: threadnum = self.getName() hosts = self.server.hosts packets = self.server.packets auth_timeout = main_config["AUTHORIZATION"]["packet_timeout"] info("--- started %s ---" % threadnum) while self.threadMayRun: # grab a RADIUS packet and process it pkt = packets.remove_packet(blocking=False) if not pkt: continue # check if this thread should be allowed for logging if pkt.source[0] in hosts and hosts[ pkt.source[0]].enableLogging: logger.addUnrestrictedThread() info('thread "%s" grabbed a packet for processing' % threadnum) if isinstance(pkt, packet.AuthPacket): # check if packet is too old if (time.time() - pkt.timestamp > auth_timeout): continue try: authResult = self.ProcessAuthPacket(pkt) except AuthFailure, err: error("auth failure: ", err) continue except: misc.printException() continue # create and send a reply packet address = pkt.source[0] client = hosts[address] if authResult[0]: # access accept code = packet.AccessAccept debug("Sending Authorization ACCEPT to %s (%s)" % (client.name, address)) else: # access reject code = packet.AccessReject debug("Sending Authorization REJECT to %s (%s)" % (client.name, address)) reply = pkt.CreateReply(**authResult[1]) reply.source = pkt.source reply.code = code debug(reply) pkt.fd.sendto(reply.ReplyPacket(), reply.source)
def run(self): """Thread that does the actual job of processing RADIUS packets""" # since this method is assigned to thread we have to catch all exceptions # by ourselves try: threadnum = self.getName() hosts = self.server.hosts packets = self.server.packets auth_timeout = main_config["AUTHORIZATION"]["packet_timeout"] info("--- started %s ---" % threadnum) while self.threadMayRun: # grab a RADIUS packet and process it pkt = packets.remove_packet(blocking = False) if not pkt: continue # check if this thread should be allowed for logging if pkt.source[0] in hosts and hosts[pkt.source[0]].enableLogging: logger.addUnrestrictedThread() info('thread "%s" grabbed a packet for processing' % threadnum) if isinstance(pkt, packet.AuthPacket): # check if packet is too old if (time.time() - pkt.timestamp > auth_timeout): continue try: authResult = self.ProcessAuthPacket(pkt) except AuthFailure, err: error ("auth failure: ", err) continue except: misc.printException() continue # create and send a reply packet address = pkt.source[0] client = hosts[address] if authResult[0]: # access accept code = packet.AccessAccept debug ("Sending Authorization ACCEPT to %s (%s)" % (client.name, address)) else: # access reject code = packet.AccessReject debug ("Sending Authorization REJECT to %s (%s)" % (client.name, address)) reply = pkt.CreateReply(**authResult[1]) reply.source = pkt.source reply.code = code debug (reply) pkt.fd.sendto(reply.ReplyPacket(), reply.source)
def execAuthenticationModules(received, check, reply): """Execute authentication module corresponding to auth-type Input: (dict) data received from client; (dict) internal parameters; (dict) reply items; Output: (bool) True - success; False - failure """ moduleName = '' # get auth type value authType = check.get('Auth-Type', None) if isinstance(authType, ListType): authType = authType[0] if not authType: authType = 'default' # find module module = authcModules.get(authType, None) if not module: error('Unsupported Auth-Type: %s' % authType) return MODULE_FAILED # prepare and print log message modstr = '### Authentication module "%s" ###' % module.name framestr = ('#' * len(modstr)) info('%s\n%s\n%s' % (framestr, modstr, framestr)) # execute function moduleStatus = MODULE_OK result = None try: dictItemsToLists(received) dictItemsToLists(check) dictItemsToLists(reply) result = module.authc_funct(received, check, reply) if result == 'ALLOWED': moduleStatus = MODULE_OK elif result == 'CHALLENGE': moduleStatus = MODULE_CHALLENGE elif result == 'INACTIVE': moduleStatus = MODULE_INACTIVE else: moduleStatus = MODULE_REJECTED except: misc.printException() moduleStatus = MODULE_FAILED debug('--- Module %s results ---' % module.name) debug('Status: ', getModuleStatusName(moduleStatus)) debug('Check: ', check) debug('Reply: ', reply) debug('Return value: ', result) return moduleStatus
def execShutdownModules(): """Execute all shutdown-capable modules Input: none Output: none """ for moduleName, module in loadedModules.iteritems(): if module.shutdownCapable: try: module.shutdown_funct() # catch all exceptions, report them to user and shutdown server except: misc.printException() misc.quit('Can not execute shutdown function in module "%s"' % moduleName, 1)
def execAuthenticationModules(received, check, reply): """Execute authentication module corresponding to auth-type Input: (dict) data received from client; (dict) internal parameters; (dict) reply items; Output: (bool) True - success; False - failure """ moduleName = '' # get auth type value authType = check.get('Auth-Type', None) if isinstance(authType, ListType): authType = authType[0] if not authType: authType = 'default' # find module module = authcModules.get(authType, None) if not module: error ('Unsupported Auth-Type: %s' % authType) return MODULE_FAILED # prepare and print log message modstr = '### Authentication module "%s" ###' % module.name framestr = ('#' * len(modstr)) info ('%s\n%s\n%s' % (framestr, modstr, framestr)) # execute function moduleStatus = MODULE_OK result = None try: dictItemsToLists(received) dictItemsToLists(check) dictItemsToLists(reply) result = module.authc_funct(received, check, reply) if result: moduleStatus = MODULE_OK else: moduleStatus = MODULE_REJECTED except: misc.printException() moduleStatus = MODULE_FAILED debug ('--- Module %s results ---' % module.name) debug ('Status: ', getModuleStatusName(moduleStatus)) debug ('Check: ', check) debug ('Reply: ', reply) debug ('Return value: ', result) return moduleStatus
def execShutdownModules(): """Execute all shutdown-capable modules Input: none Output: none """ for moduleName, module in loadedModules.iteritems(): if module.shutdownCapable: try: module.shutdown_funct() # catch all exceptions, report them to user and shutdown server except: misc.printException() misc.quit( 'Can not execute shutdown function in module "%s"' % moduleName, 1)
def execAuthorizationModules(received, check, reply): """Execute all authorization modules in preconfigured order Input: (dict) data received from client; (dict) internal parameters; (dict) reply items; Output: (bool) True - success; False - failure """ moduleStatus = MODULE_OK result = None # value returned by module # Execute all authorization capable modules until # one of them fails or rejects or until all modules # executed. for i in xrange(len(authzModules)): module = authzModules[i] if moduleStatus == MODULE_OK and module.authorizationCapable: # prepare and print log message modstr = '### Authorization module "%s" ###' % module.name framestr = ('#' * len(modstr)) info ('%s\n%s\n%s' % (framestr, modstr, framestr)) # execute module and detect it's status try: dictItemsToLists(received) dictItemsToLists(check) dictItemsToLists(reply) result = module.authz_funct(received, check, reply) if result: moduleStatus = MODULE_OK else: moduleStatus = MODULE_REJECTED except: misc.printException() moduleStatus = MODULE_FAILED debug ('--- Module %s results ---' % module.name) debug ('Status: ', getModuleStatusName(moduleStatus)) debug ('Check: ', check) debug ('Reply: ', reply) debug ('Return value: ', result) # exit cycle if any module failed else: break # return module execution result return moduleStatus
def execAuthorizationModules(received, check, reply): """Execute all authorization modules in preconfigured order Input: (dict) data received from client; (dict) internal parameters; (dict) reply items; Output: (bool) True - success; False - failure """ moduleStatus = MODULE_OK result = None # value returned by module # Execute all authorization capable modules until # one of them fails or rejects or until all modules # executed. for i in xrange(len(authzModules)): module = authzModules[i] if moduleStatus == MODULE_OK and module.authorizationCapable: # prepare and print log message modstr = '### Authorization module "%s" ###' % module.name framestr = ('#' * len(modstr)) info('%s\n%s\n%s' % (framestr, modstr, framestr)) # execute module and detect it's status try: dictItemsToLists(received) dictItemsToLists(check) dictItemsToLists(reply) result = module.authz_funct(received, check, reply) if result: moduleStatus = MODULE_OK else: moduleStatus = MODULE_REJECTED except: misc.printException() moduleStatus = MODULE_FAILED debug('--- Module %s results ---' % module.name) debug('Status: ', getModuleStatusName(moduleStatus)) debug('Check: ', check) debug('Reply: ', reply) debug('Return value: ', result) # exit cycle if any module failed else: break # return module execution result return moduleStatus
def execShutdownModules(): """Execute all shutdown-capable modules Input: none Output: none """ for moduleName, module in loadedModules.iteritems(): if module.shutdownCapable: # prepare and print log message modstr = '### Shutdown module "%s" ###' % module.name framestr = ('#' * len(modstr)) info ('%s\n%s\n%s' % (framestr, modstr, framestr)) try: module.shutdown_funct() # catch all exceptions, report them to user and shutdown server except: misc.printException() misc.quit('Can not execute shutdown function in module "%s"' % moduleName, 1)
def run(self): """Thread that does the actual job of processing RADIUS packets""" # since this method is assigned to thread we have to catch all exceptions # by ourselves try: threadnum = self.getName() hosts = self.server.hosts packets = self.server.packets auth_timeout = main_config["AUTHORIZATION"]["packet_timeout"] info("--- started %s ---" % threadnum) while self.threadMayRun: # grab a RADIUS packet and process it pkt = packets.remove_packet(blocking=False) if not pkt: continue # check if this thread should be allowed for logging if pkt.source[0] in hosts and hosts[ pkt.source[0]].enableLogging: logger.addUnrestrictedThread() info('thread "%s" grabbed a packet for processing' % threadnum) if isinstance(pkt, packet.AuthPacket): # check if packet is too old if (time.time() - pkt.timestamp > auth_timeout): # Dump timed out auth packet dumpPacket.dumpUnhandledAuthPacket(pkt) continue try: authResult = self.ProcessAuthPacket(pkt) except AuthFailure, err: error("auth failure: ", err) continue except: misc.printException() continue # create and send a reply packet self.sendAuthResponse(pkt, authResult)
def run(self): """Thread that does the actual job of processing RADIUS packets""" # since this method is assigned to thread we have to catch all exceptions # by ourselves try: threadnum = self.getName() hosts = self.server.hosts packets = self.server.packets auth_timeout = main_config["AUTHORIZATION"]["packet_timeout"] info("--- started %s ---" % threadnum) while self.threadMayRun: # grab a RADIUS packet and process it pkt = packets.remove_packet(blocking = False) if not pkt: continue # check if this thread should be allowed for logging if pkt.source[0] in hosts and hosts[pkt.source[0]].enableLogging: logger.addUnrestrictedThread() info('thread "%s" grabbed a packet for processing' % threadnum) if isinstance(pkt, packet.AuthPacket): # check if packet is too old if (time.time() - pkt.timestamp > auth_timeout): # Dump timed out auth packet dumpPacket.dumpUnhandledAuthPacket(pkt) continue try: authResult = self.ProcessAuthPacket(pkt) except AuthFailure, err: error ("auth failure: ", err) continue except: misc.printException() continue # create and send a reply packet self.sendAuthResponse(pkt, authResult)
def execProcedure(self, procName): """Execute stored procedure in DB. Input: (string) procedure name Output: (bool) True if procedure call was successful, False if not """ ret = False if (not procName): return ret self.displayHandlerName() # call procedure try: self._cursor.callproc(procName) except: error('db>>Error Could not execute stored procedure: ', procName) misc.printException() else: ret = True return ret
def execProcedure(self, procName): """Execute stored procedure in DB. Input: (string) procedure name Output: (bool) True if procedure call was successful, False if not """ ret = False if (not procName): return ret self.displayHandlerName() # call procedure try: self._cursor.callproc(procName) except: error ('db>>Error Could not execute stored procedure: ', procName) misc.printException() else: ret = True return ret
def disconnect(self): """Disconnect from database" Input: none Output: none """ self.lock.acquire() self.displayHandlerName() if (self._connected): try: self._cursor.close() except: error('db>> Error closing cursor to DB') try: self._conn.close() except: error('db>> Error closing connection to DB') misc.printException() self._connected = False else: error('db>> Already disconnected from DB') self.lock.release()
def disconnect(self): """Disconnect from database" Input: none Output: none """ self.displayHandlerName() if self._connected: try: self._cursor.close() except: error("db>> Error closing cursor to DB") try: self._conn.close() except: error("db>> Error closing connection to DB") misc.printException() self._errorStr = "" self._errorCode = 0 self._connected = False else: error("db>> Already disconnected from DB")
def testPrintException(self): try: raise Exception("Testing misc.printException") except: misc.printException()
continue except: misc.printException() continue # create and send a reply packet self.sendAuthResponse(pkt, authResult) elif isinstance(pkt, packet.AcctPacket): try: acctResult = self.ProcessAcctPacket(pkt) except AcctFailure, err: error("acct failure: ", err) continue except: misc.printException() continue # send accounting reply if processing packet was ok # send acct response to client only after processing the packet if acctResult is True and not main_config['SERVER'][ 'fast_accounting']: self.sendAcctResponse(pkt) else: error('Wrong packet received: ', pkt) info('%s\n\n' % ('=' * 62)) # remove this thread from non-restricted thread list logger.rmUnrestrictedThread()
def loadModules(): """Load all configured modules. Shutdown server if loading unsuccessful. Input: none Output: none """ global loadedModules global authzModules global acctModules global authcModules if not modulesConfig: return disabledModules = [] # list of modules disabled by user userModDir = main_config['PATHS']['user_module_dir'] # try to import modules for moduleName, tokens in modulesConfig.items(): # check if module is enabled if not modulesConfig.getbool(moduleName, 'enable'): disabledModules.append(moduleName) debug ('WARNING: Module "%s" disabled by user. Skipping.' % moduleName) continue debug ('Loading module: ', moduleName) mod = BsdRadiusModule(moduleName) try: # read custom config file if tokens['configfile']: mod.radParsedConfig = readModCustomConfig(tokens['configfile']) # set up additional path for python modules and packages # it must be done before actually importing modules if tokens['pythonpath']: for pth in tokens['pythonpath'].split(':'): if pth not in sys.path: sys.path.insert(0, pth) debug ('Added additional pythonpath: %s' % pth) # load python modules and functions for BSDRadius module if (tokens['startup_module']): mod.startup_module = importModule(tokens['startup_module'], userModDir) mod.startup_funct = loadFunction(mod.startup_module, tokens['startup_function']) mod.startupCapable = True mod.startup_module.radParsedConfig = mod.radParsedConfig if (tokens['authorization_module']): mod.authz_module = importModule(tokens['authorization_module'], userModDir) mod.authz_funct = loadFunction(mod.authz_module, tokens['authorization_function']) mod.authorizationCapable = True mod.authz_module.radParsedConfig = mod.radParsedConfig if (tokens['authentication_module']): mod.authc_module = importModule(tokens['authentication_module'], userModDir) mod.authc_funct = loadFunction(mod.authc_module, tokens['authentication_function']) mod.authenticationCapable = True mod.authc_module.radParsedConfig = mod.radParsedConfig if (tokens['accounting_module']): mod.acct_module = importModule(tokens['accounting_module'], userModDir) mod.acct_funct = loadFunction(mod.acct_module, tokens['accounting_function']) mod.accountingCapable = True mod.acct_module.radParsedConfig = mod.radParsedConfig if (tokens['shutdown_module']): mod.shutdown_module = importModule(tokens['shutdown_module'], userModDir) mod.shutdown_funct = loadFunction(mod.shutdown_module, tokens['shutdown_function']) mod.shutdownCapable = True mod.shutdown_module.radParsedConfig = mod.radParsedConfig # catch all exceptions, report them to user and shutdown server except: misc.printException() misc.quit('Can not load BSD Radius server modules', 1) else: loadedModules[moduleName] = mod debug (mod) info ('Setting order of authorization modules') # set module executing order in authorization and accounting phases authModuleOrder = main_config['AUTHORIZATION']['modules'].split(',') for moduleName in authModuleOrder: moduleName = moduleName.strip() if moduleName in disabledModules: continue if moduleName not in loadedModules: misc.quit('Module "%s" not loaded' % moduleName, 1) # make list of authorization module references if not loadedModules[moduleName].authorizationCapable: misc.quit('Module "%s" not authorization capable' % moduleName, 1) authzModules.append(loadedModules[moduleName]) info ('Mapping auth types with modules') authTypes = main_config['AUTH_TYPES'] for authType, moduleName in authTypes.items(): authType = authType.strip() moduleName = moduleName.strip() if moduleName in disabledModules: continue if moduleName not in loadedModules: misc.quit('Module "%s" not loaded' % moduleName, 1) if not loadedModules[moduleName].authenticationCapable: misc.quit('Module "%s" not authentication capable' % moduleName, 1) authcModules[authType] = loadedModules[moduleName] info ('Setting order of accounting modules') acctModuleOrder = main_config['ACCOUNTING']['modules'].split(',') for moduleName in acctModuleOrder: moduleName = moduleName.strip() if moduleName in disabledModules: continue if moduleName not in loadedModules: misc.quit('Module "%s" not loaded' % moduleName, 1) if not loadedModules[moduleName].accountingCapable: misc.quit('Module "%s" not accounting capable' % moduleName, 1) acctModules.append(loadedModules[moduleName])
debug ("Sending Authorization REJECT to %s (%s)" % (client.name, address)) reply = pkt.CreateReply(**authResult[1]) reply.source = pkt.source reply.code = code debug (reply) pkt.fd.sendto(reply.ReplyPacket(), reply.source) elif isinstance(pkt, packet.AcctPacket): try: self.ProcessAcctPacket(pkt) except AcctFailure, err: error ("acct failure: ", err) continue except: misc.printException() continue else: error('Wrong packet received: ', pkt) info ('%s\n\n' % ('=' * 62)) # remove this thread from non-restricted thread list logger.rmUnrestrictedThread() except: logger.addUnrestrictedThread() misc.printException() error ('Error in working thread') logger.rmUnrestrictedThread()
def loadModules(): """Load all configured modules. Shutdown server if loading unsuccessful. Input: none Output: none """ global loadedModules global authzModules global acctModules global authcModules if not modulesConfig: return userModDir = main_config['PATHS']['user_module_dir'] # try to import modules for moduleName, tokens in modulesConfig.items(): debug ('Loading module: ', moduleName) mod = BsdRadiusModule(moduleName) try: if (tokens['startup_module']): mod.startup_module = importModule(tokens['startup_module'], userModDir) mod.startup_funct = loadFunction(mod.startup_module, tokens['startup_function']) mod.startupCapable = True if (tokens['authorization_module']): mod.authz_module = importModule(tokens['authorization_module'], userModDir) mod.authz_funct = loadFunction(mod.authz_module, tokens['authorization_function']) mod.authorizationCapable = True if (tokens['authentication_module']): mod.authc_module = importModule(tokens['authentication_module'], userModDir) mod.authc_funct = loadFunction(mod.authc_module, tokens['authentication_function']) mod.authenticationCapable = True if (tokens['accounting_module']): mod.acct_module = importModule(tokens['accounting_module'], userModDir) mod.acct_funct = loadFunction(mod.acct_module, tokens['accounting_function']) mod.accountingCapable = True if (tokens['shutdown_module']): mod.shutdown_module = importModule(tokens['shutdown_module'], userModDir) mod.shutdown_funct = loadFunction(mod.shutdown_module, tokens['shutdown_function']) mod.shutdownCapable = True # catch all exceptions, report them to user and shutdown server except: misc.printException() misc.quit('Can not load BSD Radius server modules', 1) else: loadedModules[moduleName] = mod debug (mod) info ('Setting order of authorization modules') # set module executing order in authorization and accounting phases authModuleOrder = main_config['AUTHORIZATION']['modules'].split(',') for moduleName in authModuleOrder: moduleName = moduleName.strip() if moduleName not in loadedModules: misc.quit('Module "%s" not loaded' % moduleName, 1) # make list of authorization module references if not loadedModules[moduleName].authorizationCapable: misc.quit('Module "%s" not authorization capable' % moduleName, 1) authzModules.append(loadedModules[moduleName]) info ('Mapping auth types with modules') authTypes = main_config['AUTH_TYPES'] for authType, moduleName in authTypes.items(): authType = authType.strip() moduleName = moduleName.strip() if moduleName not in loadedModules: misc.quit('Module "%s" not loaded' % moduleName, 1) if not loadedModules[moduleName].authenticationCapable: misc.quit('Module "%s" not authentication capable' % moduleName, 1) authcModules[authType] = loadedModules[moduleName] info ('Setting order of accounting modules') acctModuleOrder = main_config['ACCOUNTING']['modules'].split(',') for moduleName in acctModuleOrder: moduleName = moduleName.strip() if moduleName not in loadedModules: misc.quit('Module "%s" not loaded' % moduleName, 1) if not loadedModules[moduleName].accountingCapable: misc.quit('Module "%s" not accounting capable' % moduleName, 1) acctModules.append(loadedModules[moduleName])
def loadModules(): """Load all configured modules. Shutdown server if loading unsuccessful. Input: none Output: none """ global loadedModules global authzModules global acctModules global authcModules if not modulesConfig: return disabledModules = [] # list of modules disabled by user userModDir = main_config['PATHS']['user_module_dir'] # try to import modules for moduleName, tokens in modulesConfig.items(): # check if module is enabled if not modulesConfig.getbool(moduleName, 'enable'): disabledModules.append(moduleName) debug('WARNING: Module "%s" disabled by user. Skipping.' % moduleName) continue debug('Loading module: ', moduleName) mod = BsdRadiusModule(moduleName) try: # read custom config file if tokens['configfile']: mod.radParsedConfig = readModCustomConfig(tokens['configfile']) # load python modules and functions for BSDRadius module if (tokens['startup_module']): mod.startup_module = importModule(tokens['startup_module'], userModDir) mod.startup_funct = loadFunction(mod.startup_module, tokens['startup_function']) mod.startupCapable = True mod.startup_module.radParsedConfig = mod.radParsedConfig if (tokens['authorization_module']): mod.authz_module = importModule(tokens['authorization_module'], userModDir) mod.authz_funct = loadFunction( mod.authz_module, tokens['authorization_function']) mod.authorizationCapable = True mod.authz_module.radParsedConfig = mod.radParsedConfig if (tokens['authentication_module']): mod.authc_module = importModule( tokens['authentication_module'], userModDir) mod.authc_funct = loadFunction( mod.authc_module, tokens['authentication_function']) mod.authenticationCapable = True mod.authc_module.radParsedConfig = mod.radParsedConfig if (tokens['accounting_module']): mod.acct_module = importModule(tokens['accounting_module'], userModDir) mod.acct_funct = loadFunction(mod.acct_module, tokens['accounting_function']) mod.accountingCapable = True mod.acct_module.radParsedConfig = mod.radParsedConfig if (tokens['shutdown_module']): mod.shutdown_module = importModule(tokens['shutdown_module'], userModDir) mod.shutdown_funct = loadFunction(mod.shutdown_module, tokens['shutdown_function']) mod.shutdownCapable = True mod.shutdown_module.radParsedConfig = mod.radParsedConfig # catch all exceptions, report them to user and shutdown server except: misc.printException() misc.quit('Can not load BSD Radius server modules', 1) else: loadedModules[moduleName] = mod debug(mod) info('Setting order of authorization modules') # set module executing order in authorization and accounting phases authModuleOrder = main_config['AUTHORIZATION']['modules'].split(',') for moduleName in authModuleOrder: moduleName = moduleName.strip() if moduleName in disabledModules: continue if moduleName not in loadedModules: misc.quit('Module "%s" not loaded' % moduleName, 1) # make list of authorization module references if not loadedModules[moduleName].authorizationCapable: misc.quit('Module "%s" not authorization capable' % moduleName, 1) authzModules.append(loadedModules[moduleName]) info('Mapping auth types with modules') authTypes = main_config['AUTH_TYPES'] for authType, moduleName in authTypes.items(): authType = authType.strip() moduleName = moduleName.strip() if moduleName in disabledModules: continue if moduleName not in loadedModules: misc.quit('Module "%s" not loaded' % moduleName, 1) if not loadedModules[moduleName].authenticationCapable: misc.quit('Module "%s" not authentication capable' % moduleName, 1) authcModules[authType] = loadedModules[moduleName] info('Setting order of accounting modules') acctModuleOrder = main_config['ACCOUNTING']['modules'].split(',') for moduleName in acctModuleOrder: moduleName = moduleName.strip() if moduleName in disabledModules: continue if moduleName not in loadedModules: misc.quit('Module "%s" not loaded' % moduleName, 1) if not loadedModules[moduleName].accountingCapable: misc.quit('Module "%s" not accounting capable' % moduleName, 1) acctModules.append(loadedModules[moduleName])