How to use the pyrad.dictionary function in pyrad

To help you get started, we’ve selected a few pyrad examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github greearb / hostap-ct / tests / hwsim / test_eap_proto.py View on Github external
self.ctx = {}

            while not t_stop.is_set():
                for (fd, event) in self._poll.poll(1000):
                    if event == select.POLLIN:
                        try:
                            fdo = self._fdmap[fd]
                            self._ProcessInput(fdo)
                        except pyrad.server.ServerPacketError as err:
                            logger.info("pyrad server dropping packet: " + str(err))
                        except pyrad.packet.PacketError as err:
                            logger.info("pyrad server received invalid packet: " + str(err))
                    else:
                        logger.error("Unexpected event in pyrad server main loop")

    srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
                     authport=18138, acctport=18139)
    srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
                                                     "radius",
                                                     "localhost")
    srv.BindToAddress("")
    t_stop = threading.Event()
    t = threading.Thread(target=run_pyrad_server, args=(srv, t_stop, eap_handler))
    t.start()

    return { 'srv': srv, 'stop': t_stop, 'thread': t }
github greearb / hostap-ct / tests / hwsim / test_radius.py View on Github external
self.t_events = t_events

            while not t_events['stop'].is_set():
                for (fd, event) in self._poll.poll(1000):
                    if event == select.POLLIN:
                        try:
                            fdo = self._fdmap[fd]
                            self._ProcessInput(fdo)
                        except pyrad.server.ServerPacketError as err:
                            logger.info("pyrad server dropping packet: " + str(err))
                        except pyrad.packet.PacketError as err:
                            logger.info("pyrad server received invalid packet: " + str(err))
                    else:
                        logger.error("Unexpected event in pyrad server main loop")

    srv = TestServer(dict=pyrad.dictionary.Dictionary("dictionary.radius"),
                     authport=18138, acctport=18139)
    srv.hosts["127.0.0.1"] = pyrad.server.RemoteHost("127.0.0.1",
                                                     b"radius",
                                                     "localhost")
    srv.BindToAddress("")
    t_events = {}
    t_events['stop'] = threading.Event()
    t_events['psk'] = psk
    t_events['invalid_code'] = invalid_code
    t_events['acct_interim_interval'] = acct_interim_interval
    t_events['session_timeout'] = session_timeout
    t_events['reject'] = reject
    t = threading.Thread(target=run_pyrad_server, args=(srv, t_events))
    t.start()
    return t, t_events
