All checks were successful
continuous-integration/drone/push Build is passing
181 lines
4.7 KiB
Python
181 lines
4.7 KiB
Python
import argparse
|
|
import logging
|
|
import ipaddress
|
|
import os
|
|
import re
|
|
import tempfile
|
|
from collections import UserDict
|
|
|
|
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 IpaddressDict(UserDict):
|
|
def __getitem__(self, key):
|
|
# If `key` exists as a key, just return that
|
|
if super().__contains__(key):
|
|
return super().__getitem__(key)
|
|
|
|
# Test that `key` is actually an ip_address
|
|
try:
|
|
key = ipaddress.ip_address(key)
|
|
except ValueError as e:
|
|
raise KeyError(key) from e
|
|
|
|
# Check each key we have as an ip_network
|
|
for (test, value) in self.items():
|
|
try:
|
|
test = ipaddress.ip_network(test)
|
|
except ValueError:
|
|
continue
|
|
|
|
if key in test:
|
|
return value
|
|
|
|
# No dice
|
|
raise KeyError(key)
|
|
|
|
def __contains__(self, key):
|
|
try:
|
|
self[key]
|
|
except KeyError:
|
|
return False
|
|
return True
|
|
|
|
|
|
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 not in self.usermap:
|
|
reply = self.CreateReplyPacket(pkt)
|
|
reply.code = AccessAccept
|
|
else:
|
|
vlan = str(self.usermap[mac_address])
|
|
|
|
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", encoding="utf-8") 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,
|
|
enable_pkt_verify=True,
|
|
usermap=config["assign"]
|
|
)
|
|
|
|
for address in config["clients"]:
|
|
server.hosts[address] = RemoteHost(
|
|
address,
|
|
config["clients"][address].encode(),
|
|
address
|
|
)
|
|
|
|
server.hosts = IpaddressDict(server.hosts)
|
|
|
|
try:
|
|
# Initialize transports
|
|
loop.run_until_complete(
|
|
asyncio.ensure_future(
|
|
server.initialize_transports(
|
|
addresses=["0.0.0.0"],
|
|
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()
|