Пример #1
0
 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)
Пример #2
0
 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)
Пример #3
0
    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)
Пример #4
0
 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)
Пример #5
0
    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)
Пример #6
0
 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()
Пример #7
0
 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()
Пример #8
0
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... "
                )
Пример #9
0
def radius_dictionary():
    global _RADIUS_DICTIONARY
    if not _RADIUS_DICTIONARY:
        fp = StringIO(dictionary.RADIUS_ATTRIBUTES)
        _RADIUS_DICTIONARY = Dictionary(fp)
        fp.close()
    return _RADIUS_DICTIONARY
Пример #10
0
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)
Пример #11
0
 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'))
Пример #12
0
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()
Пример #13
0
    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 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
Пример #15
0
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
Пример #16
0
    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
Пример #17
0
 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)
Пример #18
0
 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)
Пример #19
0
 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
Пример #20
0
 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)
Пример #21
0
 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 = []
Пример #22
0
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)
Пример #23
0
 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'))
Пример #24
0
 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
Пример #25
0
 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'))
Пример #26
0
 def __init__(self, *args):
     super(TesterWin, self).__init__(*args)
     self.running = False
     self.random_running = False
     self.testusers = {}
     self.setupUi(self)
     self.dict=Dictionary("./dictionarys/dictionary")
     self.init_testusers()
     self.settings = QtCore.QSettings( 'ToughRADIUS', 'tester' )
     self.init_config()
     self.ooline_ips = set()
Пример #27
0
 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)
Пример #28
0
 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)
Пример #29
0
 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),
     )
Пример #30
0
    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
Пример #31
0
 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
