コード例 #1
0
def dumpPacket(pkt, filePath, pktType=None):
    """Dump packet into file
		Input: (packet or dict) packet, must contain __str__ method
			(string) path to file
		Output: none
	"""
    # check directory
    dirPath = dirname(filePath)
    if not misc.checkDir(dirPath):
        error('Directory %s not available for logging' % dirPath)
        return

    # dump packet to file
    try:
        debug('Dumping packet to file:\n', filePath)
        file = open(filePath, 'a+')
        if pktType == PACKET_TYPE_ACCT:
            pktStr = misc.acctPacketToStr(pkt)
        elif pktType == PACKET_TYPE_AUTH:
            pktStr = misc.authPacketToStr(pkt)
        else:
            pktStr = misc.packetToStr(pkt)
        file.write(pktStr)
        file.close()
    except:
        error('Can not dump packet to file "%s"' % filePath)
        misc.printExceptionError()
コード例 #2
0
ファイル: dumpPacket.py プロジェクト: BackupGGCode/bsdradius
def dumpPacket(pkt, filePath, pktType = None):
	"""Dump packet into file
		Input: (packet or dict) packet, must contain __str__ method
			(string) path to file
		Output: none
	"""
	# check directory
	dirPath = dirname(filePath)
	if not misc.checkDir(dirPath):
		error('Directory %s not available for logging' % dirPath)
		return
		
	# dump packet to file
	try:
		debug ('Dumping packet to file:\n', filePath)
		file = open(filePath, 'a+')
		if pktType == PACKET_TYPE_ACCT:
			pktStr = misc.acctPacketToStr(pkt)
		elif pktType == PACKET_TYPE_AUTH:
			pktStr = misc.authPacketToStr(pkt)
		else:
			pktStr = misc.packetToStr(pkt)
		file.write(pktStr)
		file.close()
	except:
		error('Can not dump packet to file "%s"' % filePath)
		misc.printExceptionError()
コード例 #3
0
    def __init__(self,
                 code=0,
                 id=None,
                 secret="",
                 authenticator=None,
                 **attributes):
        """Constructor

		@param dict:   RADIUS dictionary
		@type dict:    pyrad.dictionary.Dictionary class
		@param secret: secret needed to communicate with a RADIUS server
		@type secret:  string
		@param id:     packet identifaction number
		@type id:      integer (8 bits)
		@param code:   packet type code
		@type code:    integer (8bits)
		@param packet: raw packet to decode
		@type packet:  string
		"""
        UserDict.UserDict.__init__(self)
        self.code = code
        self.source = None
        if id != None:
            self.id = id
        else:
            self.id = CreateID()
        self.secret = secret
        self.authenticator = authenticator

        if attributes.has_key("dict"):
            self.dict = attributes["dict"]

        if attributes.has_key("packet"):
            self.DecodePacket(attributes["packet"])

        for (key, value) in attributes.items():
            if key in ["dict", "fd", "packet"]:
                continue

            key = key.replace("_", "-")
            try:
                if isinstance(value, ListType):
                    for listItemValue in value:
                        self.AddAttribute(key, listItemValue)
                else:
                    self.AddAttribute(key, value)
            # silently discard wrong attributes
            except KeyError:
                error(
                    'Item "%s" not found in dictionary. I\'m discarding it.' %
                    key)
                continue
            except:
                error('Can not add item "%s". I\'m discarding it.' % key)
                misc.printExceptionError(prefix='  ')
                continue
