def test_success_okta(self, a, b): self.server.hosts["127.0.0.1"] = os.getenv('RADIUS_SECRET') self.server.BindToAddress("127.0.0.1") Client(server="127.0.0.1", secret=os.getenv('RADIUS_SECRET').encode(), dict=Dictionary("dictionary")) # create request req = AuthPacket( id=AccessRequest, secret=os.getenv('RADIUS_SECRET').encode(), authenticator=b'01234567890ABCDEF', dict=Dictionary("dictionary") ) req["User-Name"] = '*****@*****.**' req["User-Password"] = req.PwCrypt('fake') req["Proxy-State"] = 'state'.encode("ascii") req.source = ("test", "port") fd = MockFd() req.fd = fd # send request with self.assertLogs('server', level='INFO') as log: self.server.auth_handler(req) self.assertEqual(fd.data, b'\x02\x01\x00\x1b\x82\xb4\x88\xb4G\xbc:\xde\xc1\xe5A\xe0\xe7y\r\x1f!\x07state') self.assertIn('INFO:server:Push approved by [email protected].', log.output)
def test_using_samaccountname_flag(self, o, mock_get, mock_post): self.assertIsNotNone(os.environ.get('OKTA_USE_SAMACCOUNTNAME')) self.server.hosts["127.0.0.1"] = os.getenv('RADIUS_SECRET') self.server.BindToAddress("127.0.0.1") Client(server="127.0.0.1", secret=os.getenv('RADIUS_SECRET').encode(), dict=Dictionary("dictionary")) # create request req = AuthPacket( id=AccessRequest, secret=os.getenv('RADIUS_SECRET').encode(), authenticator=b'01234567890ABCDEF', dict=Dictionary("dictionary") ) req["User-Name"] = 'username' req["User-Password"] = req.PwCrypt('fake') req["Proxy-State"] = 'state'.encode() req.source = ("test", "port") fd = MockFd() req.fd = fd # send request with self.assertLogs('server', level='INFO') as log: o.return_value = '00ub0oNGTSWTBKOLGLNR' self.server.auth_handler(req) o.assert_called_once_with('username') self.assertEqual(fd.data, b'\x02\x01\x00\x1b\x82\xb4\x88\xb4G\xbc:\xde\xc1\xe5A\xe0\xe7y\r\x1f!\x07state') self.assertIn('INFO:server:Push approved by username.', log.output)
def testParseMultipleDictionaries(self): dict = Dictionary(StringIO('')) self.assertEqual(len(dict), 0) one = StringIO('ATTRIBUTE Test-First 1 string') two = StringIO('ATTRIBUTE Test-Second 2 string') dict = Dictionary(StringIO(''), one, two) self.assertEqual(len(dict), 2)
def peers_alive(config): from pyrad.client import Client from pyrad.dictionary import Dictionary radconfig = config['radius'] localconfig = config['local'] auth_OK = True dictionary = Dictionary(localconfig['raddict']) for server in radconfig['servers']: srv = Client(server=server, secret=str(radconfig['secret']), dict=dictionary) req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=radconfig['username'], NAS_Identifier="localhost") req["User-Password"] = req.PwCrypt(radconfig['password']) try: reply = srv.SendPacket(req) except pyrad.client.Timeout: print "Could not contact:", server auth_OK = False if reply.code != 2: print "Auth failed to", server auth_OK = False return auth_OK
class RADIUSBackend(BaseAuthBackend): RADIUS_DICT = Dictionary("services/login/backends/radius.dict") def authenticate(self, user: str = None, password: str = None, **kwargs) -> str: radius_server = config.login.radius_server radius_secret = smart_bytes(config.login.radius_secret) client = Client(server=radius_server, secret=radius_secret, dict=self.RADIUS_DICT) req = client.CreateAuthPacket(code=AccessRequest, User_Name=user, NAS_Identifier="noc") req["User-Password"] = req.PwCrypt(password) try: reply = client.SendPacket(req) except client.Timeout: raise self.LoginError("Timed out") if reply.code != AccessAccept: raise self.LoginError("RADIUS Authentication failed. Code=%s", reply.code) return user
def do_authentication(self, user, passcode=""): radcli = Client(server=self._server, authport=self._port, secret=self._secret, dict=Dictionary(RADIUS_DICTIONARY)) radcli.retries = self._conn_retries radcli.timeout = self._conn_timeout l = ldap.initialize("ldap://192.168.56.101") try: l.simple_bind_s("*****@*****.**", "Welcome123") ldap_result = l.search("dc=internal,dc=neteas", ldap.SCOPE_SUBTREE, "(&(objectClass=group)(cn=BALABIT_MFA))", None) res_type, data = l.result(ldap_result, 0) user1 = user[1:] a = str(data[0][1]['member']) if user1 in a: ldap_result = l.search( "dc=internal,dc=neteas", ldap.SCOPE_SUBTREE, "(&(objectClass=user)(cn=" + user + "))", None) res_type, data = l.result(ldap_result, 0) user = data[0][1]['userPrincipalName'][0] radpkt = self._createAuthenticationPacket(client=radcli, radius_user=user, radius_pass=passcode) print user else: return True except Exception, error: return True
def execute(self): args = self.args # pylint: disable=W0703 try: username = args.get("username", "") password = args.get("password", "") rad_secret = args.get("secret", "").encode("utf-8") identifier = args.get("identifier", "") dictionary = args.get("dictionary", DEFAULT_DICTIONARY) ip, _port = self.get_address() srv = Client(server=ip, secret=rad_secret, dict=Dictionary(dictionary)) req = srv.CreateAuthPacket( code=pyrad.packet.AccessRequest, User_Name=username, NAS_Identifier=identifier, ) req["User-Password"] = req.PwCrypt(password) srv.SendPacket(req) except Exception as err: return ( Event.DOWN, "Failed connecting to %s: %s)" % (self.get_address(), str(err)), ) version = "FreeRadius 1.0" # Fetch from radiusmonitor later. self.version = version return Event.UP, "Radius: " + version
def setUp(self): self.path = os.path.join(home, 'tests', 'data') self.dict = Dictionary(os.path.join(self.path, 'chap')) # self.packet = packet.Packet(id=0, secret=six.b('secret'), # dict=self.dict) self.client = Client(server='localhost', secret=six.b('secret'), dict=self.dict)
def init_dictionary(): if not os.path.exists(DICTIONARY_DIR): raise Exception('DICTIONARY_DIR:{} not exist'.format(DICTIONARY_DIR)) # 遍历目录一次 root, dirs, files = next(os.walk(DICTIONARY_DIR)) dictionaries = [os.path.join(root, f) for f in files] return Dictionary(*dictionaries)
def setUp(self): self.path = os.path.join(home, 'tests', 'data') self.dict = Dictionary(os.path.join(self.path, 'full')) self.pkt = packet.AuthPacket(dict=self.dict, auto_crypt=True, secret=six.b('secret'), authenticator=six.b('01234567890ABCDEF'))
def testContainment(self): dict = Dictionary() self.assertEqual('test' in dict, False) self.assertEqual(dict.has_key('test'), False) dict.attributes['test'] = 'dummy' self.assertEqual('test' in dict, True) self.assertEqual(dict.has_key('test'), True)
def parse_packet(filename): with PcapReader(filename) as file_capture: global start_parse, end_parse, count, totaltime for packet in file_capture: try: if ( len(packet) > 400 and packet.dport == 1813 ): # We only need pcakets whose length is greater than 400 bytes # Capturing the RAW data from packet (the index value for raw data is 3) start_parse = time() radius_packet = str(packet[Radius]) # Pyrad has a dictionary with the RADIUS attributes defined, It'll help in decoding the RAW Packet pkt = Packet(packet=radius_packet, dict=Dictionary("dictionary")) attr1 = pkt._DecodeKey(8) value1 = pkt.__getitem__(attr1) attr2 = pkt._DecodeKey(31) value2 = pkt.__getitem__(attr2) end_parse = time() print("Time Taken to parse RADIUS packet: %s seconds" % (end_parse - start_parse)) count += 1 totaltime += (end_parse - start_parse) print("%d Private IP: %s and MSISDN: %s" % (count, value1, value2)) except AttributeError: print( "Port attribute not available in the packet, skipping the parsing on the packet... " )
def authenticate(self, username=None, password=None): """Authenticate against the RADIUS server""" # Create a RADIUS client radius_dict = Dictionary(settings.RADIUS_DICT) client = Client(server=settings.RADIUS_HOST, authport=settings.RADIUS_PORT, secret=settings.RADIUS_SECRET.encode('utf-8'), # avoid UnicodeDecodeError dict=radius_dict, ) # Create a packet ... req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=username.encode('utf-8'), ) req["User-Password"] = req.PwCrypt(password) # .. and send it try: reply = client.SendPacket(req) except Exception as e: # Something went wrong with the packet. Just fall through return None # Handle the reply if reply.code == pyrad.packet.AccessReject: # Access was rejected return None elif reply.code != pyrad.packet.AccessAccept: # Some error return None else: backend = self.__module__ + "." + self.__class__.__name__ user, created = get_or_create_user(backend, username) return user
def setUp(self): self.path = os.path.join(home, 'tests', 'data') self.dict = Dictionary(os.path.join(self.path, 'full')) self.packet = packet.Packet(id=0, secret=six.b('secret'), authenticator=six.b('01234567890ABCDEF'), dict=self.dict)
def run(): # Check to make sure env variables are set if not all(v in os.environ for v in [ "OKTA_API_KEY", "OKTA_TENANT", "RADIUS_SECRET", "RADIUS_PORT", "OKTA_WKF_ASYNC_MFA_CREATE_TRANSACTION_URL", "OKTA_WKF_ASYNC_MFA_POLL_TRANSACTION_URL" ]): logger.error("Missing environment variables!") sys.exit("Missing environment variables!") # Create server and read the attribute dictionary srv = RadiusServer(os.getenv('OKTA_TENANT'), os.getenv('OKTA_API_KEY'), dict=Dictionary("dictionary"), coa_enabled=False, authport=int(os.getenv('RADIUS_PORT'))) # Add clients (address, secret, name) srv.hosts["0.0.0.0"] = RemoteHost("0.0.0.0", os.getenv("RADIUS_SECRET").encode(), "0.0.0.0") srv.BindToAddress("") logger.info("Starting server...") # Run the RADIUS server srv.Run()
def radius_dictionary(): global _RADIUS_DICTIONARY if not _RADIUS_DICTIONARY: fp = StringIO(dictionary.RADIUS_ATTRIBUTES) _RADIUS_DICTIONARY = Dictionary(fp) fp.close() return _RADIUS_DICTIONARY
def authenticate_using_radius_server(self, request, callback): """Authenticate a subject using a RADIUS server.""" try: root_dir = os.path.abspath( os.path.join(_conf.install_location(), '..')) client = Client( server=self.sec_conf['authentication']['server_ip'], secret=bytes(self.sec_conf['authentication']['secret']), dict=Dictionary( os.path.join(root_dir, "extras", "pyrad_dicts", "dictionary"), os.path.join(root_dir, "extras", "pyrad_dicts", "dictionary.acc"))) req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=request['subject']['user'], NAS_Identifier=self.node.id) req["User-Password"] = req.PwCrypt(request['subject']['password']) # FIXME: should not block here (use a callback instead) reply = client.SendPacket(req) if reply.code == pyrad.packet.AccessAccept: _log.debug("Security: access accepted") # Save attributes returned by server. self._return_authentication_decision( True, json.loads(reply["Reply-Message"][0]), callback) return _log.debug("Security: access denied") self._return_authentication_decision(False, [], callback) except Exception as err: _log.error("Failed RADIUS authentication, err={}".format(err)) self._return_authentication_decision(False, [], callback)
def testDictFileParseError(self): tmpdict = Dictionary() try: tmpdict.ReadDictionary(os.path.join(self.path, 'dictfiletest')) except ParseError as e: self.assertEqual('dictfiletest' in str(e), True) else: self.fail()
def __init__(self, host, port=None): self.host = host self.port = port self.nas_ip_address = '192.168.155.93' self.nas_port_type = 'virtual' self.nas_called_station_id = '94.74.128.22' self.nas_calling_station_id = '94.74.128.22' self.frame_protocol = 'PPP' self.service_type = 'Framed-User' self.dictionary = Dictionary("dictionary", "dictionary") self.interimupdate = 60 self.shared_secret = "testing123" self.Nas_Identifier = "localhost" self.srv = Client(server=constants.host, secret="testing123", dict=Dictionary("dictionary", "dictionary")) self.userlist = []
def login(): server = app.config['AUTH_SERVER'] secret = app.config['AUTH_SECRET'] nas_id = app.config['NAS_ID'] form = LoginForm() if form.validate_on_submit(): srv = Client(server=server, secret=secret, dict=Dictionary("dictionary.py")) #test account if ('test' in form.username.data): print("access accepted") user = User.query.filter_by(username=form.username.data).first() if user: login_user(user, remember=form.remember.data) else: new_user = User(username=form.username.data) db.session.add(new_user) db.session.commit() login_user(new_user, remember=form.remember.data) logger.info('{}:{} created'.format(current_user.id, new_user.username)) logger.info('{}:{} login'.format(current_user.username, current_user.id)) return redirect(url_for('asset.invest_list')) # create request req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=form.username.data, NAS_Identifier=nas_id) req["User-Password"] = req.PwCrypt(form.password.data) # send request reply = srv.SendPacket(req) if reply.code == pyrad.packet.AccessAccept: print("access accepted") user = User.query.filter_by(username=form.username.data).first() if user: login_user(user, remember=form.remember.data) else: new_user = User(username=form.username.data) db.session.add(new_user) db.session.commit() login_user(new_user, remember=form.remember.data) return redirect(url_for('asset.invest_list')) else: print("access denied") flash('用户名或密码错误,请重新登陆') return redirect(url_for('auth.login')) print("Attributes returned by server:") for i in reply.keys(): print("%s: %s" % (i, reply[i])) return render_template('auth/login.html', form=form)
def __init__(self, server_addr, secret): """ Initialize the connection """ self.server_addr = server_addr self.nas_identifier = self.server_addr self.secret = secret.encode() self.server = Client(server=self.server_addr, secret=self.secret, dict=Dictionary('/etc/ejabberd/dictionary'))
def setUp(self): self.path = os.path.join(home, 'tests', 'data') self.dict = Dictionary(os.path.join(self.path, 'full')) self.packet = packet.AuthPacket( id=0, secret=six.b('secret'), authenticator=six.b('01234567890ABCDEF'), dict=self.dict) self.packet['Test-Tunnel-Pwd'] = \ (1, self.packet.TunnelPwCrypt(six.b('\x80\x01'), 'test'))
def __init__(self, user, password, log): client = Client(server=os.environ.get('RADIUS_SERVER'), secret=os.environ.get('RADIUS_SECRET').encode('ascii'), dict=Dictionary('dictionary')) req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=user) req['User-Password'] = req.PwCrypt(password) reply = client.SendPacket(req) self.auth = reply.code self.log = log
def __init__(self, *args): super(TesterWin, self).__init__(*args) self.running = False self.random_running = False self.testusers = {} self.setupUi(self) self.dict=Dictionary("./dict/dictionary") self.init_client() self.init_random_client() self.init_testusers()
def __init__(self,argvals): self.argvals = argvals self.config = NewConfig('tester.cfg') self.dict=Dictionary("dictionary") self.server = self.config.get('server','host','127.0.0.1') self.authport = self.config.getint('server','authport') self.acctport = self.config.getint('server','acctport') self.authsecret = self.config.get('server','authsecret','secret') self.acctsecret = self.config.get('server','acctsecret','secret') self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,10240000) self.sock.settimeout(self.argvals.timeout)
def __init__(self, radius_settings_tuple, logging): """Инициализация объекта из файла ibitial.conf.""" self.packet_send = 0 self.logging = logging radius_ip = radius_settings_tuple[0] radius_secret = radius_settings_tuple[1] radius_dict_path = radius_settings_tuple[2] self.srv = Client( server=radius_ip, secret=radius_secret.encode(), dict=Dictionary(radius_dict_path), )
def check_auth(self, username, password, allowed_roles, resource, method): srv = Client(server="192.168.137.200", secret="wowsuchsecret", dict=Dictionary("/usr/share/freeradius/dictionary")) req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=username, NAS_Identifier="") req["Password"] = req.PwCrypt(password) reply = srv.SendPacket(req) return reply.code == pyrad.packet.AccessAccept
def setUp(self): self.data_session_id = 'some-id-1234' self.data_src_ip = '2.3.4.5' self.path = os.path.join(sys.modules["tests"].__path__[0], 'data') self.dictionary = Dictionary(os.path.join(self.path, 'dictionary')) self.pkt = Packet(id=0, secret=b'secret', authenticator=b'01234567890ABCDEF', dict=self.dictionary) self.pkt[b'Acct-Status-Type'] = 'Start' self.pkt[b'Acct-Session-Id'] = self.data_session_id self.pkt[b'User-Name'] = 'SomeUser' self.pkt.source = (self.data_src_ip, 5000)
def authenticate(cls, form): """ Authenticates to the configured RADIUS server. """ try: username = unicode(form['username'].split('@', 1)[0].strip()) except Exception: flash("{field} is required.".format( field=cls.inputs['username']['label'])) log.error("Username field missing from authentication form!") return None, False try: password = unicode(form['password']) except Exception: flash("{field} is required.".format( field=cls.inputs['password']['label'])) log.error("Password field missing from authentication form!") return username, False srv = Client(server=cls.config.radius_server, secret=cls.config.radius_secret, dict=Dictionary(dict=cls.config.radius_dictionary)) req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest) req["User-Name"] = username req["User-Password"] = req.PwCrypt(password) req["NAS-Identifier"] = cls.config.radius_nas_identifier # The IP address config option could be made optional # and determined from radius_nas_identifier req["NAS-IP-Address"] = cls.config.radius_nas_ip_address log.debug( "Attempting radius auth: Server: {server}; User-Name: {user}; " "NAS-Identifier {nasid}; NAS-IP: {nasip}; Dictionary {dict}". format(server=srv.server, user=req["User-Name"], nasid=req["NAS-Identifier"], nasip=req["NAS-IP-Address"], dict=cls.config.radius_dictionary)) try: reply = srv.SendPacket(req) except pyrad.client.Timeout: flash('An error has occurred. Please try again.') log.error( "Connection to radius server timed out. This may " "be caused by incorrect sever settings. Check the radius " "server logs for more information. {err}".format( err=format_exc())) return username, False except Exception: flash('An error has occurred. Please try again.') log.error( "Radius server connect failed. {err}".format(err=format_exc())) return username, False return username, reply.code == pyrad.packet.AccessAccept
def parse_packet(packet): if (packet.haslayer(Radius)): radius_packet = str(packet[Radius]) pkt = Packet(packet=radius_packet, dict=Dictionary("dictionary")) for key, value in pkt.iteritems(): attr = pkt._DecodeKey(key) value = pkt.__getitem__(attr) #print attr, value fout.write("%s %s\n" % (attr, str(value))) else: #packet.show() pass