forked from talkincode/toughradius
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
wangjuntao
committed
Nov 18, 2017
1 parent
c1787a6
commit 524f996
Showing
282 changed files
with
28,174 additions
and
1,341 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
#!/usr/bin/env python | ||
#coding=utf-8 | ||
import os, sys | ||
|
||
__version__ = '5.0.0.5' | ||
__license__ = 'Apache License 2.0' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# coding: utf-8 | ||
class ObjectDict(dict): | ||
def __getattr__(self, name): | ||
try: | ||
return self[name] | ||
except KeyError: | ||
raise AttributeError(name) | ||
|
||
def __setattr__(self, name, value): | ||
self[name] = value |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
import logging | ||
from datetime import datetime | ||
|
||
import json | ||
|
||
BUILTIN_ATTRS = { | ||
'args', | ||
'asctime', | ||
'created', | ||
'exc_info', | ||
'exc_text', | ||
'filename', | ||
'funcName', | ||
'levelname', | ||
'levelno', | ||
'lineno', | ||
'module', | ||
'msecs', | ||
'message', | ||
'msg', | ||
'name', | ||
'pathname', | ||
'process', | ||
'processName', | ||
'relativeCreated', | ||
'stack_info', | ||
'thread', | ||
'threadName', | ||
} | ||
|
||
|
||
class JSONFormatter(logging.Formatter): | ||
"""JSON log formatter. | ||
Usage example:: | ||
import logging | ||
import json_log_formatter | ||
json_handler = logging.FileHandler(filename='/var/log/my-log.json') | ||
json_handler.setFormatter(json_log_formatter.JSONFormatter()) | ||
logger = logging.getLogger('my_json') | ||
logger.addHandler(json_handler) | ||
logger.info('Sign up', extra={'referral_code': '52d6ce'}) | ||
The log file will contain the following log record (inline):: | ||
{ | ||
"message": "Sign up", | ||
"time": "2015-09-01T06:06:26.524448", | ||
"referral_code": "52d6ce" | ||
} | ||
""" | ||
|
||
json_lib = json | ||
|
||
def format(self, record): | ||
message = record.getMessage() | ||
extra = self.extra_from_record(record) | ||
json_record = self.json_record(message, extra, record) | ||
mutated_record = self.mutate_json_record(json_record) | ||
# Backwards compatibility: Functions that overwrite this but don't | ||
# return a new value will return None because they modified the | ||
# argument passed in. | ||
if mutated_record is None: | ||
mutated_record = json_record | ||
return self.to_json(mutated_record) | ||
|
||
def to_json(self, record): | ||
"""Converts record dict to a JSON string. | ||
Override this method to change the way dict is converted to JSON. | ||
""" | ||
return self.json_lib.dumps(record,default=repr,ensure_ascii=False) | ||
|
||
def extra_from_record(self, record): | ||
"""Returns `extra` dict you passed to logger. | ||
The `extra` keyword argument is used to populate the `__dict__` of | ||
the `LogRecord`. | ||
""" | ||
return { | ||
attr_name: record.__dict__[attr_name] | ||
for attr_name in record.__dict__ | ||
if attr_name not in BUILTIN_ATTRS | ||
} | ||
|
||
def json_record(self, message, extra, record): | ||
"""Prepares a JSON payload which will be logged. | ||
Override this method to change JSON log format. | ||
:param message: Log message, e.g., `logger.info(msg='Sign up')`. | ||
:param extra: Dictionary that was passed as `extra` param | ||
`logger.info('Sign up', extra={'referral_code': '52d6ce'})`. | ||
:param record: `LogRecord` we got from `JSONFormatter.format()`. | ||
:return: Dictionary which will be passed to JSON lib. | ||
""" | ||
extra['message'] = message | ||
if 'time' not in extra: | ||
extra['time'] = datetime.utcnow() | ||
|
||
if record.exc_info: | ||
extra['exc_info'] = self.formatException(record.exc_info) | ||
|
||
return extra | ||
|
||
def mutate_json_record(self, json_record): | ||
"""Override it to convert fields of `json_record` to needed types. | ||
Default implementation converts `datetime` to string in ISO8601 format. | ||
""" | ||
for attr_name in json_record: | ||
attr = json_record[attr_name] | ||
if isinstance(attr, datetime): | ||
json_record[attr_name] = attr.isoformat() | ||
return json_record |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
#!/usr/bin/env python | ||
# coding: utf-8 | ||
import os | ||
import sys | ||
from gevent import socket | ||
from toughradius.txradius.radius import packet | ||
from toughradius.txradius.radius import dictionary | ||
from toughradius.txradius import message | ||
from toughradius.common import six | ||
from toughradius.txradius.ext import ikuai | ||
import toughradius | ||
import logging | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
def get_dictionary(dictfile=None): | ||
if dictfile and os.path.exists(dictfile): | ||
return dictionary.Dictionary(dictfile) | ||
else: | ||
return dictionary.Dictionary(os.path.join(os.path.dirname(toughradius.__file__),'dictionarys/dictionary')) | ||
|
||
def send_auth(server, port=1812, secret=six.b("testing123"), debug=False, dictfile=None, **kwargs): | ||
try: | ||
radius_dictionary = get_dictionary(dictfile=dictfile) | ||
timeout_sec = kwargs.pop('timeout', 5) | ||
result = kwargs.pop('result', True) | ||
User_Password = kwargs.pop("User-Password", None) | ||
CHAP_Password = kwargs.pop("CHAP-Password", None) | ||
CHAP_Password_Plaintext = kwargs.pop("CHAP-Password-Plaintext", None) | ||
CHAP_Challenge = kwargs.get("CHAP-Challenge") | ||
request = message.AuthMessage(dict=radius_dictionary, secret=secret, **kwargs) | ||
if User_Password: | ||
request['User-Password'] = request.PwCrypt(User_Password) | ||
if CHAP_Password: | ||
if CHAP_Challenge: | ||
request['CHAP-Challenge'] = CHAP_Challenge | ||
request['CHAP-Password'] = CHAP_Password | ||
if CHAP_Password_Plaintext: | ||
request['CHAP-Password'] = request.ChapEcrypt(CHAP_Password_Plaintext) | ||
|
||
if debug: | ||
logger.debug("Send radius auth request to (%s:%s): %s" % (server, port, request.format_str())) | ||
|
||
sock = socket.socket(type=socket.SOCK_DGRAM) | ||
sock.settimeout(timeout_sec) | ||
sock.connect((server,port)) | ||
sock.send(request.RequestPacket()) | ||
if result: | ||
data, address = sock.recvfrom(8192) | ||
reply = request.CreateReply(packet=data) | ||
if debug: | ||
logger.debug("Recv radius auth response from (%s:%s): %s" % (server, port, reply.format_str())) | ||
return reply | ||
except Exception as e: | ||
logger.error("authenticator error {}".format(e.message), exc_info=True) | ||
|
||
|
||
def send_acct(server, port=1813, secret=six.b("testing123"), debug=False, dictfile=None, **kwargs): | ||
try: | ||
radius_dictionary = get_dictionary(dictfile=dictfile) | ||
timeout_sec = kwargs.pop('timeout', 5) | ||
result = kwargs.pop('result', True) | ||
request = message.AcctMessage(dict=radius_dictionary, secret=secret, **kwargs) | ||
if debug: | ||
logger.debug("Send radius acct request to (%s:%s): %s" % (server, port, request.format_str())) | ||
|
||
sock = socket.socket(type=socket.SOCK_DGRAM) | ||
sock.settimeout(timeout_sec) | ||
sock.connect((server,port)) | ||
sock.send(request.RequestPacket()) | ||
if result: | ||
data, address = sock.recvfrom(8192) | ||
reply = request.CreateReply(packet=data) | ||
if debug: | ||
logger.debug("Recv radius auth response from (%s:%s): %s" % (server, port, reply.format_str())) | ||
return reply | ||
except Exception as e: | ||
logger.error("accounting error {}".format(e.message), exc_info=True) | ||
|
||
|
||
def send_coadm(server, port=3799, secret=six.b("testing123"), debug=False, dictfile=None, **kwargs): | ||
try: | ||
radius_dictionary = get_dictionary(dictfile=dictfile) | ||
timeout_sec = kwargs.pop('timeout', 5) | ||
result = kwargs.pop('result', True) | ||
vendor_id = kwargs.pop('vendor_id', 0) | ||
request = message.CoAMessage(code=packet.DisconnectRequest, dict=radius_dictionary, secret=secret, **kwargs) | ||
username = request["User-Name"][0] | ||
if vendor_id == ikuai.VENDOR_ID: | ||
pkg = ikuai.create_dm_pkg(secret, username) | ||
if debug: | ||
logger.debug( "Send ikuai radius CoaDmRequest to (%s:%s) [username:%s]: %s" % (server, port, username, repr(pkg))) | ||
else: | ||
pkg = request.RequestPacket() | ||
if debug: | ||
logger.debug("Send radius CoaDmRequest to (%s:%s) [username:%s]: %s" % (server, port, username, request.format_str())) | ||
|
||
sock = socket.socket(type=socket.SOCK_DGRAM) | ||
sock.settimeout(timeout_sec) | ||
sock.connect((server,port)) | ||
sock.send(pkg) | ||
if result: | ||
data, address = sock.recvfrom(8192) | ||
if vendor_id != ikuai.VENDOR_ID: | ||
reply = request.CreateReply(packet=data) | ||
if debug: | ||
logger.debug("Recv radius coa dm response from (%s:%s): %s" % (server, port, reply.format_str())) | ||
return reply | ||
else: | ||
if debug: | ||
logger.debug("Recv radius ik coa dm response from (%s:%s): %s" % (server, port, repr(data))) | ||
return data | ||
except Exception as e: | ||
logger.error("accounting error {}".format(e.message), exc_info=True) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
#!/usr/bin/env python | ||
# coding: utf-8 | ||
import os | ||
import sys | ||
import gevent | ||
import argparse | ||
import logging | ||
import logging.config | ||
import importlib | ||
|
||
def run(): | ||
from toughradius import settings | ||
logging.config.dictConfig(settings.LOGGER) | ||
logger = logging.getLogger(__name__) | ||
parser = argparse.ArgumentParser() | ||
parser.add_argument('--auth-port', default='1812', dest="auth_port",type=int) | ||
parser.add_argument('--acct-port', default='1813', dest="acct_port",type=int) | ||
parser.add_argument('--pool', default='1024', dest="pool",type=int) | ||
parser.add_argument('--rest-auth-url', default=None, dest="rest_auth_url",type=str) | ||
parser.add_argument('--rest-acct-url', default=None, dest="rest_acct_url",type=str) | ||
parser.add_argument('-x','--debug', action='store_true',default=False,dest='debug',help='debug option') | ||
args = parser.parse_args(sys.argv[1:]) | ||
|
||
if args.debug: | ||
settings.RADIUSD.update(debug=1) | ||
os.environ['TOUGHRADIUS_DEBUG_ENABLED'] = "1" | ||
|
||
if args.auth_port > 0: | ||
settings.RADIUSD.update(auth_port=args.auth_port) | ||
|
||
if args.acct_port > 0: | ||
settings.RADIUSD.update(acct_port=args.acct_port) | ||
|
||
if args.rest_auth_url: | ||
settings.ADAPTERS['rest'].update(authurl=args.rest_auth_url) | ||
|
||
if args.rest_acct_url: | ||
settings.ADAPTERS['rest'].update(accturl=args.rest_acct_url) | ||
|
||
from toughradius.radiusd.master import RudiusAuthServer | ||
from toughradius.radiusd.master import RudiusAcctServer | ||
host = settings.RADIUSD['host'] | ||
auth_port = settings.RADIUSD['auth_port'] | ||
acct_port = settings.RADIUSD['acct_port'] | ||
pool_size = settings.RADIUSD['pool_size'] | ||
adapter_class = settings.RADIUSD['adapter'] | ||
adapter = importlib.import_module(adapter_class).adapter(settings) | ||
auth_server = RudiusAuthServer(adapter, host=host, port=auth_port, pool_size=pool_size) | ||
acct_server = RudiusAcctServer(adapter, host=host, port=acct_port, pool_size=pool_size) | ||
auth_server.start() | ||
acct_server.start() | ||
logger.info(auth_server) | ||
logger.info(acct_server) | ||
gevent.wait() | ||
|
||
if __name__ == "__main__": | ||
run() |
Oops, something went wrong.