Code Monkey home page Code Monkey logo

pyrad's Introduction

image

image

image

image

image

Documentation Status

image

Introduction

pyrad is an implementation of a RADIUS client/server as described in RFC2865. It takes care of all the details like building RADIUS packets, sending them and decoding responses.

Here is an example of doing a authentication request:

from __future__ import print_function
from pyrad.client import Client
from pyrad.dictionary import Dictionary
import pyrad.packet

srv = Client(server="localhost", secret=b"Kah3choteereethiejeimaeziecumi",
             dict=Dictionary("dictionary"))

# create request
req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest,
                           User_Name="wichert", NAS_Identifier="localhost")
req["User-Password"] = req.PwCrypt("password")

# send request
reply = srv.SendPacket(req)

if reply.code == pyrad.packet.AccessAccept:
    print("access accepted")
else:
    print("access denied")

print("Attributes returned by server:")
for i in reply.keys():
    print("%s: %s" % (i, reply[i]))

Requirements & Installation

pyrad requires Python 2.7, or Python 3.6 or later

Installing is simple; pyrad uses the standard distutils system for installing Python modules:

python setup.py install

Author, Copyright, Availability

pyrad was written by Wichert Akkerman <[email protected]> and is maintained by Christian Giese (GIC-de) and Istvan Ruzman (Istvan91).

This project is licensed under a BSD license.

Copyright and license information can be found in the LICENSE.txt file.

The current version and documentation can be found on pypi: https://pypi.org/project/pyrad/

Bugs and wishes can be submitted in the pyrad issue tracker on github: https://github.com/pyradius/pyrad/issues

pyrad's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyrad's Issues

pyrad testPktEncodeAttributes test fails when run against Python 3.6+

This is the result of python3.6 setup.py test

======================================================================
FAIL: testPktEncodeAttributes (pyrad.tests.testPacket.PacketTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/sgallagh/workspace/fedora/python-pyrad/pyrad-2.1/pyrad/tests/testPacket.py", line 199, in testPktEncodeAttributes
    six.b('\x1a\x0d\x00\x00\x00\x01\x02\x07value\x01\x07value'))
AssertionError: b'\x01\x07value\x1a\r\x00\x00\x00\x01\x02\x07value' != b'\x1a\r\x00\x00\x00\x01\x02\x07value\x01\x07value'

----------------------------------------------------------------------
Ran 179 tests in 9.066s

FAILED (failures=1)
Test failed: <unittest.runner.TextTestResult run=179 errors=0 failures=1>
error: Test failed: <unittest.runner.TextTestResult run=179 errors=0 failures=1>
error: Bad exit status from /var/tmp/rpm-tmp.OGPFww (%check)
    Bad exit status from /var/tmp/rpm-tmp.OGPFww (%check)

This test passed previously when using python 3.5, so I presume something changed in the encoding handling. I'm also using python-six 1.11.0, which is the latest upstream release.

Server bug, will only run on 127.0.0.1

Whenever I try to run a server using the example, it will only work on 127.0.0.1.

Both 0.0.0.0 and any given interfaces IP don't work, the server starts and runs without error. You can even see it running on port 1812 in netstat, but radclient simple times out. If I set it back to 127.0.0.1, radclient works as expected.

srv=FakeServer(dict=dictionary.Dictionary("dictionary"))
srv.hosts["0.0.0.0"]=server.RemoteHost("0.0.0.0",
"sharedsecret",
"test")
srv.BindToAddress("")
srv.Run()

send several instances of attribute with different tags failed

I'm trying to send several instances of attribute with different tags (using tagged attribute):

srv = Client(server=radius, secret=radius_secret, dict=Dictionary("dictionary"))
req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name=username)
req["User-Password"] = req.PwCrypt(password)
req["ERX-Service-Activate:3"] = 'test3'
req["ERX-Service-Activate:8"] = 'test8'
reply = srv.SendPacket(req)

But only one (the last) instance is sending to RADIUS server:

Received Access-Request Id 90 from 127.0.0.1:50116 to 127.0.0.1:1812 length 59
User-Name = 'user1'
User-Password = 'test'
ERX-Service-Activate:8 = 'test8'

pyrad + python3.6

Good afternoon. I used your wonderful library in python 2.7.It's time to move to 3.6 and asyncio and ran into this problem.


import pyrad.packet
from pyrad.dictionary import Dictionary
from pyrad.client import Client

srv = Client(
    server='localhost',
    secret=b'test',
    dict=Dictionary('/opt//dictionary')
)

req = srv.CreateAuthPacket(
    code=pyrad.packet.AccessRequest,
    User_Name='xxxxx',
)
req["User-Password"] = req.PwCrypt('yyyyy')
req['NAS-Identifier'] = 'node'
req['NAS-IP-Address'] = '0.0.0.0'

