safe progress

This commit is contained in:
Istvan Ruzman
2020-08-06 18:04:24 +02:00
parent 3254bc66e0
commit fd16436c3c
53 changed files with 2167 additions and 4589 deletions

View File

@@ -15,41 +15,47 @@ def send_accounting_packet(srv, req):
try:
srv.SendPacket(req)
except pyrad.client.Timeout:
print('RADIUS server does not reply')
print("RADIUS server does not reply")
sys.exit(1)
except socket.error as error:
print('Network error: ' + error[1])
print("Network error: " + error[1])
sys.exit(1)
def main(path_to_dictionary):
srv = Client(server='127.0.0.1',
secret=b'Kah3choteereethiejeimaeziecumi',
dict=Dictionary(path_to_dictionary))
srv = Client(
server="127.0.0.1",
secret=b"Kah3choteereethiejeimaeziecumi",
dict=Dictionary(path_to_dictionary),
)
req = srv.CreateAcctPacket(**{
'User-Name': 'wichert',
'NAS-IP-Address': '192.168.1.10',
'NAS-Port': 0,
'NAS-Identifier': 'trillian',
'Called-Station-Id': '00-04-5F-00-0F-D1',
'Calling-Station-Id': '00-01-24-80-B3-9C',
'Framed-IP-Address': '10.0.0.100',
})
req = srv.CreateAcctPacket(
**{
"User-Name": "wichert",
"NAS-IP-Address": "192.168.1.10",
"NAS-Port": 0,
"NAS-Identifier": "trillian",
"Called-Station-Id": "00-04-5F-00-0F-D1",
"Calling-Station-Id": "00-01-24-80-B3-9C",
"Framed-IP-Address": "10.0.0.100",
}
)
print('Sending accounting start packet')
req['Acct-Status-Type'] = 'Start'
print("Sending accounting start packet")
req["Acct-Status-Type"] = "Start"
send_accounting_packet(srv, req)
print('Sending accounting stop packet')
req['Acct-Status-Type'] = 'Stop'
req['Acct-Input-Octets'] = random.randrange(2**10, 2**30)
req['Acct-Output-Octets'] = random.randrange(2**10, 2**30)
req['Acct-Session-Time'] = random.randrange(120, 3600)
req['Acct-Terminate-Cause'] = random.choice(['User-Request', 'Idle-Timeout'])
print("Sending accounting stop packet")
req["Acct-Status-Type"] = "Stop"
req["Acct-Input-Octets"] = random.randrange(2 ** 10, 2 ** 30)
req["Acct-Output-Octets"] = random.randrange(2 ** 10, 2 ** 30)
req["Acct-Session-Time"] = random.randrange(120, 3600)
req["Acct-Terminate-Cause"] = random.choice(
["User-Request", "Idle-Timeout"]
)
send_accounting_packet(srv, req)
if __name__ == '__main__':
dictionary = path.join(path.dirname(path.abspath(__file__)), 'dictionary')
if __name__ == "__main__":
dictionary = path.join(path.dirname(path.abspath(__file__)), "dictionary")
main(dictionary)

View File