Пример #32
0
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
Пример #33
0
class TesterWin(QtGui.QMainWindow,form_class):
    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_testusers(self):
        with open("testusers.txt") as ufs:
            for line in ufs:
                if  not line or not line.strip():
                    continue
                _props = line.split(",")
                _user = dict(user_name=_props[0].strip(),passwd=_props[1].strip())
                self.testusers[_props[0]] = _user


    def init_client(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,8192000)
        self.sock.settimeout(self.timeout.value()) 

    def init_random_client(self):
        self.rsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.rsock.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,8192000)
        self.rsock.settimeout(self.timeout.value())         


    @property
    def server(self):
        return self.server_addr.text()

    @property
    def authport(self):
        return int(self.auth_port.text() or 1812)

    @property
    def acctport(self):
        return int(self.acct_port.text() or 1813)
    @property
    def authsecret(self):
        return six.b(str(self.auth_secret.text() or 'secret'))
    
    @property
    def acctsecret(self):
        return six.b(str(self.acct_secret.text() or 'secret'))

    def encode_attr(self,key,val):
        if self.dict.has_key(key):
            typ = self.dict[key].type
            if typ == 'integer' or typ == 'date':
                val = int(val)
            else:
                val = str(val)
            return val     
        else:
            self.logger("unknow attr %s"%key)                 

    def decode_attr(self,key,value):
        if self.dict.has_key(key):
            typ = self.dict[key].type
            if typ == 'string':
                return value
            return value
        else:
            self.logger("unknow attr %s"%key)              

    def logger(self,msg):
        self.log_view.append(msg)
        
    def log_packet(self,pkt):
        # self.logger(repr(pkt))
        attr_keys = pkt.keys()
        self.logger("\nRadius Packet:")
        self.logger("id:%s" % pkt.id)
        self.logger("code:%s" % pkt.code)
        self.logger("Attributes: ")        
        for attr in attr_keys:
            self.logger( ":::: %s: %s" % (attr, self.decode_attr(attr,pkt[attr][0])))      

    def get_acct_type(self):
        if self.acct_start.isChecked():
            return status_vars['start']
        elif self.acct_stop.isChecked():
            return status_vars['stop']
        elif self.acct_update.isChecked():
            return status_vars['update']    
        elif self.acct_on.isChecked():
            return status_vars['on']
        elif self.acct_off.isChecked():
            return status_vars['off']

    def build_auth_request(self):
        req = AuthPacket2(secret=self.authsecret,dict=self.dict)
        for _row in range(self.auth_attr_table.rowCount()):
            attr_name_item = self.auth_attr_table.item(_row,0)
            attr_val_item = self.auth_attr_table.item(_row,1)
            flag_item =  self.auth_attr_table.item(_row,2)
            attr_name = attr_name_item and str(attr_name_item.text())
            attr_val = attr_val_item and str(attr_val_item.text())
            flag = flag_item and flag_item.text()
            if attr_name and attr_val and flag == '1':
                val = self.encode_attr(attr_name,attr_val)
                if not val:
                    continue
                if attr_name == 'CHAP-Password':
                    req["CHAP-Password"] = req.ChapEcrypt(val)
                elif  attr_name == 'User-Password':
                    req["User-Password"] = req.PwCrypt(val)   
                else:
                    req[attr_name] = val
        return req

    def build_acct_request(self):
        req = packet.AcctPacket(dict=self.dict,secret=self.acctsecret)
        for _row in range(self.acct_attr_table.rowCount()):
            attr_name_item = self.acct_attr_table.item(_row,0)
            attr_val_item = self.acct_attr_table.item(_row,1)
            flag_item =  self.acct_attr_table.item(_row,2)
            attr_name = attr_name_item and str(attr_name_item.text())
            attr_val = attr_val_item and str(attr_val_item.text())
            flag = flag_item and flag_item.text()
            if attr_name and attr_val and flag == '1':
                val = self.encode_attr(attr_name,attr_val)
                if val :
                    req[attr_name] = val
        return req

    def sendauth(self,req):
        if self.is_debug.isChecked():
            self.logger(u"\nsend an authentication request to %s"%self.server)
            self.log_packet(req)    
        self.sock.sendto(req.RequestPacket(),(self.server,self.authport)) 
        app.processEvents()

    def sendacct(self):
        req = self.build_acct_request()
        req['Acct-Status-Type'] = self.get_acct_type()
        if  self.is_debug.isChecked():
            self.logger("\nsend an accounting request")
            self.log_packet(req)               
        self.sock.sendto(req.RequestPacket(),(self.server,self.acctport)) 
        app.processEvents()

    def random_onoff(self):
        gevent.sleep(1)  
        while self.random_running:
            app.processEvents()
            user  = self.testusers[random.choice(self.testusers.keys())]
            if not user.get("is_online"):
                authreq = self.build_auth_request()
                authreq["User-Name"] = user['user_name']
                authreq["User-Password"] = authreq.PwCrypt(user['passwd']) 
                if self.is_debug.isChecked():
                    self.logger(u"\nsend an authentication request to %s"%self.server)
                    self.log_packet(authreq)    
                self.rsock.sendto(authreq.RequestPacket(),(self.server,self.authport)) 

                _session_id = uuid.uuid4().hex
                user["session_id"] = _session_id
                acctreq = self.build_acct_request()
                acctreq["User-Name"] = user['user_name']
                acctreq["Acct-Status-Type"] = status_vars['start']
                acctreq["Acct-Session-Id"] = _session_id 
                acctreq["Acct-Session-Time"] = random.randint(1000,9999) 
                if  self.is_debug.isChecked():
                    self.logger("\nsend an accounting start request")
                    self.log_packet(acctreq)               
                self.rsock.sendto(acctreq.RequestPacket(),(self.server,self.acctport)) 
                user["is_online"] = True
            else:
                acctreq = self.build_acct_request()
                acctreq["User-Name"] = user['user_name']
                acctreq["Acct-Status-Type"] = status_vars['stop']
                acctreq["Acct-Session-Id"] = user.get("session_id")
                if  self.is_debug.isChecked():
                    self.logger("\nsend an accounting stop request")
                    self.log_packet(acctreq)               
                self.rsock.sendto(acctreq.RequestPacket(),(self.server,self.acctport)) 
                user["is_online"] = False

            gevent.sleep(random.choice(random_sleeps))


    def on_recv(self,times):
        _times = 0
        stat_time = time.time()
        while self.running:
            app.processEvents()
            if _times == times:
                break
            try:
                msg, addr = self.sock.recvfrom(8192)
                _times += 1
                self.lasttime = time.time()

                if self.lasttime - stat_time > 2:
                    self.logger("\nCurrent received %s response"%_times)
                    stat_time = self.lasttime
                if msg:
                    self.reply += 1
                    if self.is_debug.isChecked():
                        try:
                            resp = packet.Packet(packet=msg,dict=self.dict)
                            attr_keys = resp.keys()
                            self.logger("\nReceived an response:")
                            self.logger("id:%s" % resp.id)
                            self.logger("code:%s" % resp.code)
                            self.logger("Attributes: ")        
                            for attr in attr_keys:
                                self.logger( ":::: %s: %s" % (attr, self.decode_attr(attr,resp[attr][0])))  
                        except Exception as e:
                            import traceback
                            traceback.print_exc()
                            self.logger('\nerror %s'%str(e))
            except:
                break

        sectimes = self.lasttime - self.starttime
        if times > 1:
            percount = self.reply /sectimes
            self.logger("\nTotal time (sec):%s"%round(sectimes,4))
            self.logger("response total:%s"%self.reply)
            self.logger("request per second:%s"%percount)
        self.stop()

    def run(self,times):
        if self.running:
            return
        if times > 1:
            self.is_debug.setChecked(False)
            self.logger("\nTotal request:%s"%times)            
        self.send_auth_cmd.setEnabled(False) 
        self.send_acct_cmd.setEnabled(False)               
        self.running = True
        self.starttime = time.time()
        self.reply = 0
        self.lasttime = 0   
        gevent.spawn(self.on_recv,times)  

    def stop(self):
        self.running = False     
        self.send_auth_cmd.setEnabled(True) 
        self.send_acct_cmd.setEnabled(True)         

    @QtCore.pyqtSlot()
    def on_send_auth_cmd_clicked(self):
        times = self.auth_times.value()
        self.run(times)
        req = self.build_auth_request()
        for _ in xrange(times):
            app.processEvents()
            if not self.running:
                break            
            gevent.spawn(self.sendauth,req)


    @QtCore.pyqtSlot()
    def on_send_acct_cmd_clicked(self):
        times = self.acct_times.value()
        self.run(times)
        for _ in xrange(times):
            app.processEvents()
            if not self.running:
                break
            gevent.spawn(self.sendacct)

    @QtCore.pyqtSlot()
    def on_random_test_start_clicked(self):
        rand_nums = self.random_nums.value()
        if not self.random_running:
            self.log_view.clear()
            self.logger(u"即将开始随机测试")      
            self.random_running = True
            for _ in range(rand_nums):
                gevent.spawn(self.random_onoff)   
        self.random_test_start.setEnabled(False) 
        self.random_test_end.setEnabled(True) 


    @QtCore.pyqtSlot()
    def on_random_test_end_clicked(self):
        self.random_running = False  
        self.random_test_start.setEnabled(True)  
        self.random_test_end.setEnabled(False)          

    @QtCore.pyqtSlot()
    def on_clearlog_cmd_clicked(self):
        self.log_view.clear()

    def closeEvent(self, event):
        global app_running
        app_running = False
        try:
            gevent.killall(timeout=2)
        except:
            pass
        event.accept()