github greearb / hostap-ct / tests / hwsim / test_radius.py View on Github external
def test_radius_server_failures(dev, apdev):
    """RADIUS server failure cases"""
    try:
        import pyrad.client
        import pyrad.packet
        import pyrad.dictionary
    except ImportError:
        raise HwsimSkip("No pyrad modules available")

    dict = pyrad.dictionary.Dictionary("dictionary.radius")
    client = pyrad.client.Client(server="127.0.0.1", authport=1812,
                                 secret=b"radius", dict=dict)
    client.retries = 1
    client.timeout = 1

    # unexpected State
    req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest,
                                  User_Name="foo")
    req['State'] = b'foo-state'
    add_message_auth(req)
    reply = client.SendPacket(req)
    if reply.code != pyrad.packet.AccessReject:
        raise Exception("Unexpected RADIUS response code " + str(reply.code))

    # no EAP-Message
    req = client.CreateAuthPacket(code=pyrad.packet.AccessRequest,
github AGProjects / mediaproxy / mediaproxy / interfaces / accounting / radius.py View on Github external
secrets = dict(line.rstrip('\n').split(None, 1) for line in open(config['servers']) if len(line.split(None, 1)) == 2 and not line.startswith('#'))
            server = config['acctserver']
            try:
                server, acctport = server.split(':')
                acctport = int(acctport)
            except ValueError:
                acctport = 1813
            secret = secrets[server]
            dicts = [RadiusDictionaryFile(config['dictionary'])]
            if RadiusConfig.additional_dictionary:
                additional_dictionary = process.configuration.file(RadiusConfig.additional_dictionary)
                if additional_dictionary:
                    dicts.append(RadiusDictionaryFile(additional_dictionary))
                else:
                    log.warning('Could not load additional RADIUS dictionary file: %r' % RadiusConfig.additional_dictionary)
            raddict = pyrad.dictionary.Dictionary(*dicts)
            timeout = int(config['radius_timeout'])
            retries = int(config['radius_retries'])
        except Exception:
            log.critical('cannot read the RADIUS configuration file')
            raise
        pyrad.client.Client.__init__(self, server, 1812, acctport, 3799, secret, raddict)
        self.timeout = timeout
        self.retries = retries
        if 'bindaddr' in config and config['bindaddr'] != '*':
            self.bind((config['bindaddr'], 0))
        EventQueue.__init__(self, self.do_accounting)
github pyradius / pyrad / example / coa.py View on Github external
import sys

if len(sys.argv) != 3:
  print ("usage: coa.py {coa|dis} daemon-1234")
  sys.exit(1)

ADDRESS = "127.0.0.1"
SECRET = b"Kah3choteereethiejeimaeziecumi"
ATTRIBUTES = {
    "Acct-Session-Id": "1337"
}

ATTRIBUTES["NAS-Identifier"] = sys.argv[2]

# create coa client
client = Client(server=ADDRESS, secret=SECRET, dict=dictionary.Dictionary("dictionary"))

# set coa timeout
client.timeout = 30

# create coa request packet
attributes = {k.replace("-", "_"): ATTRIBUTES[k] for k in ATTRIBUTES}

if sys.argv[1] == "coa":
    # create coa request
    request = client.CreateCoAPacket(**attributes)
elif sys.argv[1] == "dis":
    # create disconnect request
    request = client.CreateCoAPacket(code=packet.DisconnectRequest, **attributes)
else:
  sys.exit(1)
github pyradius / pyrad / example / server.py View on Github external
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__':

    # create server and read dictionary
    srv = FakeServer(dict=dictionary.Dictionary("dictionary"), coa_enabled=True)

    # add clients (address, secret, name)
    srv.hosts["127.0.0.1"] = server.RemoteHost("127.0.0.1", b"Kah3choteereethiejeimaeziecumi", "localhost")
    srv.BindToAddress("")

    # start server
    srv.Run()
github pyradius / pyrad / pyrad / curved.py View on Github external
    def __init__(self, hosts={}, dict=dictionary.Dictionary()):
        host.Host.__init__(self, dict=dict)
        self.hosts = hosts
github jamiesun / PyRadius / radiusd / server.py View on Github external
    def __init__(self, address,nases={},dict=dictionary.Dictionary("dictionary")):
        DatagramServer.__init__(self,address)
        self.nases = nases
        self.address = address
        self.dict = dict
        self.start()
        self.socket.setsockopt(socket.SOL_SOCKET,
            socket.SO_RCVBUF,10240000)
github pyradius / pyrad / pyrad / curved.py View on Github external
    def __init__(self, hosts={}, dict=dictionary.Dictionary()):
        host.Host.__init__(self, dict=dict)
        self.hosts = hosts
github krb5 / krb5 / src / lib / krad / t_daemon.py View on Github external
for key in pkt.keys():
            if key == "User-Password":
                passwd = map(pkt.PwDecrypt, pkt[key])

        reply = self.CreateReplyPacket(pkt)
        if passwd == ['accept']:
            reply.code = packet.AccessAccept
        else:
            reply.code = packet.AccessReject
        self.SendReplyPacket(pkt.fd, reply)

srv = TestServer(addresses=["localhost"],
                 hosts={"127.0.0.1":
                        server.RemoteHost("127.0.0.1", "foo", "localhost")},
                 dict=dictionary.Dictionary(StringIO.StringIO(DICTIONARY)))

# Write a sentinel character to let the parent process know we're listening.
sys.stdout.write("~")
sys.stdout.flush()

srv.Run()