コード例 #4
0
ファイル: packet.py プロジェクト: BackupGGCode/bsdradius
	def __init__(self, code=0, id=None, secret="", authenticator=None, **attributes):
		"""Constructor

		@param dict:   RADIUS dictionary
		@type dict:    pyrad.dictionary.Dictionary class
		@param secret: secret needed to communicate with a RADIUS server
		@type secret:  string
		@param id:     packet identifaction number
		@type id:      integer (8 bits)
		@param code:   packet type code
		@type code:    integer (8bits)
		@param packet: raw packet to decode
		@type packet:  string
		"""
		UserDict.UserDict.__init__(self)
		self.code=code
		self.source = None
		if id != None:
			self.id=id
		else:
			self.id=CreateID()
		self.secret=secret
		self.authenticator=authenticator

		if attributes.has_key("dict"):
			self.dict=attributes["dict"]

		if attributes.has_key("packet"):
			self.DecodePacket(attributes["packet"])

		for (key,value) in attributes.items():
			if key in [ "dict", "fd", "packet"]:
				continue

			key=key.replace("_", "-")
			try:
				if isinstance(value, ListType):
					for listItemValue in value:
						self.AddAttribute(key, listItemValue)
				else:
					self.AddAttribute(key, value)
			# silently discard wrong attributes
			except KeyError:
				error ('Item "%s" not found in dictionary. I\'m discarding it.' % key)
				continue
			except:
				error ('Can not add item "%s". I\'m discarding it.' % key)
				misc.printExceptionError(prefix = '  ')
				continue
コード例 #5
0
ファイル: bsdradiusd.py プロジェクト: ikelos/bsdradius
def main():
    """Prepare and execute server
	"""
    # make sure that keyboard interrupt stops our server
    # and clean up before exiting
    signal.signal(signal.SIGINT, misc.killSignalHandler)
    signal.signal(signal.SIGTERM, misc.killSignalHandler)

    #	try:
    #		import psyco
    #		psyco.full()
    #		print ('--- Running psyco ---')
    #	except:
    #		print('Using psyco failed')

    # read main configuration data
    Config.readMainConf()
    main_config = Config.main_config
    debug(main_config)

    # fork and run as daemon
    if mayRunInBackground and not main_config['SERVER']['foreground']:
        info('Daemonizing...')
        childProcId = os.fork()
        if childProcId != 0:
            sys.exit(0)

    # store pid in file
    user = main_config['SERVER']['user']
    group = main_config['SERVER']['group']
    runDirPath = main_config['PATHS']['run_dir']
    if not misc.checkDir(runDirPath, user=user, group=group):
        misc.quit("Checking %s directory failed" % runDirPath, 1)
    misc.makePidfile()

    # check and/or create log directory
    logDirPath = main_config['PATHS']['log_dir']
    if not misc.checkDir(logDirPath, user=user, group=group):
        misc.quit("Checking %s directory failed" % logDirPath, 1)

    # open log file
    logFilePath = main_config['PATHS']['server_log_file']
    if logFilePath and main_config['SERVER']['log_to_file']:
        info('--- Opening log file ---')
        # open file
        try:
            logger.logFile = open(logFilePath, 'a+')