reply = srv.SendPacket(req)

'''
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/pyrad/client.py", line 173, in SendPacket
    return self._SendPacket(pkt, self.authport)
  File "/usr/local/lib/python3.6/dist-packages/pyrad/client.py", line 137, in _SendPacket
    self._socket.sendto(pkt.RequestPacket(), (self.server, port))
socket.gaierror: [Errno -2] Name or service not known

'''
Tell me please what this means, since the conclusion about anything does not tell me

How to add vendor-specific attribute to a packet

Hello, Thanks for implementing this pyrad as opensource.
I am trying to test a radius server by using this pyrad as a client and I am looking for how to include VSA attributes in a packet.

Can you please give an example of how to add vendor-specific attribute to a packet ?
Tried things like this but did not work:
req['Vendor-Specific]['Cisco/Cisco-AVPair'] = "someattrvalue"
req['Vendor-Specific]['Cisco:Cisco-AVPair'] = "someattrvalue"
req['Cisco:Cisco-AVPair'] = "someattrvalue"
req['Cisco/Cisco-AVPair'] = "someattrvalue"

[PATCH] Various problems with freeradius 2.1.x dictionary

Using pyrad-2.0 (from easy_install), pointing it at freeradius 2.1.10's dictionary collection:

>>> from pyrad.dictionary import Dictionary
>>> Dictionary("/etc/freeradius/dictionary")
...
ParseError: dictionary.rfc5904(16): Parse error: Illegal type: short
>>> 

I hacked it about to add short and byte. This leaves two incompatible dictionary files: pyrad doesn't like <type> array (dictionary.dhcp) and there are various things in dictionary.wimax. such as VENDOR ... format=1,1,c, signed, flv and combo-ip (whatever that is)

I knocked together some quick patches (no test cases) and they're in the following branch:
https://github.com/candlerb/pyrad/tree/candlerb%2Fshortbyte

It now at least reads the dictionary, even if it doesn't actually make use of attributes like 'array'

How to support message-authenticator

I want to know if message-authenticator attribute is supported and what is the way to get this populated with shared secret as the parameter ?

VerifyAcctRequest documentation is misleading

VerifyAcctRequest doc says it returns True if verification failed:
https://github.com/wichert/pyrad/blob/master/pyrad/packet.py#L490

This seems contrary to expectations, and I think contrary to the test assertions:
https://github.com/wichert/pyrad/blob/master/pyrad/tests/testPacket.py#L393

So it seems the doc is wrong? I can submit a PR for it, but wanted to ask first since a doc change might sneak past without breaking any tests. Maybe I'm reading the code wrong?

Password authentication rejected in the Mininet Environment

Hello dear friend, how are you? I am trying to understand what's happening with my code, but I didnt understand why this error is occuring..

Anyway, I am running the pyrad code (.py) in a mininet environment. In the first case, I was able to authenticate my host but, in the second, with the same code, there is a difference in the password authentication (something related to encrypt).

1) First case (ok - pyrad is running ok)
Host 1 (h1) -> Radius Server

At the same h1, I tried to authenticate with my python code and everything works perfectly
1 - ok

2) Second case (nok)
Host 1 (h1) -> Radius Server
Host 2 (h2) -> Trying to authenticate in H1

2

Basically the only difference, comparing the test 1 with test 2, was that: in the test 1, both code and radius server instance was running in the same host. On the other hand, in the test 2, host 1 is running my radius server instance and host 2 is trying to authenticate in host 1.

Ps: I am developing a SDN application based on Rytu controller. I can assure that the conectivity between host1 and host 2 is ok.

I am also attaching my pyrad code here ->
auth.zip

I am looking forward your answer and let me know if you need something else.

Thank you!

Best regards,

Sincerely,
Antonio

has_tag attribute implementation

How can I send a query whose attributes contain the has_tag, as defined in RFC2868.

example:
User-Name := "redback"
Service-Name:1 += "RSE-SVC-DIDNTPAY"
Service-Action:1 += 1
Service-Parameter:1 += "InterimTime=900"
Service-Name:2 += "RSE-SVC-INET"
Service-Action:2 += 1)
Service-Parameter:2 += "InterimTime=900 Rate=1024"

thanks

CoA request not implemented

I'm trying to build small pyrad based application for sending CoA (RFC5176) requests to Cisco ASR.

This is my code:

    import pyrad.packet
    from pyrad.client import Client
    from pyrad.dictionary import Dictionary

    srv = Client(server="172.16.x.x", secret="secret", dict=Dictionary("standard", "cisco"))

    req = srv.CreatePacket(code=pyrad.packet.CoARequest, User_Name="errno", Cisco_Account_Info="S172.16.x.x", Cisco_AVPair="subscriber:command=account-logoff")

    reply = srv.SendPacket(req)

    if reply.code == pyrad.packet.CoAACK:
        print "Ok"
    else:
        print "Fail"

