commit c46fbf3d723ba20c8bd7050181e7568700ceae0e Author: Steve McMaster Date: Sun Oct 16 16:22:42 2022 +0000 Initial commit diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..186e620 --- /dev/null +++ b/.drone.yml @@ -0,0 +1,34 @@ +kind: pipeline +name: default +type: docker + +steps: + - name: build + image: docker:dind + volumes: + - name: dockersock + path: /var/run + commands: + - sleep 8 + - DOCKER_BUILDKIT=1 docker build --tag cr.smcm.xyz/${DRONE_REPO_NAME}:${DRONE_COMMIT_SHA} --cache-from cr.smcm.xyz/${DRONE_REPO_NAME}:latest . + - docker tag cr.smcm.xyz/${DRONE_REPO_NAME}:${DRONE_COMMIT_SHA} cr.smcm.xyz/${DRONE_REPO_NAME}:latest + - docker push --all-tags cr.smcm.xyz/${DRONE_REPO_NAME} + +services: + - name: docker + image: docker:dind + privileged: true + volumes: + - name: dockersock + path: /var/run + +volumes: + - name: dockersock + temp: {} + +trigger: + branch: + - main + event: + - push + - custom \ No newline at end of file diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..3e25327 --- /dev/null +++ b/.flake8 @@ -0,0 +1,6 @@ +[flake8] +# max-complexity = 15 +# ignore = F403 +inline-quotes = " +max-line-length = 250 +import-order-style = smarkets \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..67d3334 --- /dev/null +++ b/.gitignore @@ -0,0 +1,66 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg +.python-version + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage_data +.cache +nosetests.xml +coverage.xml + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Vim +*.swp + +# Divshot +.divshot-cache/ +.venv +.vscode/** +.pytest_cache/** +.venv-py27 \ No newline at end of file diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..6b3818f --- /dev/null +++ b/.pylintrc @@ -0,0 +1,52 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code +extension-pkg-whitelist=lxml + + +[MESSAGES CONTROL] + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once).You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use"--disable=all --enable=classes +# --disable=W" +disable=locally-disabled, + wrong-import-order, + missing-docstring, + logging-not-lazy, + invalid-name, + broad-except, + fixme, + too-few-public-methods, + ungrouped-imports, + no-else-return, + no-else-raise, + duplicate-code, + no-member, + unused-argument, + redefined-outer-name + + +[FORMAT] + +# Maximum number of characters on a single line. +max-line-length=250 + +[REPORTS] + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio).You can also give a reporter class, eg +# mypackage.mymodule.MyReporterClass. +output-format=colorized + +[SIMILARITIES] + +# Ignore imports when computing similarities. +ignore-imports=yes \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..209fe46 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM python:alpine AS venv + +RUN python3 -m venv /opt/venv +ENV PATH="/opt/venv/bin:$PATH" + +COPY *.py /opt/app/ + +RUN pip3 install /opt/app/ + +FROM python:alpine AS runtime + +ENTRYPOINT ["/opt/app/bin/vlanassign"] +CMD ["-c", "/data/config.yaml", "-L", "info"] \ No newline at end of file diff --git a/config.sample.yaml b/config.sample.yaml new file mode 100644 index 0000000..728049c --- /dev/null +++ b/config.sample.yaml @@ -0,0 +1,29 @@ +assign: + "DB-9E-5B-14-44-D1": 10 + "92:73:D9:8A:63:37": 20 + "BE39.34DD.76AC": 30 + "C919.2AC9.7E20": 40 +clients: + 127.0.0.1: 070c58eb-f79d-4cbb-8482-3aaab089cc88 + 192.168.200.123: 1231fa06-593b-4f37-a4a1-646e22c34928 + 10.244.0.1: 83f271a8-285d-4830-b4ae-2c91d460b7e1 +default_vlan: 100 +dictionary: + - name: User-Name + id: 1 + type: string + - name: User-Password + id: 2 + type: string + - name: NAS-Identifier + id: 32 + type: string + - name: Tunnel-Type + id: 64 + type: integer + - name: Tunnel-Medium-Type + id: 65 + type: integer + - name: Tunnel-Private-Group-ID + id: 81 + type: string \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..e73861e --- /dev/null +++ b/setup.py @@ -0,0 +1,29 @@ +from setuptools import setup + + +setup( + name="vlanassign", + version="1.0.0", + author="Steve McMaster", + author_email="steve@mcmaster.io", + py_modules=["vlanassign"], + include_package_data=True, + zip_safe=False, + description="Minimal RADIUS server for responding to VLAN assignment requests", + long_description="Minimal RADIUS server for responding to VLAN assignment requests", + install_requires=[ + "asyncio", + "pyrad", + "pyyaml", + ], + entry_points={ + "console_scripts": [ + "vlanassign = vlanassign:main", + ] + }, + classifiers=[ + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3 :: Only", + "Development Status :: 5 - Production/Stable", + ], +) diff --git a/test.py b/test.py new file mode 100644 index 0000000..38d2147 --- /dev/null +++ b/test.py @@ -0,0 +1,25 @@ +import pyrad.packet +from pyrad.client import Client +from pyrad.dictionary import Dictionary + + +srv = Client( + server="127.0.0.1", + secret=b"070c58eb-f79d-4cbb-8482-3aaab089cc88", + dict=Dictionary("dictionary") +) + +req = srv.CreateAuthPacket( + code=pyrad.packet.AccessRequest, + User_Name="9273D98A6337", + NAS_Identifier="9273D98A6337" +) +req["User-Password"] = req.PwCrypt("9273D98A6337") + +reply = srv.SendPacket(req) + +assert reply.code == pyrad.packet.AccessAccept + +assert reply["Tunnel-Type"] == [13] +assert reply["Tunnel-Medium-Type"] == [6] +assert reply["Tunnel-Private-Group-ID"] == ["20"] diff --git a/vlanassign.py b/vlanassign.py new file mode 100644 index 0000000..6f2e493 --- /dev/null +++ b/vlanassign.py @@ -0,0 +1,141 @@ +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()