#			misc.setOwner(logFilePath, user, group)
        except:
            misc.printExceptionError()
            quit('Can not open logfile')

    # parse dictionaries
    info('--- Parsing dictionary files ---')
    radiusDict = dictionary.Dictionary(main_config['PATHS']['dictionary_file'])

    # connect to database
    if main_config['DATABASE']['enable']:
        info('--- Connecting to database ---')
        # set driver name
        if main_config['DATABASE']['type'] == 'postgresql':
            DatabaseConnection.dbadapterName = 'psycopg'
        else:
            DatabaseConnection.dbadapterName = 'MySQLdb'

        # connect to host and store connection globally available
        try:
            dbh1 = DatabaseConnection.DatabaseConnection.getHandler(
                'bsdradius dbh1')
            dbh1.connect(host=main_config['DATABASE']['host'],
                         user=main_config['DATABASE']['user'],
                         password=main_config['DATABASE']['pass'],
                         dbname=main_config['DATABASE']['name'])
        except:
            misc.printExceptionError()
            misc.quit(
                "Error connecting to database. Check DATABASE section in config file.",
                1)

    # start server itself
    authport = main_config["SERVER"]["auth_port"]
    acctport = main_config["SERVER"]["acct_port"]
    srv = BsdRadiusServer.BsdRadiusServer(dict = radiusDict, authport = authport, \
     acctport = acctport)

    # add valid server client hosts from file
    if main_config['PATHS']['clients_file']:
        info('--- Reading server clients from file ---')
        clientsConf = Config.Config()
        clientsConf.readFiles([main_config['PATHS']['clients_file']])
        srv.addClientHosts(clientsConf)
    # add valid server client hosts from DB
    # overwrite hosts from file
    if main_config['DATABASE']['enable']:
        info('--- Reading server clients from DB ---')
        confDb = ConfigDb(dbh1)
        confDb.ReadClients()
        srv.addClientHosts(confDb['CLIENTS'])

    debug('--- Clients: ---')
    for addr in srv.hosts:
        debug('%s: %s' % (addr, srv.hosts[addr].name))

    # bind to IP address (default: all)
    srv.BindToAddress(main_config['SERVER']['home'])

    # switch to nonprivileged user
    misc.switchUid(user, group)

    # Load BSD Radius server modules.
    # Do it just before starting the server to provide modules with maximum info.
    info('--- Reading module configuration ---')
    modules.readConfig([
        main_config['PATHS']['modules_file'],
        main_config['PATHS']['user_modules_file']
    ])
    debug('Module configuration:')
    debug(modules.modulesConfig)
    info('--- Loading modules ---')
    modules.loadModules()
    info('--- Executing startup modules ---')
    modules.execStartupModules()

    # run server
    info("--- Starting server ---")
    srv.Run()

    # do some maintenace tasks
    everythingOk = True
    dbEnable = main_config['DATABASE']['enable']
    dbRefreshCounter = 0
    dbRefreshRate = main_config['DATABASE']['refresh_rate']
    while everythingOk:
        time.sleep(1)

        # refresh radius server clients from DB
        if dbEnable:
            dbRefreshCounter += 1
            if dbRefreshCounter >= dbRefreshRate:
                #info ('Refreshing config from DB')
                #debug ('I was waiting for it %s seconds :)' % dbRefreshCounter)
                dbRefreshCounter = 0
                confDb.ReadClients()
                srv.addClientHosts(confDb['CLIENTS'])
                # print only changed clients

    # exit program
    misc.quit()
コード例 #6
0
ファイル: bsdradiusd.py プロジェクト: BackupGGCode/bsdradius
def main():
	"""Prepare and execute server
	"""
	# make sure that keyboard interrupt stops our server
	# and clean up before exiting
	signal.signal(signal.SIGINT, misc.killSignalHandler)
	signal.signal(signal.SIGTERM, misc.killSignalHandler)
	
#	try:
#		import psyco
#		psyco.full()
#		print ('--- Running psyco ---')
#	except:
#		print('Using psyco failed')
	
	# read main configuration data
	Config.readMainConf()
	main_config = Config.main_config
	debug (main_config)
	
	# fork and run as daemon
	if mayRunInBackground and not main_config['SERVER']['foreground']:
		info ('Daemonizing...')
		childProcId = os.fork()
		if childProcId != 0:
			sys.exit(0)
	
	# store pid in file
	user = main_config['SERVER']['user']
	group = main_config['SERVER']['group']
	runDirPath = main_config['PATHS']['run_dir']
	if not misc.checkDir(runDirPath, user = user, group = group):
		misc.quit("Checking %s directory failed" % runDirPath, 1)
	misc.makePidfile()
	
	# check and/or create log directory
	logDirPath = main_config['PATHS']['log_dir']
	if not misc.checkDir(logDirPath, user = user, group = group):
		misc.quit("Checking %s directory failed" % logDirPath, 1)
	
	# open log file
	logFilePath = main_config['PATHS']['server_log_file']
	if logFilePath and main_config['SERVER']['log_to_file']:
		info ('--- Opening log file ---')
		# open file
		try:
			logger.logFile = open(logFilePath, 'a+')