When I run it, traceback appears:

Traceback (most recent call last):
  File "rad-comand.py", line 9, in <module>
    reply = srv.SendPacket(req)
  File "/usr/local/lib/python2.6/dist-packages/pyrad/client.py", line 161, in SendPacket
    return self._SendPacket(pkt, self.acctport)
  File "/usr/local/lib/python2.6/dist-packages/pyrad/client.py", line 123, in _SendPacket
    self._socket.sendto(pkt.RequestPacket(), (self.server, port))
AttributeError: 'Packet' object has no attribute 'RequestPacket'

I had fast look through source and found than 'RequestPacket' method implemented only for AcctPacket and AuthPacket, what class must be used for CoA request (packet code 43)?

I'm using latest pyrad-2.0 from PyPi.

Cannnot send Status requests

Hello,

I am trying to use pyrad to build a tiny script to get statistics about my freeradus server. Freeradius server since version 2.x implements a "status server" that allow one to gather such statistcs using radius request (Status-Server). So I wrote the code bellow:

import pyrad.packet
from pyrad.client import Client
from pyrad.dictionary import Dictionary
dicts=Dictionary("/tmp/dictionaries")
srv=Client(server='localhost',authport=18121,secret='adminsecret',dict=dicts)
req=srv.CreatePacket(code=pyrad.packet.StatusServer)
req.AddAttribute("FreeRADIUS-Statistics-Type", "Authentication")
req.AddAttribute("Message-Authenticator", req.CreateAuthenticator())
reply=srv.SendPacket(req)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/pymodules/python2.7/pyrad/client.py", line 161, in SendPacket
    return self._SendPacket(pkt, self.acctport)
  File "/usr/lib/pymodules/python2.7/pyrad/client.py", line 123, in _SendPacket
    self._socket.sendto(pkt.RequestPacket(), (self.server, port))
AttributeError: Packet instance has no attribute 'RequestPacket'

If I try to use CreatAuthPacket instead, then freeradius complains about an invalid message-authenticator.

A similat request with radclient (which support status requests) works.

Pyrad client ignore timeout for accounting packets

Got following issue.

self.RadServer = RadiusClient(server=self.server, secret=self.serversecret,
                                      dict=RadiusDictionary(self.radiusdictpath))
self.RadServer.SendPacket(RadRequest) 

for accounting packets ignore timeout variable. If server not reply faster than 10 ms Pyrad send accounting request again.
i tried different self.RadServer.timeout values without any result

Python3 bytecompiling error

Hi,

I'm maintaining this package in Fedora, something not correct now:

Bytecompiling .py files below /home/rpmaker/rpmbuild/BUILDROOT/python-pyrad-2.0-1.fc20.i386/usr/lib/python2.7/ using /usr/bin/python2.7
Bytecompiling .py files below /home/rpmaker/rpmbuild/BUILDROOT/python-pyrad-2.0-1.fc20.i386/usr/lib/python3.3/ using /usr/bin/python3.3
*** Error compiling '/home/rpmaker/rpmbuild/BUILDROOT/python-pyrad-2.0-1.fc20.i386/usr/lib/python3.3/site-packages/pyrad/curved.py'...
File "/usr/lib/python3.3/site-packages/pyrad/curved.py", line 38
def datagramReceived(self, datagram, (host, port)):
^
SyntaxError: invalid syntax

error: Bad exit status from /var/tmp/rpm-tmp.XQLy85 (%install)

Server bug, will only run on 127.0.0.1

Whenever I try to run a server using the example, it will only work on 127.0.0.1.

Both 0.0.0.0 and any given interfaces IP don't work, the server starts and runs without error. You can even see it running on port 1812 in netstat, but radclient simple times out. If I set it back to 127.0.0.1, radclient works as expected.

srv=FakeServer(dict=dictionary.Dictionary("dictionary"))
srv.hosts["0.0.0.0"]=server.RemoteHost("0.0.0.0",
"sharedsecret",
"test")
srv.BindToAddress("")
srv.Run()

EAP Support

Hi.
It is possible to use pyrad as a client for extended types of authentication such a EAP-MD5, EAP-GTC,etc.?

pyrad fails on Access-Accept packet with encrypted Tunnel-Password Attribute

If the Access-Accept packet contains an encrypted attribute such as "Tunnel-Password" it fails deconding the encrypted reply password:

python radiustest.py