@@ -11,43 +11,46 @@ from pyrad.dictionary import Dictionary
def main(path_to_dictionary):
srv = Client(server='127.0.0.1',
secret=b'Kah3choteereethiejeimaeziecumi',
dict=Dictionary(path_to_dictionary))
srv = Client(
server="127.0.0.1",
secret=b"Kah3choteereethiejeimaeziecumi",
dict=Dictionary(path_to_dictionary),
)
req = srv.CreateAuthPacket(
code=pyrad.packet.AccessRequest,
**{
'User-Name': 'wichert',
'NAS-IP-Address': '192.168.1.10',
'NAS-Port': 0,
'Service-Type': 'Login-User',
'NAS-Identifier': 'trillian',
'Called-Station-Id': '00-04-5F-00-0F-D1',
'Calling-Station-Id': '00-01-24-80-B3-9C',
'Framed-IP-Address': '10.0.0.100',
})
"User-Name": "wichert",
"NAS-IP-Address": "192.168.1.10",
"NAS-Port": 0,
"Service-Type": "Login-User",
"NAS-Identifier": "trillian",
"Called-Station-Id": "00-04-5F-00-0F-D1",
"Calling-Station-Id": "00-01-24-80-B3-9C",
"Framed-IP-Address": "10.0.0.100",
},
)
try:
print('Sending authentication request')
print("Sending authentication request")
reply = srv.SendPacket(req)
except pyrad.client.Timeout:
print('RADIUS server does not reply')
print("RADIUS server does not reply")
sys.exit(1)
except socket.error as error:
print('Network error: ' + error[1])
print("Network error: " + error[1])
sys.exit(1)
if reply.code == pyrad.packet.AccessAccept:
print('Access accepted')
print("Access accepted")
else:
print('Access denied')
print("Access denied")
print('Attributes returned by server:')
print("Attributes returned by server:")
for key, value in reply.items():
print(f'{key} {value}')
print(f"{key} {value}")
if __name__ == '__main__':
dictionary = path.join(path.dirname(path.abspath(__file__)), 'dictionary')
if __name__ == "__main__":
dictionary = path.join(path.dirname(path.abspath(__file__)), "dictionary")
main(dictionary)

View File

