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 _radius_auth_func(self, server, **kwargs): """More private method used to authenticate a user and password against the current RADIUS server. Returns False if the user is rejected, True if the user is accepted. Raises CurrentServerFailed if there was an error with the request (such as a timeout).""" try: auth_port = self.server_dict[server]['auth_port'] secret = self.server_dict[server]['secret'] srv = Client(server=server, authport=auth_port, secret=secret, dict=self.dictionary) srv.timeout = self.server_timeout if self.client_bind_ip is not None: # Binding to port 0 is the official way to bind to a OS-assigned random port. srv.bind((self.client_bind_ip, 0)) req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=kwargs['user'], NAS_Identifier=self.nas_identifier) req["User-Password"] = req.PwCrypt(kwargs['password']) reply = srv.SendPacket(req) if reply.code == pyrad.packet.AccessAccept: return True else: return False except (pyrad.packet.PacketError, pyrad.client.Timeout, socket.error): raise CurrentServerFailed
def auth( path ): # first look in the arguments username = request.args.get('username', None) password = request.args.get('password', None) # then look in the uri or in the X-Auth-Info header auth_header = app.config.get('AUTH_HEADER', '') if not (username and password) : s1 = path.split('/') path2 = request.headers.get(auth_header, "") s2 = path2.split('/') s = [] if len(s1) >= 2: s = s1 elif len(s2) >= 2: s = s2 if len(s) >= 2: username = s[0] password = s[1] app.logger.debug("Incoming auth request: %s/%s" % (username, password) ) rad_server = app.config.get('FREERADIUS_SERVER') rad_secret = app.config.get('FREERADIUS_SECRET') rad_nas = app.config.get('FREERADIUS_NAS') assert rad_server and rad_secret and rad_nas, "Oops.." if username and password: srv=Client( server = rad_server, secret = rad_secret, dict = Dictionary("dictionary") ) # increase timeout srv.timeout = 30 req=srv.CreateAuthPacket( code = pyrad.packet.AccessRequest, User_Name = username, NAS_Identifier = rad_nas ) req["User-Password"]=req.PwCrypt(password) reply=srv.SendPacket(req) if reply.code==pyrad.packet.AccessAccept: return jsonify(), 200 else: return jsonify(), 403 else: return jsonify(), 403
def test_user_connection(self, username, password): """ Method used to perform test search over RADIUS Repository :param username: String with username :param password: String with password """ logger.debug("Radius_authentication_test::Trying to authenticate username {}".format(username.encode('utf-8'))) response = { 'status': None, 'reason': None } try: # Create client srv = Client(server=self.host, secret=self.secret, dict=Dictionary(DICTIONARY_PATH)) srv.retries = self.max_retry srv.timeout = self.max_timeout # create request req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=username, NAS_Identifier=self.nas_id) req["Password"] = req.PwCrypt(password) # send request reply = srv.SendPacket(req) logger.debug("Radius_authentication_test:: Username:{}, return code:{}".format(username, reply.code)) msg = "" if reply.code == pyrad.packet.AccessAccept: response['status'] = True logger.info("RADIUS::Auth: Authentication succeed for user {}".format(username)) for key, item in reply.iteritems(): msg += str(key) + ":" + str(item) else: response['status'] = False msg = "Authentication failed" logger.info("RADIUS::Auth: Authentication failure for user {}".format(username)) response['reason'] = msg except Timeout: response['status'] = False logger.info("RADIUS::Auth: Authentication failure for user {} : Timeout expired while connecting".format(username)) response['reason'] = "Timeout expired while connecting" except Exception as e: response['status'] = False logger.error("Radius_authentication_test::Unable to authenticate username:{}, exception:{}".format(username, str(e))) response['reason'] = "Exception : " + str(e) return response
def authenticate(self, username, password, **kwargs): # """Authentication method of LDAP repository, which returns dict of specified attributes:their values # :param username: String with username # :param password: String with password # :param oauth2_attributes: List of attributes to retrieve # :return: None and raise if failure, server message otherwise # """ logger.debug("Trying to authenticate username {}".format(username.encode('utf-8'))) # try: # Create client srv = Client(server=self.host, secret=self.secret, dict=Dictionary(DICTIONARY_PATH)) srv.retries = self.max_retry srv.timeout = self.max_timeout # create request req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=username, NAS_Identifier=self.nas_id) req["Password"] = req.PwCrypt(password) # send request reply = srv.SendPacket(req) logger.debug("Radius authentication username:{}, return code : {}".format(username, reply.code)) if reply.code == pyrad.packet.AccessAccept: ret = "" for key, item in reply.iteritems(): ret += str(key) + ":" + str(item) else: logger.error("RADIUS_CLI::authenticate: Authentication failure for user '{}'".format(username)) raise AuthenticationError("Authentication failure on Radius backend for user '{}'".format(username)) logger.debug("RADIUS_CLI::authenticate: Authentication reply from server : '{}'".format(ret)) logger.info("RADIUS_CLI::authenticate: Autentication succeed for user '{}'".format(username)) # except Timeout: # raise Timeout # except Exception, e: # logger.error("Unable to authenticate username {} : exception : {}".format(username, str(e))) return { 'dn': username, 'user_phone': 'N/A', 'user_email': 'N/A', 'password_expired': False, 'account_locked': False }
def mk_client(x): try: c = Client( server=x["host"], authport=x["port"], secret=x["secret"].encode(), dict=Dictionary(dictPath), ) except KeyError as e: raise Exception( "%s attribute is missing in one of the radius host entries. Please fix SECURITY_RADIUS_SERVERS:\n " "%s" % (str(e), str(servers))) try: c.timeout = x["timeout"] except KeyError: pass try: c.retries = x["retries"] except KeyError: pass return c
def _connect_radius(host, port, config, toolbox): """Spin up test client and send a Status-Server packet to check if we can reach the radius server""" secret = config.get_protected_str('secret_protected', 'secret').encode() client = Client(server=host, authport=port, secret=secret, dict=base.radius_dictionary()) client.timeout = const.DEFAULT_RADIUS_RETRY_WAIT request = client.CreateAuthPacket(code=pyrad.packet.StatusServer) # The request must contain a message authenticator. request.add_message_authenticator() try: nas_ip = config.get_str('nas_ip') except ConfigError: nas_ip = util.get_authproxy_ip() request.AddAttribute('NAS-IP-Address', nas_ip) return toolbox.test_connect_radius(client, request)
def rad_disconnect(id_port: int): port = EqptPort.query.get(id_port) rad_acct = RadAcct.query \ .filter_by(username=port.radius_user, acctstoptime=None) \ .order_by( RadAcct.radacctid.desc() ).first() if rad_acct is not None: """ # TO-DO: Need testing ------------------------------------ """ acct_session_id = rad_acct.acctsessionid nas_ip_address = rad_acct.nasipaddress # create coa client client = RadClient( server=current_app.config['RADIUS_ADDRESS'], secret=current_app.config['RADIUS_SECRET'], dict=dictionary.Dictionary("dictionary") ) # set coa timeout client.timeout = current_app.config['RADIUS_TIMEOUT'] attr = { "Acct-Session-Id": acct_session_id, "User-Name": port.radius_user, "NAS-IP-Address": nas_ip_address, } # create coa request packet attributes = {k.replace("-", "_"): attr[k] for k in attr} request = client.CreateCoAPacket(code=packet.DisconnectRequest, **attributes) return client.SendPacket(request) # return 'Off CoA paket - need testing. User online.' else: return 'No active user session found. User offline.'
def request(config, user, password): """ Perform a RADIUS request to a RADIUS server. The RADIUS configuration contains the IP address, the port and the secret of the RADIUS server. * config.server * config.port * config.secret * config.retries * config.timeout :param config: The RADIUS configuration :type config: RADIUSServer Database Model :param user: the radius username :param password: the radius password :return: True or False. If any error occurs, an exception is raised. """ success = False nas_identifier = get_from_config("radius.nas_identifier", "privacyIDEA") r_dict = config.dictionary or get_from_config( "radius.dictfile", "/etc/privacyidea/" "dictionary") log.debug("NAS Identifier: %r, " "Dictionary: %r" % (nas_identifier, r_dict)) log.debug("constructing client object " "with server: %r, port: %r, secret: %r" % (config.server, config.port, config.secret)) srv = Client(server=config.server, authport=config.port, secret=decryptPassword(config.secret), dict=Dictionary(r_dict)) # Set retries and timeout of the client if config.timeout: srv.timeout = config.timeout if config.retries: srv.retries = config.retries req = srv.CreateAuthPacket( code=pyrad.packet.AccessRequest, User_Name=user.encode('ascii'), NAS_Identifier=nas_identifier.encode('ascii')) req["User-Password"] = req.PwCrypt(password) try: response = srv.SendPacket(req) if response.code == pyrad.packet.AccessAccept: log.info("Radiusserver %s granted " "access to user %s." % (config.server, user)) success = True else: log.warning("Radiusserver %s rejected " "access to user %s." % (config.server, user)) except Timeout: log.warning( "Receiving timeout from remote radius server {0!s}".format( config.server)) return success
#!/usr/bin/python from __future__ import print_function from pyrad.client import Client from pyrad import dictionary from pyrad import packet import sys if len(sys.argv) != 4: print("usage: disconnect.py <host> <secret> <session-id>") sys.exit(1) ADDRESS = sys.argv[1] SECRET = sys.argv[2] ATTRIBUTES = {"Acct-Session-Id": sys.argv[3]} client = Client(server=ADDRESS, secret=SECRET, dict=dictionary.Dictionary("dictionary")) client.timeout = 30 attributes = {k.replace("-", "_"): ATTRIBUTES[k] for k in ATTRIBUTES} request = client.CreateCoAPacket(code=packet.DisconnectRequest, **attributes) result = client.SendPacket(request) print(result.code)
#!/usr/bin/python from __future__ import print_function from pyrad.client import Client from pyrad import dictionary from pyrad import packet ADDRESS = "127.0.0.1" SECRET = b"Kah3choteereethiejeimaeziecumi" ATTRIBUTES = {"Acct-Session-Id": "1337"} CODE = packet.CoARequest # 43 # CODE = packet.DisconnectRequest # 40 # create coa client client = Client(server=ADDRESS, secret=SECRET, authport=3799, acctport=3799, dict=dictionary.Dictionary("dictionary")) # set coa timeout client.timeout = 30 # create coa request packet attributes = {k.replace("-", "_"): attributes[k] for k in attributes} request = client.CreateAcctPacket(code=CODE, **attributes) # send coa request result = client.SendPacket(request) print(result)
def _check_radius(self, otpval, options=None, radius_state=None): """ run the RADIUS request against the RADIUS server :param otpval: the OTP value :param options: additional token specific options :type options: dict :return: counter of the matching OTP value. :rtype: AccessAccept, AccessReject, AccessChallenge """ result = AccessReject radius_message = None if options is None: options = {} radius_dictionary = None radius_identifier = self.get_tokeninfo("radius.identifier") radius_user = self.get_tokeninfo("radius.user") system_radius_settings = self.get_tokeninfo("radius.system_settings") radius_timeout = 5 radius_retries = 3 if radius_identifier: # New configuration radius_server_object = get_radius(radius_identifier) radius_server = radius_server_object.config.server radius_port = radius_server_object.config.port radius_server = u"{0!s}:{1!s}".format(radius_server, radius_port) radius_secret = radius_server_object.get_secret() radius_dictionary = radius_server_object.config.dictionary radius_timeout = int(radius_server_object.config.timeout or 10) radius_retries = int(radius_server_object.config.retries or 1) elif system_radius_settings: # system configuration radius_server = get_from_config("radius.server") radius_secret = get_from_config("radius.secret") else: # individual token settings radius_server = self.get_tokeninfo("radius.server") # Read the secret secret = self.token.get_otpkey() radius_secret = binascii.unhexlify(secret.getKey()) # here we also need to check for radius.user log.debug(u"checking OTP len:{0!s} on radius server: " u"{1!s}, user: {2!r}".format(len(otpval), radius_server, radius_user)) try: # pyrad does not allow to set timeout and retries. # it defaults to retries=3, timeout=5 # TODO: At the moment we support only one radius server. # No round robin. server = radius_server.split(':') r_server = server[0] r_authport = 1812 if len(server) >= 2: r_authport = int(server[1]) nas_identifier = get_from_config("radius.nas_identifier", "privacyIDEA") if not radius_dictionary: radius_dictionary = get_from_config( "radius.dictfile", "/etc/privacyidea/dictionary") log.debug(u"NAS Identifier: %r, " u"Dictionary: %r" % (nas_identifier, radius_dictionary)) log.debug(u"constructing client object " u"with server: %r, port: %r, secret: %r" % (r_server, r_authport, to_unicode(radius_secret))) srv = Client(server=r_server, authport=r_authport, secret=to_bytes(radius_secret), dict=Dictionary(radius_dictionary)) # Set retries and timeout of the client srv.timeout = radius_timeout srv.retries = radius_retries req = srv.CreateAuthPacket( code=pyrad.packet.AccessRequest, User_Name=radius_user.encode('utf-8'), NAS_Identifier=nas_identifier.encode('ascii')) req["User-Password"] = req.PwCrypt(otpval) if radius_state: req["State"] = radius_state log.info( u"Sending saved challenge to radius server: {0!r} ".format( radius_state)) try: response = srv.SendPacket(req) except Timeout: log.warning( u"The remote RADIUS server {0!s} timeout out for user {1!s}." .format(r_server, radius_user)) return AccessReject # handle the RADIUS challenge if response.code == pyrad.packet.AccessChallenge: # now we map this to a privacyidea challenge if "State" in response: radius_state = response["State"][0] if "Reply-Message" in response: radius_message = response["Reply-Message"][0] result = AccessChallenge elif response.code == pyrad.packet.AccessAccept: radius_state = '<SUCCESS>' radius_message = 'RADIUS authentication succeeded' log.info(u"RADIUS server {0!s} granted " u"access to user {1!s}.".format( r_server, radius_user)) result = AccessAccept else: radius_state = '<REJECTED>' radius_message = 'RADIUS authentication failed' log.debug(u'radius response code {0!s}'.format(response.code)) log.info(u"Radiusserver {0!s} " u"rejected access to user {1!s}.".format( r_server, radius_user)) result = AccessReject except Exception as ex: # pragma: no cover log.error("Error contacting radius Server: {0!r}".format((ex))) log.info("{0!s}".format(traceback.format_exc())) options.update({'radius_result': result}) options.update({'radius_state': radius_state}) options.update({'radius_message': radius_message}) return result
def authenticate(self, environ, identity): """authenticator""" try: if check_failed_logins(environ): return None login = identity['login'].decode('utf-8') password = identity['password'].decode('utf-8') username = login domain = None is_alias = False if '@' not in login: return None username, domain = login.split('@') try: dma = self.dbsession.query(self.dommodel.name)\ .join(self.dam)\ .filter(self.dam.name == domain).one() domain = dma.name is_alias = True except NoResultFound: pass radiussettings = self.dbsession.query(self.rsm, self.asm.address, self.asm.port, self.asm.split_address, self.asm.user_map_template)\ .join(self.asm)\ .join(self.dommodel)\ .filter(self.asm.enabled == True)\ .filter(self.dommodel.status == True)\ .filter(self.dommodel.name == domain)\ .one() settings, address, port, split_address, template = radiussettings if not port: port = 1812 radclient = Client(server=address, authport=port, secret=settings.secret.encode('utf-8'), dict=Dictionary(StringIO(DICTIONARY))) if settings.timeout: radclient.timeout = settings.timeout if split_address: login = username if is_alias: identity['login'] = "******" % (username, domain) if not split_address: login = "******" % (username, domain) if (template and (USER_TEMPLATE_MAP_RE.search(template) or DOM_TEMPLATE_MAP_RE.search(template))): # domain has user template login = USER_TEMPLATE_MAP_RE.sub(username, template) login = DOM_TEMPLATE_MAP_RE.sub(domain, login) request = radclient.CreateAuthPacket(code=packet.AccessRequest, User_Name=login) request["User-Password"] = request.PwCrypt(password) reply = radclient.SendPacket(request) if reply.code == packet.AccessAccept: identity['login'] = identity['login'].lower() return identity['login'] except (KeyError, IndexError, NoResultFound, Timeout): return None return None
from pyrad.client import Client, Timeout from pyrad.dictionary import Dictionary dicts = Dictionary("/tmp/dictionaries") srv = Client(server='localhost', secret='adminsecret', dict=dicts) srv.timeout = 30 attributes = { "Alc-Subsc-ID-Str": "00:00:00:00:00:00", "Interim-Interval": 14400 } req = srv.CreateCoAPacket(**attributes) result = client.SendPacket(req) print result print result.code
self.SendReplyPacket(pkt.fd, reply) def HandleDisconnectPacket(self, pkt): print("Received an disconnect request") print("Attributes: ") for attr in pkt.keys(): print("%s: %s" % (attr, pkt[attr])) reply = self.CreateReplyPacket(pkt) # COA NAK reply.code = 45 self.SendReplyPacket(pkt.fd, reply) if __name__ == '__main__': proxyClient = Client(server="127.0.0.1", authport=11812, acctport=11813, secret=b"Kah3choteereethiejeimaeziecumi", dict=Dictionary("dictionary")) proxyClient.retries = 1 proxyClient.timeout = 500 # create server and read dictionary srv = FakeServer(authport=21812, acctport=21813,dict=dictionary.Dictionary("dictionary"), coa_enabled=False) # add clients (address, secret, name) srv.hosts["127.0.0.1"] = server.RemoteHost("127.0.0.1", b"Kah3choteereethiejeimaeziecumi", "localhost") srv.BindToAddress("0.0.0.0") # start server srv.Run()
def request(config, user, password): """ Perform a RADIUS request to a RADIUS server. The RADIUS configuration contains the IP address, the port and the secret of the RADIUS server. * config.server * config.port * config.secret * config.retries * config.timeout :param config: The RADIUS configuration :type config: RADIUSServer Database Model :param user: the radius username :param password: the radius password :return: True or False. If any error occurs, an exception is raised. """ success = False nas_identifier = get_from_config("radius.nas_identifier", "privacyIDEA") r_dict = config.dictionary or get_from_config("radius.dictfile", "/etc/privacyidea/" "dictionary") log.debug("NAS Identifier: %r, " "Dictionary: %r" % (nas_identifier, r_dict)) log.debug("constructing client object " "with server: %r, port: %r, secret: %r" % (config.server, config.port, config.secret)) srv = Client(server=config.server, authport=config.port, secret=decryptPassword(config.secret), dict=Dictionary(r_dict)) # Set retries and timeout of the client if config.timeout: srv.timeout = config.timeout if config.retries: srv.retries = config.retries req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=user.encode('ascii'), NAS_Identifier=nas_identifier.encode('ascii')) req["User-Password"] = req.PwCrypt(password) try: response = srv.SendPacket(req) if response.code == pyrad.packet.AccessAccept: log.info("Radiusserver %s granted " "access to user %s." % (config.server, user)) success = True else: log.warning("Radiusserver %s" "rejected access to user %s." % (config.server, user)) except Timeout: log.warning("Receiving timeout from remote radius server {0!s}".format(config.server)) return success
def authenticate(self, environ, identity): """authenticator""" try: if check_failed_logins(environ): return None login = identity['login'].decode('utf-8') password = identity['password'].decode('utf-8') username = login domain = None if '@' not in login: return None username, domain = login.split('@') and_clause = and_(self.domainmodel.id == self.aliasmodel.domain_id, self.aliasmodel.name == domain, self.aliasmodel.status == True) radiussettings = self.dbsession.query(self.radsettingsmodel, self.authsettingsmodel.address, self.authsettingsmodel.port, self.authsettingsmodel.split_address, self.authsettingsmodel.user_map_template, self.domainmodel.name)\ .join(self.authsettingsmodel)\ .join(self.domainmodel)\ .filter(self.authsettingsmodel.enabled == True)\ .filter(self.domainmodel.status == True)\ .filter(or_(self.domainmodel.name == domain, func._(and_clause)))\ .all() settings, address, port, split_address, template, \ domain_name = radiussettings[0] if not port: port = 1812 radclient = Client(server=address, authport=port, secret=settings.secret.encode('utf-8'), dict=Dictionary(StringIO(DICTIONARY))) if settings.timeout: radclient.timeout = settings.timeout if split_address: login = username if domain != domain_name: identity['login'] = "******" % (username, domain_name) if not split_address: login = "******" % (username, domain_name) if (template and (USER_TEMPLATE_MAP_RE.search(template) or DOM_TEMPLATE_MAP_RE.search(template))): # domain has user template login = USER_TEMPLATE_MAP_RE.sub(username, template) login = DOM_TEMPLATE_MAP_RE.sub(domain, login) request = radclient.CreateAuthPacket(code=packet.AccessRequest, User_Name=login) request["User-Password"] = request.PwCrypt(password) reply = radclient.SendPacket(request) if reply.code == packet.AccessAccept: return identity['login'] except (KeyError, IndexError, NoResultFound, Timeout): return None return None
#!/usr/bin/python from __future__ import print_function from pyrad.client import Client from pyrad.dictionary import Dictionary import socket import sys import pyrad.packet srv = Client(server="127.0.0.1",authport=21812, acctport=21813, secret=b"Kah3choteereethiejeimaeziecumi", dict=Dictionary("dictionary")) srv.retries=1 srv.timeout = 500 req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name="wichert") req['Cisco-AVPair'] = "client-mac-address=f4b5.aa95.657a" req['Cisco-AVPair'] = "remote-id-tag=000007db302f332f30" req['Cisco-AVPair'] = "dhcpv6-interface-id=12345678-ZTEGC8A18A2E" req['Cisco-AVPair'] = "dhcp-vendor-class=3902" req['NAS-Port-Id'] = "0/0/100/12.400" req['Cisco-AVPair'] = "Cisco-NAS-Port=0/0/100/12.400" req['User-Name'] = "12345678-ZTEGC8A18A2E|0/3/0" #req['User-Name'] = "12345678-ZTEGC8A18A2E|000007db302f332f30" #12345678-ZTEGC8A18A2E|0/3/0 #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"