access accepted
Attributes returned by server:
Reply-Message: [u'Authentication successful']
Traceback (most recent call last):
File "radiustest.py", line 29, in
print "%s: %s" % (i, reply[i])
File "/usr/lib/python2.7/site-packages/pyrad/packet.py", line 173, in getitem
res.append(self._DecodeValue(attr, v))
File "/usr/lib/python2.7/site-packages/pyrad/packet.py", line 114, in _DecodeValue
return tools.DecodeAttr(attr.type, value)
File "/usr/lib/python2.7/site-packages/pyrad/tools.py", line 79, in DecodeAttr
return DecodeString(value)
File "/usr/lib/python2.7/site-packages/pyrad/tools.py", line 43, in DecodeString
return str.decode('utf-8')
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x94 in position 1: invalid start byte

tagged attributes support

Does pyrad support tagged attributes? If yes, can somebody please share example how to use / parse them?

I'm working on client application and RADIUS server is replying with several tagged instances of attribute (tag=2 and tag=5):
ERX-Service-Activate: [u'\x02INTERNET(1000000,1000000)', u'\x05TEST']

From server side:
Sending Access-Accept Id 137 from 127.0.0.1:1812 to 127.0.0.1:43556
Framed-IP-Address = 1.2.3.4
ERX-Service-Activate:2 = 'INTERNET(1000000,1000000)'
ERX-Service-Activate:5 = 'TEST'

Thanks!

how to implement chap encryption

I use the following code, but failed, and Server is the same code

class AuthPacket2(AuthPacket):
    def __init__(self, code=AccessRequest, id=None, secret=six.b(''),
            authenticator=None, **attributes):
        AuthPacket.__init__(self, code, id, secret, authenticator, **attributes)   

def get_passwd(self):
    try:return self.PwDecrypt(self.get(2)[0])
    except:return None        

def get_chappwd(self):
    try:return tools.DecodeString(self.get(3)[0])
    except:return None    

def encrypt_chap(self,password):
    if not self.authenticator:
        self.authenticator = self.CreateAuthenticator()
    if not self.id:
        self.id = self.CreateID()
    if isinstance(password, six.text_type):
        password = password.encode('utf-8')
    return md5_constructor("%s%s%s"%(self.id,password,self.authenticator)).digest()        

def is_valid_pwd(self,userpwd):
    if not self.get_chappwd():
        pwd = self.get_passwd()
        return pwd == userpwd
    else:
        return self.encrypt_chap(userpwd) == self.get_chappwd()

client code
server code

Radius Client isn't working PwCrypt not defined in the Client Class.

Hi I am trying to run the client following the documentation.
It looks like the PwCrypt function is not defined in the pyrad.client.Client.
I am receiving the errors below, the code is:
Please advice if things changed on how to create a password using PwCrypt.

create request

req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest,
User_Name="wichert", NAS_Identifier="localhost")
req["User-Password"] = req.PwCrypt("password")

/scripts$ ./clientradius.py
Traceback (most recent call last):
File "./clientradius.py", line 16, in
req["User-Password"] = req.PwCrypt("password")
File "build/bdist.linux-i686/egg/pyrad/packet.py", line 189, in setitem
File "build/bdist.linux-i686/egg/pyrad/packet.py", line 126, in _EncodeKeyValues
KeyError: 'User-Password'

pyrad is not unicode-aware

I've been using pyrad to authenticate against RSA Auth Manager RADIUS and had a question. I've got a simple test script that works at the command-line just fine. However, when I take the exact same code and put it inside a web.py script under Apache I get a UnicodeDecodeError trying to encode attributes during authentication:

File "/usr/lib/pymodules/python2.6/pyrad/packet.py", line 290, in _PktEncodeAttributes
result+=self._PktEncodeAttribute(code, data)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xaf in position 2: ordinal not in range(128)

If I change this code in packet.py to coerce the return from _PktEncodeAttribute to a string like this it suppresses the error:

     def _PktEncodeAttributes(self):
         result=""
         for (code, datalst) in self.items():
             for data in datalst:
                 result+=str(self._PktEncodeAttribute(code, data))

Rather than simply make a change without understanding what I'm actually doing to the RADIUS packet, I figured I'd run it by you first. Is there a better way to handle this error?

Thanks!

FTBFS with python-six >= 1.11.0

Hi,

rharwood@seton:~/pyrad$ nosetests3
.............................................................................................................................F.....................................................
======================================================================
FAIL: testPktEncodeAttributes (pyrad.tests.testPacket.PacketTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/bos/rharwood/pyrad/pyrad/tests/testPacket.py", line 199, in testPktEncodeAttributes
    six.b('\x1a\x0d\x00\x00\x00\x01\x02\x07value\x01\x07value'))
AssertionError: b'\x01\x07value\x1a\r\x00\x00\x00\x01\x02\x07value' != b'\x1a\r\x00\x00\x00\x01\x02\x07value\x01\x07value'

