Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async Client/Server Radius #85

Merged
merged 3 commits into from
Jul 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 164 additions & 0 deletions example/auth_async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
#!/usr/bin/python

import asyncio

import logging
import traceback
from pyrad.dictionary import Dictionary
from pyrad.client_async import ClientAsync
from pyrad.packet import AccessAccept

logging.basicConfig(level="DEBUG",
format="%(asctime)s [%(levelname)-8s] %(message)s")
client = ClientAsync(server="localhost",
secret=b"Kah3choteereethiejeimaeziecumi",
timeout=4,
dict=Dictionary("dictionary"))

loop = asyncio.get_event_loop()


def create_request(client, user):
req = client.CreateAuthPacket(User_Name=user)

req["NAS-IP-Address"] = "192.168.1.10"
req["NAS-Port"] = 0
req["Service-Type"] = "Login-User"
req["NAS-Identifier"] = "trillian"
req["Called-Station-Id"] = "00-04-5F-00-0F-D1"
req["Calling-Station-Id"] = "00-01-24-80-B3-9C"
req["Framed-IP-Address"] = "10.0.0.100"

return req

def print_reply(reply):
if reply.code == AccessAccept:
print("Access accepted")
else:
print("Access denied")

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

def test_auth1():

global client

try:
# Initialize transports
loop.run_until_complete(
asyncio.ensure_future(
client.initialize_transports(enable_auth=True,
local_addr='127.0.0.1',
local_auth_port=8000,
enable_acct=True,
enable_coa=True)))



req = client.CreateAuthPacket(User_Name="wichert")

req["NAS-IP-Address"] = "192.168.1.10"
req["NAS-Port"] = 0
req["Service-Type"] = "Login-User"
req["NAS-Identifier"] = "trillian"
req["Called-Station-Id"] = "00-04-5F-00-0F-D1"
req["Calling-Station-Id"] = "00-01-24-80-B3-9C"
req["Framed-IP-Address"] = "10.0.0.100"

future = client.SendPacket(req)

# loop.run_until_complete(future)
loop.run_until_complete(asyncio.ensure_future(
asyncio.gather(
future,
return_exceptions=True
)

))

if future.exception():
print('EXCEPTION ', future.exception())
else:
reply = future.result()

if reply.code == AccessAccept:
print("Access accepted")
else:
print("Access denied")

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

# Close transports
loop.run_until_complete(asyncio.ensure_future(
client.deinitialize_transports()))
print('END')

del client
except Exception as exc:
print('Error: ', exc)
print('\n'.join(traceback.format_exc().splitlines()))
# Close transports
loop.run_until_complete(asyncio.ensure_future(
client.deinitialize_transports()))

loop.close()

def test_multi_auth():

global client

try:
# Initialize transports
loop.run_until_complete(
asyncio.ensure_future(
client.initialize_transports(enable_auth=True,
local_addr='127.0.0.1',
local_auth_port=8000,
enable_acct=True,
enable_coa=True)))



reqs = []
for i in range(255):
req = create_request(client, "user%s" % i)
future = client.SendPacket(req)
reqs.append(future)

# loop.run_until_complete(future)
loop.run_until_complete(asyncio.ensure_future(
asyncio.gather(
*reqs,
return_exceptions=True
)

))

for future in reqs:
if future.exception():
print('EXCEPTION ', future.exception())
else:
reply = future.result()
print_reply(reply)

# Close transports
loop.run_until_complete(asyncio.ensure_future(
client.deinitialize_transports()))
print('END')

del client
except Exception as exc:
print('Error: ', exc)
print('\n'.join(traceback.format_exc().splitlines()))
# Close transports
loop.run_until_complete(asyncio.ensure_future(
client.deinitialize_transports()))

loop.close()

#test_multi_auth()
test_auth1()
117 changes: 117 additions & 0 deletions example/server_async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
#!/usr/bin/python

import asyncio

import logging
import traceback
from pyrad.dictionary import Dictionary
from pyrad.server_async import ServerAsync
from pyrad.packet import AccessAccept
from pyrad.server import RemoteHost

try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except:
pass

logging.basicConfig(level="DEBUG",
format="%(asctime)s [%(levelname)-8s] %(message)s")

class FakeServer(ServerAsync):

def __init__(self, loop, dictionary):

ServerAsync.__init__(self, loop=loop, dictionary=dictionary,
enable_pkt_verify=True, debug=True)


def handle_auth_packet(self, protocol, pkt, addr):

print("Received an authentication request with id ", pkt.id)
print('Authenticator ', pkt.authenticator.hex())
print('Secret ', pkt.secret)
print("Attributes: ")
for attr in pkt.keys():
print("%s: %s" % (attr, pkt[attr]))

reply = self.CreateReplyPacket(pkt, **{
"Service-Type": "Framed-User",
"Framed-IP-Address": '192.168.0.1',
"Framed-IPv6-Prefix": "fc66::1/64"
})

reply.code = AccessAccept
protocol.send_response(reply, addr)

def handle_acct_packet(self, protocol, pkt, addr):

print("Received an accounting request")
print("Attributes: ")
for attr in pkt.keys():
print("%s: %s" % (attr, pkt[attr]))

reply = self.CreateReplyPacket(pkt)
protocol.send_response(reply, addr)

def handle_coa_packet(self, protocol, pkt, addr):

print("Received an coa request")
print("Attributes: ")
for attr in pkt.keys():
print("%s: %s" % (attr, pkt[attr]))

reply = self.CreateReplyPacket(pkt)
protocol.send_response(reply, addr)

def handle_disconnect_packet(self, protocol, pkt, addr):

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
protocol.send_response(reply, addr)


if __name__ == '__main__':

# create server and read dictionary
loop = asyncio.get_event_loop()
server = FakeServer(loop=loop, dictionary=Dictionary('dictionary'))

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

try:

# Initialize transports
loop.run_until_complete(
asyncio.ensure_future(
server.initialize_transports(enable_auth=True,
enable_acct=True,
enable_coa=True)))

try:
# start server
loop.run_forever()
except KeyboardInterrupt as k:
pass

# Close transports
loop.run_until_complete(asyncio.ensure_future(
server.deinitialize_transports()))

except Exception as exc:
print('Error: ', exc)
print('\n'.join(traceback.format_exc().splitlines()))
# Close transports
loop.run_until_complete(asyncio.ensure_future(
server.deinitialize_transports()))

loop.close()
Loading