vlanassign/vlanassign.py
Steve McMaster c46fbf3d72
All checks were successful
continuous-integration/drone/push Build is passing
Initial commit
2022-10-16 16:22:42 +00:00

142 lines
3.8 KiB
Python

import argparse
import logging
import os
import re
import tempfile
import asyncio
import yaml
from pyrad.dictionary import Dictionary
from pyrad.server_async import ServerAsync
from pyrad.packet import AccessAccept, AccessReject
from pyrad.server import RemoteHost
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
logger = logging.getLogger(__name__)
class VlanAssign(ServerAsync):
def __init__(self, usermap, *args, default_vlan=1, **kwargs):
super().__init__(*args, **kwargs)
self.default_vlan = default_vlan
self.usermap = usermap
def handle_auth_packet(self, protocol, pkt, addr):
mac_address = pkt["User-Name"][0]
vlan = None
if mac_address != pkt["NAS-Identifier"][0]:
reply = self.CreateReplyPacket(pkt)
reply.code = AccessReject
else:
vlan = str(self.usermap.get(mac_address, self.default_vlan))
reply = self.CreateReplyPacket(pkt, **{
"Tunnel-Type": [13],
"Tunnel-Medium-Type": [6],
"Tunnel-Private-Group-ID": [vlan]
})
reply.code = AccessAccept
logger.info("src=%s, mac=%s, status=%s, vlan=%s", addr[0], mac_address, reply.code, vlan)
protocol.send_response(reply, addr)
def handle_acct_packet(self, protocol, pkt, addr):
pass
def handle_coa_packet(self, protocol, pkt, addr):
pass
def handle_disconnect_packet(self, protocol, pkt, addr):
pass
def normalize_mac(mac):
return re.sub("[^A-Fa-f0-9]", "", mac).upper()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--config", default="config.yaml")
ap.add_argument("-L", "--loglevel", default="INFO")
args = ap.parse_args()
if not os.path.exists(args.config):
print(f"Config file {args.config} does not exist")
return
try:
logging.basicConfig(level=args.loglevel.upper(), format="%(asctime)s [%(levelname)-8s] %(message)s")
except ValueError:
print(f"Invalid log level {args.loglevel}")
return
with open(args.config, "r", encoding="utf-8") as f:
config = yaml.load(f, Loader=yaml.SafeLoader)
config["assign"] = {normalize_mac(k): v for (k, v) in config["assign"].items()}
with tempfile.NamedTemporaryFile() as tmpfile:
with open(tmpfile.name, "w") as f:
for attribute in config["dictionary"]:
f.write(f"ATTRIBUTE {attribute['name']} {attribute['id']} {attribute['type']}\n")
dictionary = Dictionary(tmpfile.name)
# create server and read dictionary
loop = asyncio.get_event_loop()
server = VlanAssign(
loop=loop,
dictionary=dictionary,
usermap=config["assign"]
)
for address in config["clients"]:
server.hosts[address] = RemoteHost(
address,
config["clients"][address].encode(),
address
)
try:
# Initialize transports
loop.run_until_complete(
asyncio.ensure_future(
server.initialize_transports(
enable_auth=True,
enable_acct=False,
enable_coa=False
)
)
)
try:
# start server
loop.run_forever()
except KeyboardInterrupt:
pass
# Close transports
loop.run_until_complete(
asyncio.ensure_future(
server.deinitialize_transports()
)
)
except Exception:
# Close transports
loop.run_until_complete(asyncio.ensure_future(
server.deinitialize_transports()))
loop.close()
if __name__ == "__main__":
main()