def warp(self, result): if result: radius = storage.Storage() radius.ip_addr = result['ip_addr'] radius.secret = result['secret'] radius.auth_port = result['auth_port'] radius.acct_port = result['acct_port'] radius.dict = dictionary.Dictionary( os.path.join(os.path.dirname(toughcrt.__file__), "dictionarys/dictionary")) radius.send_auth = functools.partial(client.send_auth, str(radius.secret), radius.dict, radius.ip_addr, authport=int( radius.auth_port), debug=True) radius.send_acct = functools.partial(client.send_acct, str(radius.secret), radius.dict, radius.ip_addr, acctport=int( radius.acct_port), debug=True) return radius
def __init__(self, config, dbengine, radcache=None): self.config = config self.dict = dictionary.Dictionary( os.path.join(os.path.dirname(toughradius.__file__), 'dictionarys/dictionary')) self.db_engine = dbengine or get_engine(config) self.mcache = radcache self.pusher = ZmqPushConnection( ZmqFactory(), ZmqEndpoint('connect', 'ipc:///tmp/radiusd-acct-result')) self.stat_pusher = ZmqPushConnection( ZmqFactory(), ZmqEndpoint('connect', 'ipc:///tmp/radiusd-stat-task')) self.puller = ZmqPullConnection( ZmqFactory(), ZmqEndpoint('connect', 'ipc:///tmp/radiusd-acct-message')) self.puller.onPull = self.process logger.info("init acct worker pusher : %s " % (self.pusher)) logger.info("init acct worker puller : %s " % (self.puller)) logger.info("init auth stat pusher : %s " % (self.stat_pusher)) self.acct_class = { STATUS_TYPE_START: RadiusAcctStart, STATUS_TYPE_STOP: RadiusAcctStop, STATUS_TYPE_UPDATE: RadiusAcctUpdate, STATUS_TYPE_ACCT_ON: RadiusAcctOnoff, STATUS_TYPE_ACCT_OFF: RadiusAcctOnoff }
def acct(host, port, acct_type, username, secret, session_id, nas_ip, user_ip): """ radius acct testing """ _dict = dictionary.Dictionary( os.path.join(os.path.dirname(client.__file__), "dictionary/dictionary")) req = {'User-Name': username} req['Acct-Status-Type'] = ACCT_TYPE_MAP[acct_type] req['Acct-Session-Id'] = session_id req["Acct-Output-Octets"] = 4096 req["Acct-Input-Octets"] = 1024 req['Acct-Session-Time'] = int(time.time()) % 1999 req["NAS-IP-Address"] = nas_ip req["NAS-Port-Id"] = '3/0/1:0.0' req["NAS-Port"] = 0 req["Service-Type"] = "Login-User" req["NAS-Identifier"] = "trtest" req["Called-Station-Id"] = random_mac() req["Calling-Station-Id"] = random_mac() req["Framed-IP-Address"] = user_ip print "radius acct: ", repr(req) def onresp(r): print message.format_packet_str(r) reactor.stop() sendacct = lambda: client.send_acct( str(secret), _dict, host, acctport=port, debug=True, **req ).addCallback(onresp) reactor.callLater(0.01, sendacct) reactor.run()
def auth(host, port, username, password, secret, encrypt_type, nas_ip, user_ip): """ radius auth testing """ _dict = dictionary.Dictionary( os.path.join(os.path.dirname(client.__file__), "dictionary/dictionary")) req = {'User-Name': username} if encrypt_type == 'pap': req['User-Password'] = password else: req['CHAP-Challenge'] = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' req['CHAP-Password-Plaintext'] = password req["NAS-IP-Address"] = nas_ip req["NAS-Port-Id"] = '3/0/1:0.0' req["NAS-Port"] = 0 req["Service-Type"] = "Login-User" req["NAS-Identifier"] = "trtest" req["Called-Station-Id"] = random_mac() req["Calling-Station-Id"] = random_mac() req["Framed-IP-Address"] = user_ip print "radius auth: ", repr(req) def onresp(r): print message.format_packet_str(r) reactor.stop() sendauth = lambda: client.send_auth( str(secret), _dict, host, authport=port, debug=True, **req ).addCallback(onresp) reactor.callLater(0.01, sendauth) reactor.run()
def __init__(self, config, dbengine): self.config = config self.dict = dictionary.Dictionary( os.path.join(os.path.dirname(toughradius.__file__), 'dictionarys/dictionary')) self.db_engine = dbengine or get_engine(config) self.aes = utils.AESCipher(key=self.config.system.secret) self.mcache = mcache.Mcache()
def post(self): username = self.get_argument('username',None) nas_addr = self.get_argument('nas_addr',None) session_id = self.get_argument('session_id',None) nas = self.db.query(models.TrBas).filter_by(ip_addr=nas_addr).first() if nas_addr and not nas: self.db.query(models.TrOnline).filter_by( nas_addr=nas_addr, acct_session_id=session_id ).delete() self.db.commit() self.render_json(code=1,msg=u"nasaddr not exists, online clear!") return if nas_addr and not session_id: onlines = self.db.query(models.TrOnline).filter_by(nas_addr=nas_addr) for online in onlines: radius_acct_stop.RadiusAcctStop(self.application.db_engine, self.application.mcache, self.application.aes, self.get_request(online)).acctounting() self.render_json(code=1,msg=u"unlock all online done!") return online = self.db.query(models.TrOnline).filter_by( nas_addr=nas_addr, acct_session_id=session_id).first() if not online: self.render_json(code=1,msg=u"online not exists") return if not CustomerOnlineUnlockHandler.dictionary: CustomerOnlineUnlockHandler.dictionary = dictionary.Dictionary( os.path.join(os.path.dirname(toughradius.__file__), 'dictionarys/dictionary')) deferd = authorize.disconnect( int(nas.vendor_id or 0), CustomerOnlineUnlockHandler.dictionary, nas.bas_secret, nas.ip_addr, coa_port=int(nas.coa_port or 3799), debug=True, User_Name=username, NAS_IP_Address=nas.ip_addr, Acct_Session_Id=session_id) deferd.addCallback( self.onSendResp, self.get_request(online)).addErrback( self.onSendError, self.get_request(online)) return deferd
def __init__(self, config, dbengine, radcache=None): self.config = config self.dict = dictionary.Dictionary( os.path.join(os.path.dirname(toughradius.__file__), 'dictionarys/dictionary')) self.db_engine = dbengine or get_engine(config) self.aes = utils.AESCipher(key=self.config.system.secret) self.mcache = radcache self.pusher = ZmqPushConnection(ZmqFactory(), ZmqEndpoint('connect', 'ipc:///tmp/radiusd-auth-result')) self.stat_pusher = ZmqPushConnection(ZmqFactory(), ZmqEndpoint('connect', 'ipc:///tmp/radiusd-stat-task')) self.puller = ZmqPullConnection(ZmqFactory(), ZmqEndpoint('connect', 'ipc:///tmp/radiusd-auth-message')) self.puller.onPull = self.process reactor.listenUDP(0, self) logger.info("init auth worker pusher : %s " % (self.pusher)) logger.info("init auth worker puller : %s " % (self.puller)) logger.info("init auth stat pusher : %s " % (self.stat_pusher))
def test_auth(): _dict = dictionary.Dictionary('../../dictionary/dictionary') sender = functools.partial(client.send_auth, 'secret', _dict, "127.0.0.1") req = {} req['User-Name'] = 'test01' req['CHAP-Password'] = '******' req["NAS-IP-Address"] = "192.168.1.10" req["NAS-Port"] = 0 req["Service-Type"] = "Login-User" req["NAS-Identifier"] = "trillian" req["Called-Station-Id"] = "00-04-5F-00-0F-D1" req["Calling-Station-Id"] = "00-01-24-80-B3-9C" req["Framed-IP-Address"] = "10.0.0.100" log.msg("req:" + repr(req)) resp = yield sender(**req) log.msg('auth done %s' % repr(resp)) reactor.stop()
def __init__(self, server, port, secret, requests, concurrency, username, password, verb=False, timeout=600, rate=1000): logname = "/tmp/trbctl-worker-{}.log".format(os.environ.get( "LOGID", 0)) log.startLogging(open(logname, 'w')) self.timeout = timeout self.pusher = ZmqPushConnection( ZmqFactory(), ZmqEndpoint('connect', 'ipc:///tmp/toughbt-message')) self.pusher.push("write worker %s log into %s" % (os.getpid(), logname)) log.msg("init BenchmarkWorker pusher : %s " % repr(self.pusher)) # define client cycle list raddict = dictionary.Dictionary( os.path.join(os.path.dirname(__file__), "dictionary")) new_cli = lambda: RadAuthClient(str(secret), raddict, server, port=port, debug=verb, stat_push=self.pusher) clis = itertools.cycle([new_cli() for c in range(concurrency)]) # send radius message send = lambda: next(clis).sendAuth(**{ 'User-Name': username, 'User-Password': password }) send_rate = 1.0 / rate send_delay = send_rate for i in xrange(requests): reactor.callLater(send_delay, send) send_delay += send_rate reactor.callLater(self.timeout, self.on_timeout)
nas_addr=nas_addr, acct_session_id=acct_session_id ).delete() self.db.commit() self.render_verify_err(msg=u"nasaddr not exists, online clear!") return online = self.db.query(models.TrOnline).filter_by( nas_addr=nas_addr, acct_session_id=acct_session_id).first() if not online: self.render_verify_err(msg=u"online not exists") return if not OnlineUnlockHandler.dictionary: OnlineUnlockHandler.dictionary = dictionary.Dictionary( os.path.join(os.path.dirname(toughradius.__file__), 'dictionarys/dictionary')) deferd = authorize.disconnect( int(nas.vendor_id or 0), OnlineUnlockHandler.dictionary, nas.bas_secret, nas.ip_addr, coa_port=int(nas.coa_port or 3799), debug=True, User_Name=account_number, NAS_IP_Address=nas.ip_addr, Acct_Session_Id=acct_session_id) deferd.addCallback( self.onSendResp, self.get_request(online)).addErrback( self.onSendError, self.get_request(online))
#!/usr/bin/env python #coding=utf-8 import os import six from twisted.python import log from twisted.internet import protocol from twisted.internet import reactor, defer from txradius.radius import packet from txradius.ext import ikuai from txradius import message from txradius.radius import dictionary import txradius RADIUS_DICT = dictionary.Dictionary(os.path.join(os.path.dirname(txradius.__file__), 'dictionary/dictionary')) def get_dm_packet(vendor_id, nas_secret, nas_addr, coa_port=3799, **kwargs): coa_request = message.CoAMessage( code=packet.DisconnectRequest, dict=RADIUS_DICT, secret=six.b(str(nas_secret)), **kwargs ) username = coa_request["User-Name"][0] if int(vendor_id) == ikuai.VENDOR_ID: pkg = ikuai.create_dm_pkg(six.b(str(nas_secret)), username) return (pkg,nas_addr,coa_port) else: return (coa_request.RequestPacket(),nas_addr,coa_port) class CoAClient(protocol.DatagramProtocol):
class RadiusEvents(BasicEvent): dictionary = dictionary.Dictionary( os.path.join(os.path.dirname(toughradius.__file__), 'dictionarys/dictionary')) def get_request(self, online): if not online: return None session_time = (datetime.datetime.now() - datetime.datetime.strptime( online.acct_start_time,"%Y-%m-%d %H:%M:%S")).total_seconds() return Storage( account_number = online.account_number, mac_addr = online.mac_addr, nas_addr = online.nas_addr, nas_port = 0, service_type = 2, framed_ipaddr = online.framed_ipaddr, framed_netmask = '', nas_class = '', session_timeout = 0, calling_station_id = '', acct_status_type = STATUS_TYPE_STOP, acct_input_octets = 0, acct_output_octets = 0, acct_terminate_cause=6, acct_session_id = online.acct_session_id, acct_session_time = session_time, acct_input_packets = online.input_total * 1024, acct_output_packets = online.output_total * 1024, acct_input_gigawords = 0, acct_output_gigawords = 0, event_timestamp = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S"), nas_port_type=16, nas_port_id=online.nas_port_id ) def onSendResp(self, resp, disconnect_req): if disconnect_req and self.db.query(models.TrOnline).filter_by( nas_addr=disconnect_req.nas_addr, acct_session_id=disconnect_req.acct_session_id).count() > 0: radius_acct_stop.RadiusAcctStop( self.dbengine,self.mcache,self.aes,disconnect_req).acctounting() logger.info(u"send disconnect ok! coa resp : %s" % resp) def onSendError(self,err, disconnect_req): if disconnect_req and self.db.query(models.TrOnline).filter_by( nas_addr=disconnect_req.nas_addr, acct_session_id=disconnect_req.acct_session_id).count() > 0: radius_acct_stop.RadiusAcctStop( self.dbengine,self.mcache,self.aes, disconnect_req).acctounting() logger.error(u"send disconnect done! %s" % err.getErrorMessage()) def event_unlock_online(self, account_number, nas_addr, acct_session_id): logger.info("event unlock online [username:{0}] {1} {2}".format(account_number, nas_addr, acct_session_id)) nas = self.db.query(models.TrBas).filter_by(ip_addr=nas_addr).first() if nas_addr and not nas: self.db.query(models.TrOnline).filter_by( nas_addr=nas_addr,acct_session_id=acct_session_id).delete() self.db.commit() return online = self.db.query(models.TrOnline).filter_by( nas_addr=nas_addr, acct_session_id=acct_session_id).first() authorize.disconnect( int(nas.vendor_id or 0), self.dictionary, nas.bas_secret, nas.ip_addr, coa_port=int(nas.coa_port or 3799), debug=True, User_Name=account_number, NAS_IP_Address=nas.ip_addr, Acct_Session_Id=acct_session_id, Framed_IP_Address=online.framed_ipaddr, ).addCallback( self.onSendResp, self.get_request(online)).addErrback( self.onSendError, self.get_request(online)) def event_clear_online(self, account_number,nas_addr, acct_session_id): try: with make_db(self.db) as db: logger.info("event clear expire online [username:{0}] {1} {2}".format(account_number, nas_addr, acct_session_id)) nas = db.query(models.TrBas).filter_by(ip_addr=nas_addr).first() if nas_addr and not nas: db.query(models.TrOnline).filter_by( nas_addr=nas_addr,acct_session_id=acct_session_id).delete() db.commit() return online = db.query(models.TrOnline).filter_by( nas_addr=nas_addr, acct_session_id=acct_session_id).first() clear_req = self.get_request(online) radius_acct_stop.RadiusAcctStop(self.dbengine,self.mcache,self.aes,clear_req).acctounting() logger.info(u"系统触发用户过期清理成功: [username:%s] OnlineInfo: %s "%(str(account_number), json.dumps(clear_req)),trace="event" ) except Exception as err: logger.exception(err)
import ConfigParser from decimal import Decimal from txradius import client from txradius.radius import dictionary from twisted.python import log from twisted.python.logfile import DailyLogFile CONFIG_FILE = '/etc/openvpn/txovpn.conf' DICTIONARY_FILE = os.path.join(os.path.dirname(client.__file__), "dictionary/ovpn_dictionary") ACCT_START = 1 ACCT_STOP = 2 ACCT_UPDATE = 3 get_dictionary = lambda: dictionary.Dictionary(DICTIONARY_FILE) get_challenge = lambda: ''.join( chr(b) for b in [random.SystemRandom().randrange(0, 256) for i in range(16)]) __defconfig__ = dict( nas_id='txovpn', nas_coa_port='3799', nas_addr='127.0.0.1', radius_addr='127.0.0.1', radius_auth_port='1812', radius_acct_port='1813', radius_secret='secret', radius_timeout='3', acct_interval='60',