Пример #34
0
class TesterWin(QtGui.QMainWindow,form_class):
    def __init__(self, *args):
        super(TesterWin, self).__init__(*args)
        self.running = False
        self.random_running = False
        self.testusers = {}
        self.setupUi(self)
        self.dict=Dictionary("./dictionarys/dictionary")
        self.init_testusers()
        self.settings = QtCore.QSettings( 'ToughRADIUS', 'tester' )
        self.init_config()
        self.ooline_ips = set()
        
    def init_testusers(self):
        with open("testusers.txt") as ufs:
            for line in ufs:
                if  not line or not line.strip():
                    continue
                _props = line.split(",")
                _user = dict(user_name=_props[0].strip(),passwd=_props[1].strip())
                self.testusers[_props[0]] = _user

    def get_udp_client(self):
        rsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        rsock.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,819200)
        rsock.settimeout(self.timeout.value())
        # rsock.setblocking( 0 )
        return rsock

    def init_config(self):
        self.server_addr.setText( self.settings.value( 'server' ).toString() or "127.0.0.1" )
        self.auth_port.setText( self.settings.value( 'auth_port' ).toString() or "1812")
        self.acct_port.setText( self.settings.value( 'acct_port' ).toString() or "1813")
        self.auth_secret.setText( self.settings.value( 'auth_secret' ).toString() or "secret")
        self.acct_secret.setText( self.settings.value( 'acct_secret' ).toString() or "secret")

    @property
    def server(self):
        return self.server_addr.text()

    @property
    def authport(self):
        return int(self.auth_port.text() or 1812)

    @property
    def acctport(self):
        return int(self.acct_port.text() or 1813)
    @property
    def authsecret(self):
        return six.b(str(self.auth_secret.text() or 'secret'))
    
    @property
    def acctsecret(self):
        return six.b(str(self.acct_secret.text() or 'secret'))

    def encode_attr(self,key,val):
        if self.dict.has_key(key):
            typ = self.dict[key].type
            if typ == 'integer' or typ == 'date':
                val = int(val)
            else:
                val = str(val)
            return val     
        else:
            self.logger("unknow attr %s"%key)                 

    def decode_attr(self,key,value):
        if self.dict.has_key(key):
            typ = self.dict[key].type
            if typ == 'string':
                return value
            return value
        else:
            self.logger("unknow attr %s"%key)              

    def logger(self,msg):
        self.log_view.append(msg)
        
    def log_packet(self,pkt):
        # self.logger(repr(pkt))
        attr_keys = pkt.keys()
        self.logger("\nRadius Packet:")
        self.logger("id:%s" % pkt.id)
        self.logger("code:%s" % pkt.code)
        self.logger("Attributes: ")        
        for attr in attr_keys:
            self.logger( ":::: %s: %s" % (attr, self.decode_attr(attr,pkt[attr][0])))      

    def get_acct_type(self):
        if self.acct_start.isChecked():
            return status_vars['start']
        elif self.acct_stop.isChecked():
            return status_vars['stop']
        elif self.acct_update.isChecked():
            return status_vars['update']    
        elif self.acct_on.isChecked():
            return status_vars['on']
        elif self.acct_off.isChecked():
            return status_vars['off']

    def build_auth_request(self):
        req = AuthPacket2(secret=self.authsecret,dict=self.dict)
        for _row in range(self.auth_attr_table.rowCount()):
            attr_name_item = self.auth_attr_table.item(_row,0)
            attr_val_item = self.auth_attr_table.item(_row,1)
            flag_item =  self.auth_attr_table.item(_row,2)
            attr_name = attr_name_item and str(attr_name_item.text())
            attr_val = attr_val_item and str(attr_val_item.text())
            flag = flag_item and flag_item.text()
            if attr_name and attr_val and flag == '1':
                val = self.encode_attr(attr_name,attr_val)
                if not val:
                    continue
                if attr_name == 'CHAP-Password':
                    req["CHAP-Password"] = req.ChapEcrypt(val)
                elif  attr_name == 'User-Password':
                    req["User-Password"] = req.PwCrypt(val)   
                else:
                    req[attr_name] = val
        return req

    def build_acct_request(self):
        req = packet.AcctPacket(dict=self.dict,secret=self.acctsecret)
        for _row in range(self.acct_attr_table.rowCount()):
            attr_name_item = self.acct_attr_table.item(_row,0)
            attr_val_item = self.acct_attr_table.item(_row,1)
            flag_item =  self.acct_attr_table.item(_row,2)
            attr_name = attr_name_item and str(attr_name_item.text())
            attr_val = attr_val_item and str(attr_val_item.text())
            flag = flag_item and flag_item.text()
            if attr_name and attr_val and flag == '1':
                val = self.encode_attr(attr_name,attr_val)
                if val :
                    req[attr_name] = val
        return req

    def sendauth(self,req, que):
        if self.is_debug.isChecked():
            self.logger(u"\nsend an authentication request to %s"%self.server)
            self.log_packet(req)

        while self.running:
            sock = self.get_udp_client()
            try:
                gevent.socket.wait_write(sock.fileno(), timeout=self.timeout.value())
                sock.sendto(req.RequestPacket(), (self.server, self.authport))
                que.put_nowait('sendreq')
                gevent.socket.wait_read(sock.fileno(), timeout=self.timeout.value())
                msg, addr = sock.recvfrom(8192)
                if msg:
                    que.put_nowait(msg)
                    # gevent.sleep(0)
                    break
            except Exception as err:
                que.put_nowait(err)
                logging.error(err)
                # gevent.sleep(1)
            finally:
                try:
                    sock.close()
                except Exception as err:
                    self.logger("auth socket close error %s" % repr(err))

    def sendacct(self, que):
        req = self.build_acct_request()
        req['Acct-Status-Type'] = self.get_acct_type()
        if self.is_debug.isChecked():
            self.logger("\nsend an accounting request")
            self.log_packet(req)
        while self.running:
            sock = self.get_udp_client()
            try:
                gevent.socket.wait_write(sock.fileno(), timeout=0.9)
                sock.sendto(req.RequestPacket(), (self.server, self.acctport))
                que.put('sendreq')
                gevent.socket.wait_read(sock.fileno(), timeout=self.timeout.value())
                msg, addr = sock.recvfrom(8192)
                if msg:
                    que.put_nowait(msg)
                    # gevent.sleep(0)
                    break
            except Exception as err:
                que.put_nowait(err)
                logging.error("err")
            finally:
                try:
                    sock.close()
                except Exception as err:
                    self.logger("auth socket close error %s" % repr(err))

    def random_onoff(self,rsock):
        while self.random_running:
            try:
                user  = self.testusers[random.choice(self.testusers.keys())]
                if not user.get("is_online"):
                    authreq = self.build_auth_request()
                    authreq["User-Name"] = user['user_name']
                    authreq["User-Password"] = authreq.PwCrypt(user['passwd'])
                    if self.is_debug.isChecked():
                        self.logger(u"\nsend an authentication request to %s"%self.server)
                        self.log_packet(authreq)
                    gevent.socket.wait_write( rsock.fileno(), timeout=0.9 )
                    rsock.sendto(authreq.RequestPacket(),(self.server,self.authport))

                    ips = ipset.difference(self.ooline_ips)
                    if not ips:
                        gevent.sleep(1)
                        continue

                    _session_id = uuid.uuid4().hex
                    user["session_id"] = _session_id
                    user["ipaddr"] = random.choice(list(ips))
                    self.ooline_ips.add(user["ipaddr"])
                    acctreq = self.build_acct_request()
                    acctreq["User-Name"] = user['user_name']
                    acctreq["Acct-Status-Type"] = status_vars['start']
                    acctreq["Acct-Session-Id"] = _session_id
                    acctreq["Acct-Session-Time"] = random.randint(1000,9999)
                    acctreq["Framed-IP-Address"] = user["ipaddr"]
                    if  self.is_debug.isChecked():
                        self.logger("\nsend an accounting start request")
                        self.log_packet(acctreq)
                    gevent.socket.wait_write( rsock.fileno(), timeout=0.9 )
                    rsock.sendto(acctreq.RequestPacket(),(self.server,self.acctport))
                    user["is_online"] = True
                else:
                    acctreq = self.build_acct_request()
                    acctreq["User-Name"] = user['user_name']
                    acctreq["Acct-Status-Type"] = status_vars['stop']
                    acctreq["Acct-Session-Id"] = user.get("session_id")
                    acctreq["Framed-IP-Address"] = user.get("ipaddr")
                    if  self.is_debug.isChecked():
                        self.logger("\nsend an accounting stop request")
                        self.log_packet(acctreq)
                    gevent.socket.wait_write( rsock.fileno(), timeout=0.9 )
                    rsock.sendto(acctreq.RequestPacket(),(self.server,self.acctport))
                    user["is_online"] = False
                    self.ooline_ips.remove(user.get("ipaddr"))
                gevent.sleep( 0 )
            except Exception as err:
                self.logger( "\nsend radius error %s" % repr(err) )
                gevent.sleep( 0 )
            finally:
                gevent.sleep(random.choice((0.1,0.2,0.3,0.4,0.5,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.0,1,2,3,4,5,6,7,8,9)))


    def on_random_recv(self,rsock):
        timeout = self.timeout.value()
        gevent.sleep( 0.5)
        while self.random_running:
            try:
                gevent.socket.wait_read( rsock.fileno(), timeout=timeout )
                msg, addr = rsock.recvfrom(8192)
                if msg:
                    if self.is_debug.isChecked():
                        try:
                            resp = packet.Packet(packet=msg,dict=self.dict)
                            attr_keys = resp.keys()
                            self.logger("\nReceived an response:")
                            self.logger("id:%s" % resp.id)
                            self.logger("code:%s" % resp.code)
                            self.logger("Attributes: ")
                            for attr in attr_keys:
                                self.logger( ":::: %s: %s" % (attr, self.decode_attr(attr,resp[attr][0])))
                        except Exception as e:
                            logging.exception( "parse packet error %s"%repr(e) )
                            self.logger('\nerror %s'%repr(e))
                gevent.sleep( 0 )
            except Exception as err:
                logging.exception("recv random error ")
                self.logger( "recv random error %s"% repr(err))
                gevent.sleep( 0 )
                continue

        try:
            rsock.close()
        except Exception as err:
            self.logger("random socket close error %s" % repr(err))


    def on_stat(self,que,times):
        _init_time = time.time()
        starttime = _init_time
        stat_time = _init_time
        lasttime = _init_time
        reply = 0
        _sendreqs = 0
        _errors = 0
        _timeouts = 0
        while self.running:
            try:
                if reply == times:
                    break
                msg = que.get()
                is_radius_reply = False
                if isinstance(msg, socket.timeout):
                    _timeouts += 1
                elif isinstance(msg,Exception):
                    _errors += 1
                elif msg == 'sendreq':
                    _sendreqs += 1
                else:
                    is_radius_reply = True
                    reply += 1

                lasttime = time.time()
                if lasttime - stat_time >= 3:
                    stat_time = lasttime
                    sectimes = lasttime - starttime
                    percount = reply / sectimes
                    self.logger("\n\nCast time total (sec):%s" % round(sectimes, 4))
                    self.logger("Send requests total:%s" % _sendreqs)
                    self.logger("Received response total:%s" % reply)
                    self.logger("Send timeouts:%s" % _timeouts)
                    self.logger("Send errors:%s" % _errors)
                    self.logger("Request per second:%s" % int(percount))

                # print logging
                try:
                    if self.is_debug.isChecked() and is_radius_reply:
                        resp = packet.Packet( packet=msg, dict=self.dict)
                        attr_keys = resp.keys()
                        self.logger( "\nReceived an response:" )
                        self.logger( "id:%s" % resp.id )
                        self.logger( "code:%s" % resp.code )
                        self.logger( "Attributes: " )
                        for attr in attr_keys:
                            self.logger( ":::: %s: %s" % (attr, self.decode_attr( attr, resp[attr][0] )) )
                except Exception as e:
                    self.logger( '\nparse resp error %s' % repr( e ) )
            except Exception as err:
                _errors += 1
                self.logger( '\nstat error %s' % repr( err ) )

            gevent.sleep( 0 )


        sectimes = lasttime - starttime
        if times > 1:
            percount = reply / sectimes
            self.logger("\n\nCast time total (sec):%s" % round(sectimes, 4))
            self.logger("Send requests total:%s" % _sendreqs)
            self.logger("Received response total:%s" % reply)
            self.logger("Send timeouts:%s" % _timeouts)
            self.logger("Send errors:%s" % _errors)
            self.logger("Request per second:%s" % int(percount))

        self.stop()

    def run(self,statque,times):
        if self.running:
            return

        if times > 1:
            self.is_debug.setChecked(False)
            self.logger("\nTotal request:%s"%times)

        self.send_auth_cmd.setEnabled(False) 
        self.send_acct_cmd.setEnabled(False)               
        self.running = True
        pool.spawn(self.on_stat,statque,times)

    def stop(self):
        self.running = False     
        self.send_auth_cmd.setEnabled(True) 
        self.send_acct_cmd.setEnabled(True)
        self.logger("\n\nStop Testing\n\n")


    @QtCore.pyqtSlot()
    def on_stop_auth_clicked(self):
        self.stop()

    @QtCore.pyqtSlot()
    def on_stop_acct_clicked(self):
        self.stop()

    @QtCore.pyqtSlot()
    def on_save_cmd_clicked(self):
        self.settings.setValue('server',self.server)
        self.settings.setValue('auth_port',self.authport)
        self.settings.setValue('acct_port',self.acctport)
        self.settings.setValue('auth_secret',self.authsecret)
        self.settings.setValue('acct_secret',self.acctsecret)
        self.settings.sync()


    @QtCore.pyqtSlot()
    def on_send_auth_cmd_clicked(self):
        from itertools import cycle
        times = self.auth_times.value()
        statque = Queue()
        self.run(statque,times)
        req = self.build_auth_request()
        for _ in xrange(times):
            app.processEvents()
            if not self.running:
                break
            pool.spawn(self.sendauth, req, statque)


    @QtCore.pyqtSlot()
    def on_send_acct_cmd_clicked(self):
        from itertools import cycle
        times = self.acct_times.value()
        statque = Queue()
        self.run(statque,times)
        for _ in xrange(times):
            app.processEvents()
            if not self.running:
                break
            pool.spawn(self.sendacct, statque)

    @QtCore.pyqtSlot()
    def on_random_test_start_clicked(self):
        rand_nums = self.random_nums.value()
        if not self.random_running:
            self.log_view.clear()
            self.logger(u"即将开始随机测试")      
            self.random_running = True
            for _ in range(rand_nums):
                rsock = self.get_udp_client()
                gevent.spawn(self.random_onoff,rsock)
                gevent.spawn(self.on_random_recv,rsock)
        self.random_test_start.setEnabled(False)
        self.random_test_end.setEnabled(True) 


    @QtCore.pyqtSlot()
    def on_random_test_end_clicked(self):
        self.random_running = False  
        self.random_test_start.setEnabled(True)  
        self.random_test_end.setEnabled(False)          

    @QtCore.pyqtSlot()
    def on_clearlog_cmd_clicked(self):
        self.log_view.clear()

    def closeEvent(self, event):
        global app_running
        app_running = False
        try:
            gevent.killall(timeout=2)
        except:
            pass
        event.accept()