----------------------------------------------------------------------
Ran 179 tests in 9.085s

FAILED (failures=1)
rharwood@seton:~/pyrad$ 

Verified broken with both Debian's python-six-1.11.0-1 and Fedora's python3-six-1.11.0-1.fc28.

Decode raises struct.error when dictionary has a different datatyle

Hi!
_DecodeValue in packet.py fails with struct.error when in a dictionary is specified an invalid datatype or when the value is different from what expected.

Either _DecodeValue or DecodeAttr in tools.py should trap this with a try/except.

Here's the trace ofthe error:

File "/usr/local/lib/python2.6/dist-packages/pyrad-1.2-py2.6.egg/pyrad/server.py", line 230, in _ProcessInput
self._HandleAuthPacket(pkt)
File "/srv/otp/lib/otpserver.py", line 140, in _HandleAuthPacket
self.HandleAuthPacket(pkt, realm)
File "/srv/otp/lib/otpserver.py", line 167, in HandleAuthPacket
self.logger.debug("%s: %s" % (attr, pkt[attr]))
File "/usr/local/lib/python2.6/dist-packages/pyrad-1.2-py2.6.egg/pyrad/packet.py", line 178, in getitem
res.append(self._DecodeValue(attr, v))
File "/usr/local/lib/python2.6/dist-packages/pyrad-1.2-py2.6.egg/pyrad/packet.py", line 109, in _DecodeValue
return tools.DecodeAttr(attr.type, value)
File "/usr/local/lib/python2.6/dist-packages/pyrad-1.2-py2.6.egg/pyrad/tools.py", line 69, in DecodeAttr
return DecodeInteger(value)
File "/usr/local/lib/python2.6/dist-packages/pyrad-1.2-py2.6.egg/pyrad/tools.py", line 43, in DecodeInteger
return (struct.unpack("!I", num))[0]
struct.error: unpack requires a string argument of length 4

Thank you,
Giuseppe

Please release a new version

Hello,

It has been almost three years since the merge of #18 and it has still not been in a release. We depend on the fixed behavior in krb5. Could you please release a new version?

Thanks!

pyrad seems to ignore $INCLUDE

Hi,

My primary dictionary has a $INCLUDE and the secondary file is in the same directory as the primary. Pyrad does not seem to be loading the secondary dictionary?

Thanks,
Yusuf

Round Robin with several radius servers

Are there any plans to support round robin in the client request?

When creating a client, I could pass the RADIUS server list, assuming that both RADIUS servers have the same secret and port

srv = Client(server=[server1, server2],
                    authport=port,
                     secret=decryptPassword(secret),
                     dict=Dictionary(r_dict))

Then it would be no problem to create the Auth Package:

req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest,
                                   User_Name=user.encode('ascii'),
                                   NAS_Identifier=nas_identifier.encode('ascii'))
req["User-Password"] = req.PwCrypt(password)

And send the request:

response = srv.SendPacket(req)

How could I assist?

Doesn't work when trying to run on macOS Sierra (10.12.5)

I am getting this error:
srv.Run()
File "build/bdist.macosx-10.12-x86_64/egg/pyrad/server.py", line 300, in Run

AttributeError: 'module' object has no attribute 'poll'

From my research it looks like there is an issue with poll on macOS, which is why the Python build for mac has it disabled.

Is poll absolutely required here?

Why can't Pyrad support dictionary attribute IDs > 255

Hi,

I am using Pyrad 2.0. I have a dictionary with many attributes. Many of them have the ID > 255. like this :

ATTRIBUTE Digest-URI 1066 string

struct.pack seems to raise a DeprecationWarning and truncates the packet ID to a 0 - 255 interval.

What can I do ??

Thanks,
Alex

Error message when run default example with python3

https://github.com/wichert/pyrad/blob/master/example/server.py
https://github.com/wichert/pyrad/blob/master/example/coa.py

From the server.py example
I ran server.py with python 3.6.1
And another terminal coa.py

I got error