#			misc.setOwner(logFilePath, user, group)
		except:
			misc.printExceptionError()
			quit('Can not open logfile')
	
	# parse dictionaries
	info ('--- Parsing dictionary files ---')
	radiusDict = dictionary.Dictionary(main_config['PATHS']['dictionary_file'])
	
	# connect to database
	if main_config['DATABASE']['enable']:
		info ('--- Connecting to database ---')
		# set driver name
		if main_config['DATABASE']['type'] == 'postgresql':
			DatabaseConnection.dbadapterName = 'psycopg'
		else:
			DatabaseConnection.dbadapterName = 'MySQLdb'
			
		# connect to host and store connection globally available
		try:
			dbh1 = DatabaseConnection.DatabaseConnection.getHandler('bsdradius dbh1')
			dbh1.connect (
				host = main_config['DATABASE']['host'],
				user = main_config['DATABASE']['user'],
				password = main_config['DATABASE']['pass'],
				dbname = main_config['DATABASE']['name'] )
		except:
			misc.printExceptionError()
			misc.quit("Error connecting to database. Check DATABASE section in config file.", 1)
	
	# start server itself
	authport = main_config["SERVER"]["auth_port"]
	acctport = main_config["SERVER"]["acct_port"]
	srv = BsdRadiusServer.BsdRadiusServer(dict = radiusDict, authport = authport, \
		acctport = acctport)
	
	# add valid server client hosts from file
	if main_config['PATHS']['clients_file']:
		info ('--- Reading server clients from file ---')
		clientsConf = Config.Config()
		clientsConf.readFiles([main_config['PATHS']['clients_file']])
		srv.addClientHosts(clientsConf)
	# add valid server client hosts from DB
	# overwrite hosts from file
	if main_config['DATABASE']['enable']:
		info ('--- Reading server clients from DB ---')
		confDb = ConfigDb(dbh1)
		confDb.ReadClients()
		srv.addClientHosts(confDb['CLIENTS'])
				
	debug ('--- Clients: ---')
	for addr in srv.hosts:
		debug ('%s: %s' % (addr, srv.hosts[addr].name))
		
	# bind to IP address (default: all)
	srv.BindToAddress(main_config['SERVER']['home'])
	
	# switch to nonprivileged user
	misc.switchUid(user, group)
	
	# Load BSD Radius server modules.
	# Do it just before starting the server to provide modules with maximum info.
	info ('--- Reading module configuration ---')
	modules.readConfig([main_config['PATHS']['modules_file'], main_config['PATHS']['user_modules_file']])
	debug ('Module configuration:')
	debug (modules.modulesConfig)
	info ('--- Loading modules ---')
	modules.loadModules()
	info ('--- Executing startup modules ---')
	modules.execStartupModules()
	
	# run server
	info ("--- Starting server ---")
	srv.Run()
	
	# do some maintenace tasks
	everythingOk = True
	dbEnable = main_config['DATABASE']['enable']
	dbRefreshCounter = 0
	dbRefreshRate = main_config['DATABASE']['refresh_rate']
	while everythingOk:
		time.sleep(1)
		
		# refresh radius server clients from DB
		if dbEnable:
			dbRefreshCounter += 1
			if dbRefreshCounter >= dbRefreshRate:
				#info ('Refreshing config from DB')
				#debug ('I was waiting for it %s seconds :)' % dbRefreshCounter)
				dbRefreshCounter = 0
				confDb.ReadClients()
				srv.addClientHosts(confDb['CLIENTS'])
				# print only changed clients
	
	
	# exit program
	misc.quit()
コード例 #7
0
ファイル: test_misc.py プロジェクト: ikelos/bsdradius
	def testPrintExceptionError(self):
		try:
			raise Exception("Testing misc.printExceptionError")
		except:
			misc.printExceptionError()
コード例 #8
0
ファイル: test_misc.py プロジェクト: BackupGGCode/bsdradius
	def testPrintExceptionError(self):
		try:
			raise Exception("Testing misc.printExceptionError")
		except:
			misc.printExceptionError()