コード例 #1
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()
コード例 #2
0
ファイル: bsdradclient.py プロジェクト: ikelos/bsdradius
    "--dont-gen-ids",
    action="store_false",
    dest="genIds",
    metavar="FILE",
    help=
    "don't generate random Acct-Session-Id and h323-conf-id, default: false",
    default=True)

(cliOptions, args) = cliParser.parse_args()
cmd = C_BOTH
if len(args) == 1 and args[0] in commands:
    cmd = commands[args[0]]

# parse dictionaries
print '--- Parsing dictionary files ---'
dict = dictionary.Dictionary(cliOptions.dictFile)
# start server itself
authport = cliOptions.authport
acctport = cliOptions.acctport
srv = Client(server=cliOptions.serverHost,
             secret=cliOptions.secret,
             dict=dict,
             authport=authport,
             acctport=acctport)

print "--- Reading config file ---"
attributes = {}
try:
    fh = open(cliOptions.attrFile)
except:
    pass
コード例 #3
0
                     action="store_true",
                     dest="noMixed",
                     help="Send mixed (acct and auth) messages",
                     default=False)
(cliOptions, args) = cliParser.parse_args()

# get options
testTime = cliOptions.testTime
testAuth = not cliOptions.noAuth
testAcct = not cliOptions.noAcct
testMixed = not cliOptions.noMixed
host = cliOptions.serverHost

# parse dictionaries
print '--- Parsing dictionary files ---'
dict = dictionary.Dictionary(main_config['PATHS']['dictionary_file'])
# start server itself
authport = main_config["SERVER"]["auth_port"]
acctport = main_config["SERVER"]["acct_port"]
srv = Client(server=host, secret="testing123", dict=dict)

### run tests ###
totalAuthRequests = 0
totalAcctRequests = 0
totalMixedRequests = 0

if testAuth:
    startTime = time.time()
    endTime = startTime + testTime
    while (time.time() < endTime):
        req = getAuthPacket(srv)