Traceback (most recent call last):
  File "radius_client.py", line 35, in <module>
    main()
  File "radius_client.py", line 31, in main
    test_call()
  File "radius_client.py", line 14, in test_call
    User_Name="wichert", NAS_Identifier="localhost")
  File "/Users/el/.pyenv/versions/uih-spot/lib/python3.6/site-packages/pyrad/client.py", line 91, in CreateAuthPacket
    return host.Host.CreateAuthPacket(self, secret=self.secret, **args)
  File "/Users/el/.pyenv/versions/uih-spot/lib/python3.6/site-packages/pyrad/host.py", line 56, in CreateAuthPacket
    return packet.AuthPacket(dict=self.dict, **args)
  File "/Users/el/.pyenv/versions/uih-spot/lib/python3.6/site-packages/pyrad/packet.py", line 417, in __init__
    Packet.__init__(self, code, id, secret, authenticator, **attributes)
  File "/Users/el/.pyenv/versions/uih-spot/lib/python3.6/site-packages/pyrad/packet.py", line 101, in __init__
    self.AddAttribute(key, value)
  File "/Users/el/.pyenv/versions/uih-spot/lib/python3.6/site-packages/pyrad/packet.py", line 182, in AddAttribute
    (key, value) = self._EncodeKeyValues(key, [value])
  File "/Users/el/.pyenv/versions/uih-spot/lib/python3.6/site-packages/pyrad/packet.py", line 137, in _EncodeKeyValues
    attr = self.dict.attributes[key]
KeyError: 'User-Name'

What does it means?
I am new to RADIUS, but not python

IPv6 Support

Any chance to implement IPv6 support in near future ? We can see ipv6addr and ipv6prefix bellow the comment "These datatypes are parsed but not supported:" .
Actually i am using v0.6 . it is fine just i want to add ipv6 support in it .
It is better for me not to upgrade to new version because my version is a modified version which included in IBSng project .

How to re-use the Client object

I try sending an Auth packet and it goes fine, the code below works all good.

srv = Client(server=cluster_host, secret=shared_secret_binary, dict=my_dict)
req = srv.CreateAuthPacket(code=pyrad.packet.AccessRequest, User_Name='user1')
### add some more attrs to request #####
reply = srv.SendPacket(req)

Now, I want to re-use the srv object to send another request but it does not work.

req = srv.CreateAcctPacket(code=pyrad.packet.AccountingRequest, User_Name="user1")
reply = srv.SendPacket(req)  # does not work

Is this not supported ? Do I need to create the srv object everytime I need to send a packet ?

commit b9518ac28 (add support for octets starting with 0x) what for?

When I generate an attribute User-Password (CHAP), I get string start with '0x'. This leads to error:

  File "/usr/local/lib/python2.7/dist-packages/pyrad/packet.py", line 150, in _EncodeKeyValues
    return (key, [self._EncodeValue(attr, v) for v in values])
  File "/usr/local/lib/python2.7/dist-packages/pyrad/packet.py", line 123, in _EncodeValue
    result = tools.EncodeAttr(attr.type, value)
  File "/usr/local/lib/python2.7/dist-packages/pyrad/tools.py", line 178, in EncodeAttr
    return EncodeOctets(value)
  File "/usr/local/lib/python2.7/dist-packages/pyrad/tools.py", line 26, in EncodeOctets
    return binascii.unhexlify(hexstring)
TypeError: Odd-length string

Can this exception be put into a separate function?

pylint is very upset with pyrad

Global evaluation

Your code has been rated at -4.81/10

for pyrad/server.py