@@ -10,49 +10,58 @@ from pyrad.client_async import ClientAsync
from pyrad.dictionary import Dictionary
from pyrad.packet import AccessAccept
logging.basicConfig(level='DEBUG',
format='%(asctime)s [%(levelname)-8s] %(message)s')
logging.basicConfig(
level="DEBUG", format="%(asctime)s [%(levelname)-8s] %(message)s"
)
def create_request(client, user):
return client.CreateAuthPacket(**{
'User-Name': user,
'NAS-IP-Address': '192.168.1.10',
'NAS-Port': 0,
'Service-Type': 'Login-User',
'NAS-Identifier': 'trillian',
'Called-Station-Id': '00-04-5F-00-0F-D1',
'Calling-Station-Id': '00-01-24-80-B3-9C',
'Framed-IP-Address': '10.0.0.100',
})
return client.CreateAuthPacket(
**{
"User-Name": user,
"NAS-IP-Address": "192.168.1.10",
"NAS-Port": 0,
"Service-Type": "Login-User",
"NAS-Identifier": "trillian",
"Called-Station-Id": "00-04-5F-00-0F-D1",
"Calling-Station-Id": "00-01-24-80-B3-9C",
"Framed-IP-Address": "10.0.0.100",
}
)
def print_reply(reply):
if reply.code == AccessAccept:
print('Access accepted')
print("Access accepted")
else:
print('Access denied')
print("Access denied")
print('Attributes returned by server:')
print("Attributes returned by server:")
for key, value in reply.items():
print(f'{key}: {value}')
print(f"{key}: {value}")
def initialize_transport(loop, client):
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)))
client.initialize_transports(
enable_auth=True,
local_addr="127.0.0.1",
local_auth_port=8000,
enable_acct=True,
enable_coa=True,
)
)
)
def main(path_to_dictionary):
client = ClientAsync(server='localhost',
secret=b'Kah3choteereethiejeimaeziecumi',
timeout=4,
dict=Dictionary(path_to_dictionary))
client = ClientAsync(
server="localhost",
secret=b"Kah3choteereethiejeimaeziecumi",
timeout=4,
dict=Dictionary(path_to_dictionary),
)
loop = asyncio.get_event_loop()
@@ -62,41 +71,41 @@ def main(path_to_dictionary):
requests = []
for i in range(255):
req = create_request(client, f'user{i}')
req = create_request(client, f"user{i}")
future = client.SendPacket(req)
requests.append(future)
# Send auth requests asynchronously to the server
loop.run_until_complete(asyncio.ensure_future(
asyncio.gather(
*requests,
return_exceptions=True
loop.run_until_complete(
asyncio.ensure_future(
asyncio.gather(*requests, return_exceptions=True)
)
))
)
for future in requests:
if future.exception():
print('EXCEPTION ', 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')
loop.run_until_complete(
asyncio.ensure_future(client.deinitialize_transports())
)
print("END")
except Exception as exc:
print('Error: ', exc)
print("Error: ", exc)
traceback.print_exc()
# Close transports
loop.run_until_complete(asyncio.ensure_future(
client.deinitialize_transports()))
loop.run_until_complete(
asyncio.ensure_future(client.deinitialize_transports())
)
loop.close()
if __name__ == '__main__':
dictionary = path.join(path.dirname(path.abspath(__file__)), 'dictionary')
if __name__ == "__main__":
dictionary = path.join(path.dirname(path.abspath(__file__)), "dictionary")
main(dictionary)

View File

@@ -14,21 +14,21 @@ from pyrad.server import Server, RemoteHost
def print_attributes(packet):
print('Attributes')
print("Attributes")
for key, value in packet.items():
print(f'{key}: {value}')
print(f"{key}: {value}")
class FakeCoA(Server):
def HandleCoaPacket(self, packet):
'''Accounting packet handler.
"""Accounting packet handler.
Function that is called when a valid
accounting packet has been received.
:param packet: packet to process
:type packet: Packet class instance
'''
print('Received a coa request %d' % packet.code)
"""
print("Received a coa request %d" % packet.code)
print_attributes(packet)
reply = self.CreateReplyPacket(packet)
@@ -38,7 +38,7 @@ class FakeCoA(Server):
self.SendReplyPacket(packet.fd, reply)
def HandleDisconnectPacket(self, packet):
print('Received a disconnect request %d' % packet.code)
print("Received a disconnect request %d" % packet.code)
print_attributes(packet)
reply = self.CreateReplyPacket(packet)
@@ -52,27 +52,27 @@ def main(path_to_dictionary, coa_port):
# create server/coa only and read dictionary
# bind and listen only on 127.0.0.1:argv[1]
coa = FakeCoA(
addresses=['127.0.0.1'],
addresses=["127.0.0.1"],
dict=Dictionary(path_to_dictionary),
coaport=coa_port,
auth_enabled=False,
acct_enabled=False,
coa_enabled=True)
coa_enabled=True,
)
# add peers (address, secret, name)
coa.hosts['127.0.0.1'] = RemoteHost(
'127.0.0.1',
b'Kah3choteereethiejeimaeziecumi',
'localhost')
coa.hosts["127.0.0.1"] = RemoteHost(
"127.0.0.1", b"Kah3choteereethiejeimaeziecumi", "localhost"
)
# start
coa.Run()
if __name__ == '__main__':
if __name__ == "__main__":
if len(sys.argv) != 2:
print('usage: client-coa.py {portnumber}')
print("usage: client-coa.py {portnumber}")
sys.exit(1)
dictionary = path.join(path.dirname(path.abspath(__file__)), 'dictionary')
dictionary = path.join(path.dirname(path.abspath(__file__)), "dictionary")
main(dictionary, int(sys.argv[1]))

View File

@@ -11,27 +11,29 @@ from pyrad.dictionary import Dictionary
def main(path_to_dictionary, coa_type, nas_identifier):
# create coa client
client = Client(server='127.0.0.1',
secret=b'Kah3choteereethiejeimaeziecumi',
dict=Dictionary(path_to_dictionary))
client = Client(
server="127.0.0.1",
secret=b"Kah3choteereethiejeimaeziecumi",
dict=Dictionary(path_to_dictionary),
)
# set coa timeout
client.timeout = 30
# create coa request packet
attributes = {
'Acct-Session-Id': '1337',
'NAS-Identifier': nas_identifier,
"Acct-Session-Id": "1337",
"NAS-Identifier": nas_identifier,
}
if coa_type == 'coa':
if coa_type == "coa":
# create coa request
request = client.CreateCoAPacket(**attributes)
elif coa_type == 'dis':
elif coa_type == "dis":
# create disconnect request
request = client.CreateCoAPacket(
code=pyrad.packet.DisconnectRequest,
**attributes)
code=pyrad.packet.DisconnectRequest, **attributes
)
else:
sys.exit(1)
@@ -41,11 +43,11 @@ def main(path_to_dictionary, coa_type, nas_identifier):
print(result.code)
if __name__ == '__main__':
if __name__ == "__main__":
if len(sys.argv) != 3:
print('usage: coa.py {coa|dis} daemon-1234')
print("usage: coa.py {coa|dis} daemon-1234")
sys.exit(1)
dictionary = path.join(path.dirname(path.abspath(__file__)), 'dictionary')
dictionary = path.join(path.dirname(path.abspath(__file__)), "dictionary")
main(dictionary, sys.argv[1], sys.argv[2])

View File

@@ -8,46 +8,52 @@ import pyrad.packet
from pyrad import server
from pyrad.dictionary import Dictionary
logging.basicConfig(filename='pyrad.log', level='DEBUG',
format='%(asctime)s [%(levelname)-8s] %(message)s')
logging.basicConfig(
filename="pyrad.log",
level="DEBUG",
format="%(asctime)s [%(levelname)-8s] %(message)s",
)
def print_attributes(packet):
print('Attributes')
print("Attributes")
for key, value in packet.items():
print(f'{key}: {value}')
print(f"{key}: {value}")
class FakeServer(server.Server):
def HandleAuthPacket(self, packet):
print('Received an authentication request')
print("Received an authentication request")
print_attributes(packet)
reply = self.CreateReplyPacket(packet, **{
'Service-Type': 'Framed-User',
'Framed-IP-Address': '192.168.0.1',
'Framed-IPv6-Prefix': 'fc66::/64'
})
reply = self.CreateReplyPacket(
packet,
**{
"Service-Type": "Framed-User",
"Framed-IP-Address": "192.168.0.1",
"Framed-IPv6-Prefix": "fc66::/64",
},
)
reply.code = pyrad.packet.AccessAccept
self.SendReplyPacket(packet.fd, reply)
def HandleAcctPacket(self, packet):
print('Received an accounting request')
print("Received an accounting request")
print_attributes(packet)
reply = self.CreateReplyPacket(packet)
self.SendReplyPacket(packet.fd, reply)
def HandleCoaPacket(self, packet):
print('Received an coa request')
print("Received an coa request")
print_attributes(packet)
reply = self.CreateReplyPacket(packet)
self.SendReplyPacket(packet.fd, reply)
def HandleDisconnectPacket(self, packet):
print('Received an disconnect request')
print("Received an disconnect request")
print_attributes(packet)
reply = self.CreateReplyPacket(packet)
@@ -58,20 +64,18 @@ class FakeServer(server.Server):
def main(path_to_dictionary):
# create server and read dictionary
srv = FakeServer(dict=Dictionary(path_to_dictionary),
coa_enabled=True)
srv = FakeServer(dict=Dictionary(path_to_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('0.0.0.0')
srv.hosts["127.0.0.1"] = server.RemoteHost(
"127.0.0.1", b"Kah3choteereethiejeimaeziecumi", "localhost"
)
srv.BindToAddress("0.0.0.0")
# start server
srv.Run()
if __name__ == '__main__':
dictionary = path.join(path.dirname(path.abspath(__file__)), 'dictionary')
if __name__ == "__main__":
dictionary = path.join(path.dirname(path.abspath(__file__)), "dictionary")
main(dictionary)

View File

@@ -12,57 +12,67 @@ 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')
logging.basicConfig(
level="DEBUG", format="%(asctime)s [%(levelname)-8s] %(message)s"
)
def print_attributes(packet):
print('Attributes returned by server:')
print("Attributes returned by server:")
for key, value in packet.items():
print(f'{key}: {value}')
print(f"{key}: {value}")
class FakeServer(ServerAsync):
def __init__(self, loop, dictionary):
ServerAsync.__init__(self, loop=loop, dictionary=dictionary,
enable_pkt_verify=True, debug=True)
ServerAsync.__init__(
self,
loop=loop,
dictionary=dictionary,
enable_pkt_verify=True,
debug=True,
)
def handle_auth_packet(self, protocol, packet, addr):
print('Received an authentication request with id ', packet.id)
print('Authenticator ', packet.authenticator.hex())
print('Secret ', packet.secret)
print("Received an authentication request with id ", packet.id)
print("Authenticator ", packet.authenticator.hex())
print("Secret ", packet.secret)
print_attributes(packet)
reply = self.CreateReplyPacket(packet, **{
'Service-Type': 'Framed-User',
'Framed-IP-Address': '192.168.0.1',
'Framed-IPv6-Prefix': 'fc66::/64'
})
reply = self.CreateReplyPacket(
packet,
**{
"Service-Type": "Framed-User",
"Framed-IP-Address": "192.168.0.1",
"Framed-IPv6-Prefix": "fc66::/64",
},
)
reply.code = AccessAccept
protocol.send_response(reply, addr)
def handle_acct_packet(self, protocol, packet, addr):
print('Received an accounting request')
print("Received an accounting request")
print_attributes(packet)
reply = self.CreateReplyPacket(packet)
protocol.send_response(reply, addr)
def handle_coa_packet(self, protocol, packet, addr):
print('Received an coa request')
print("Received an coa request")
print_attributes(packet)
reply = self.CreateReplyPacket(packet)
protocol.send_response(reply, addr)
def handle_disconnect_packet(self, protocol, packet, addr):
print('Received an disconnect request')
print("Received an disconnect request")
print_attributes(packet)
reply = self.CreateReplyPacket(packet)
@@ -77,17 +87,19 @@ def main(path_to_dictionary):
server = FakeServer(loop=loop, dictionary=Dictionary(path_to_dictionary))
# add clients (address, secret, name)
server.hosts['127.0.0.1'] = RemoteHost('127.0.0.1',
b'Kah3choteereethiejeimaeziecumi',
'localhost')
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)))
server.initialize_transports(
enable_auth=True, enable_acct=True, enable_coa=True
)
)
)
try:
# start server
@@ -96,20 +108,22 @@ def main(path_to_dictionary):
pass
# Close transports
loop.run_until_complete(asyncio.ensure_future(
server.deinitialize_transports()))
loop.run_until_complete(
asyncio.ensure_future(server.deinitialize_transports())
)
except Exception as exc:
print('Error: ', exc)
print("Error: ", exc)
traceback.print_exc()
# Close transports
loop.run_until_complete(asyncio.ensure_future(
server.deinitialize_transports()))
loop.run_until_complete(
asyncio.ensure_future(server.deinitialize_transports())
)
loop.close()
if __name__ == '__main__':
dictionary = path.join(path.dirname(path.abspath(__file__)), 'dictionary')
if __name__ == "__main__":
dictionary = path.join(path.dirname(path.abspath(__file__)), "dictionary")
main(dictionary)

View File

@@ -11,32 +11,33 @@ from pyrad.dictionary import Dictionary
def main(path_to_dictionary):
srv = Client(server='localhost',
authport=18121,
secret=b'test',
dict=Dictionary(path_to_dictionary))
srv = Client(
server="localhost",
authport=18121,
secret=b"test",
dict=Dictionary(path_to_dictionary),
)
req = srv.CreateAuthPacket(
code=pyrad.packet.StatusServer,
FreeRADIUS_Statistics_Type='All',
code=pyrad.packet.StatusServer, FreeRADIUS_Statistics_Type="All",
)
req.add_message_authenticator()
try:
print('Sending FreeRADIUS status request')
print("Sending FreeRADIUS status request")
reply = srv.SendPacket(req)
except pyrad.client.Timeout:
print('RADIUS server does not reply')
print("RADIUS server does not reply")
sys.exit(1)
except socket.error as error:
print('Network error: ' + error[1])
print("Network error: " + error[1])
sys.exit(1)
print('Attributes returned by server:')
print("Attributes returned by server:")
for key, value in reply.items():
print(f'{key}: {value}')
print(f"{key}: {value}")
if __name__ == '__main__':
dictionary = path.join(path.dirname(path.abspath(__file__)), 'dictionary')
if __name__ == "__main__":
dictionary = path.join(path.dirname(path.abspath(__file__)), "dictionary")
main(dictionary)