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 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 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 _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
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
#!/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"