for the rest of that directory:
$ for d in pyrad/*.py; do echo -n "$d: "; pylint $d | grep "Your code has been rated"; done
pyrad/bidict.py: Your code has been rated at -4.23/10
pyrad/client.py: Your code has been rated at -1.85/10
pyrad/curved.py: Your code has been rated at 0.20/10
pyrad/dictfile.py: Your code has been rated at -3.38/10
pyrad/dictionary.py: Your code has been rated at -1.74/10
pyrad/host.py: Your code has been rated at -8.50/10
pyrad/init.py: Your code has been rated at -40.00/10
pyrad/packet.py: Your code has been rated at -3.26/10
pyrad/proxy.py: Your code has been rated at 0.00/10
pyrad/server.py: Your code has been rated at -4.81/10 (previous run: -4.81/10, +0.00)
pyrad/tools.py: Your code has been rated at -2.61/10

that's ugly :( it'd be nice if it conformed somewhat better :)

CoA Access Request Authentication is failing

I am getting the password authentication fail message when i used the following Pyrad.AuthPackets PwCrypt() method, after converting it to a function. as per given the example for CreateAuthPacket class.
srv=Client(server="radius.my.domain", secret="s3cr3t",
dict=Dictionary("dicts/dictionary", "dictionary.acc"))
req=srv.CreateAuthPacket(code=pyrad.packet.AccessRequest,User_Name="wichert",
NAS_Identifier="localhost")
req["User-Password"]=req.PwCrypt("password")
reply=srv.SendPacket(req)

I wrote another short version of Pwd encryption method which is given below is also failing, would you please let me know if pyrad doesn't support the CoA account logon or I am doing something wrong here.

srv = Client(server=ISG_SERVER_IP,
authport=ISG_SERVER_CUSTOM_AUTH_PORT,
secret=six.b(ISG_SERVER_SECRET),
dict=Dictionary("CapPortalApp\radiusclient\dictionary"))

req = srv.CreateCoAPacket()
req['User-Name'] = ISG_SERVER_USER_NAME
req['Cisco-Account-Info'] = PBHK
req['User-Password'] = EncPwd('cisco','radius')        
req['Cisco-AVPair'] = 'subscriber:command=account-logon'
  #if i use the following cisco-avpair i am getting unhashable type: 'list' error.
 #req['Cisco-AVPair'] = ['subscriber:password=cisco', 'subscriber:command=profile-status-query']        
 reply = srv.SendPacket(req)

I am using the following pwd encryption as per cisco document given here.
http://www.cisco.com/c/en/us/td/docs/ios/12_2sb/isg/coa/guide/isg_ig/isgcoa3.html#wp1100384

def EncPwd(password, secret):
#Python script that computes the User-Password for pwd length less than 16 char.
password = password.encode('latin-1')
secret = secret.encode('latin-1')
I = 'IIIIIIIIIIIIIIII'.encode('latin-1')
encrypted_pwd = ''.encode('latin-1')
P = (binascii.unhexlify(hex(len(password))[2:].rjust(2,'0')) + password) +
('\x00').encode('latin-1') * (16 - (len(password) % 16))
b = hashlib.md5((secret + I)).digest()
for i in range(16):
encrypted_pwd += bytes(( b[i] ^ P[i],))
#result = I + encrypted_pwd #for binary result
result = binascii.hexlify(I) + binascii.hexlify(encrypted_pwd) #for hex result
return result

Incorrect rtype in docstring for Client.CreateAuthPacket

The rtype in the docstring of Client.CreateAuthPacket is incorrectly given as pyrad.packet.Packet.

IDEs which respect the rtype of functions as declared in their docstrings (such as PyCharm) will complain about calling AuthPacket methods such as PwCrypt on the result of Client.CreateAuthPacket because of this rtype.

This is already fixed by my PR #81 but I thought it might be useful to have an issue about it as well, in case anyone comes looking.

pyrad.server accepting requests (packets) from any NAS

Is there a way that a pyrad server respond to packets sent from any host, I don't know in advance what the IP addresses of the "remote hosts" are.

I've tried passing a RemoteHost with the IP address 0.0.0.0/0 (this works in FreeRADIUS), I also have tried not passing the hosts keyword argument to the pyrad.server.Server constructor... but it doesn't work.

Any workaround?

example/server.py fails

hello,
i get this error when trying to play with server.py in the example folder:
Traceback (most recent call last):
File "serverRadius.py", line 37, in
srv.Run()
File "C:\Python27\lib\site-packages\pyrad-2.0-py2.7.egg\pyrad\server.py", line 233, in Run
self._poll = select.poll()
AttributeError: 'module' object has no attribute 'poll'

regards,
Laurent

Add .egg/ directories to .gitignore

there are a few other things ignored, fixing this means not having to worry about 'git status' showing:
Untracked files:
(use "git add ..." to include in what will be committed)

netaddr-0.7.19-py2.7.egg/
nose-1.3.7-py2.7.egg/

after running: python setup.py test

Does Pyrad Support EAP Message inside Radius

Hi ,

I saw the library also the Robot Framework Library built on top of it. I want to simulate AAA Server which I can control based on my request. I would like to send EAP Encapsulated Access Accept message want to know whether we can use it to send EAP packets.

Password decode issue using curved

I have a working server written for Linux machines that performs the functionality I require (authentication requests only). I, unfortunately, also need it to function on Windows machines, and I discovered that pyrad has a dependency issue when on Windows machines. The curved.py (which uses twisted) included in pyrad apparently will work around this (#16).

I've modified my code for an implementation that inherits from curved.RADIUSAccess. One issue that I have had with curved is the datagramReceived is not being properly overloaded and was calling self.CreatePacket instead of self.CreateAuthPacket. I discovered this by attempting to call pkt.PwDecrypt. I had to overload datagramReceived in order to fix this issue.

Now, when I call pkt.PwDecrypt(pkt[attr][0]), where attr = "User-Password", I get the following traceback:

        Traceback (most recent call last):
          File "C:\Users\michael.dresser\AppData\Local\Programs\Python\Python35\lib\site-packages\twisted\python\log.py", line 86, in callWithContext
            return context.call({ILogContext: newCtx}, func, *args, **kw)
          File "C:\Users\michael.dresser\AppData\Local\Programs\Python\Python35\lib\site-packages\twisted\python\context.py", line 122, in callWithContext
            return self.currentContext().callWithContext(ctx, func, *args, **kw)
          File "C:\Users\michael.dresser\AppData\Local\Programs\Python\Python35\lib\site-packages\twisted\python\context.py", line 85, in callWithContext
            return func(*args,**kw)
          File "C:\Users\michael.dresser\AppData\Local\Programs\Python\Python35\lib\site-packages\twisted\internet\selectreactor.py", line 149, in _doReadOrWrite
            why = getattr(selectable, method)()
        --- <exception caught here> ---
          File "C:\Users\michael.dresser\AppData\Local\Programs\Python\Python35\lib\site-packages\twisted\internet\udp.py", line 249, in doRead
            self.protocol.datagramReceived(data, addr)
          File ".\owRadiusServer_win.py", line 39, in datagramReceived
            self.processPacket(pkt)
          File ".\owRadiusServer_win.py", line 60, in processPacket
            RAD_REQUEST[attr] = pkt.PwDecrypt(pkt[attr][0])
          File "C:\Users\michael.dresser\AppData\Local\Programs\Python\Python35\lib\site-packages\pyrad\packet.py", line 477, in PwDecrypt
            return pw.decode('utf-8')
        builtins.UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8e in position 0: invalid start byte

The "invalid start byte" is not always at position 0, but I always get this error. What can I do to resolve this?

Note: Using python 3.5.4, and the same issue occurs with 2.7.14

Packet Problem

File "server3.py", line 159, in
srv.Run()
File "/root/pyrad-2.0/example/pyrad/server.py", line 242, in Run
self._ProcessInput(fdo)
File "/root/pyrad-2.0/example/pyrad/server.py", line 221, in _ProcessInput
self._HandleAuthPacket(pkt)
File "server3.py", line 128, in _HandleAuthPacket
self.get_password( pkt['User-Name'][0] ) )
File "server3.py", line 105, in validate_mschapv2
return self.add_attributes( reply,pkt )
File "server3.py", line 46, in add_attributes
pkt.AddAttribute( pkt[ attr ],attr )
File "/root/pyrad-2.0/example/pyrad/packet.py", line 165, in AddAttribute
self.setdefault(key, []).append([value])
TypeError: unhashable type: 'list'

when the client using MS-CHAP2 the python get this error but on PAP does'nt have any problem
I decoding MS-CHAP2 password from MS-CHAP2-Response and MS-CHAP-Challenge
and when i want to add attribute "MS-CHAP2-Success" to packet and dictionary and send it to Client python get above error.
what's the problem?

Support for equality checks __eq__ on objects

Objects created in pyrad can't be check for equality as they don't implement __eq__ methods. For instance

>>> from pyrad.client import Client
>>> from unittest.mock import MagicMock
>>> rad_dict = MagicMock()
>>> client1 = Client('192.0.2.1', secret='supersecret', dict=rad_dict)
>>> client2 = Client('192.0.2.1', secret='supersecret', dict=rad_dict)
>>> client1 == client2
False

Usage examples and general information

We have being requested by a local ISP provider to make an ERP writted in python to be able to control Freeradius server in order to allow/deny access to Wireless WAN bassed on customer good standing on payments.

Does this library could help us to acomplish that? If yes, would you mind point me on some intial documentation/examples for start playing wit ti?

Thanks in advance

pyrad installation with python3.2.6

i have installed pyrad using the setup.py ,

i wanted to try the example in readme , but when i run the file i get :
from pyrad.client import Client ModuleNotFoundError: No module named 'pyrad.client'; 'pyrad' is not a package

i copy pasted the same example , how can i fix this ?

Missing LICENSE.txt

This is likely a nitpick but the source distribution in pypi does not include the license file.

Server doesn't reply to the client

Hello friend, how are u?

I am working hard in a solution to authenticate some users using pyrad, but I got some issues that I would like to share with you.

Basically, I created a virtual networking using mininet and there are just 2 hosts, like bellow:

h1 -> 10.0.0.1 (that's my pyrad server host) - Server
h2 -> 10.0.0.2 (that's the host which I am trying to authenticate in h1) - Client

1) First issue - I got an error related to UTF-8 in the the "PwDecrypt" function

In the client side, my password is just: 123. When I send an authentication request, the password is crypted and sent to the server (h1). I know that I need to decrypt the password received in the server side, but when I try to implement the function "PwDecrypt", I got a lot of errors related to UTF-8 encoding.

I tried to implement some functions, such as "password_dec = (pkt.PwDecrypt(pkt[2][0])).decode('latin-1').encode("utf-8")", to correct the mismatch but anything has solved my problem.

Printscreens:

1

**2) Second issue - My server side doesn't reply to the client host **

I really don't know what I did wrong, but, it's possible to receive the authentication request from the client host in the server side, but when I need to answer if the authentication is accepted or not, my client host doesn't receive anything.

I am attaching my server and client code here. Can you please help me ?

pyrad.zip

Thank you in advance.

Cheers.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.