commit 087a5ea8fb3396e914e47d2dd48e2faf4a7635fd Author: norohind <60548839+norohind@users.noreply.github.com> Date: Fri Apr 4 21:00:45 2025 +0000 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bee8a64 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9968f2a --- /dev/null +++ b/LICENSE @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2025, norohind + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..cb6975c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,19 @@ +[project] +name = "nebula_confgen" +version = "0.0.1" +authors = [ + { name="norohind", email="60548839+norohind@users.noreply.github.com" }, +] +description = "Script to generate configs for nebula VPN" +# readme = "README.md" +requires-python = ">=3.8" +classifiers = [ + "Programming Language :: Python :: 3", + "Operating System :: OS Independent", +] +license = "BSD-3-Clause" +license-files = ["LICENSE"] + +[project.urls] +Homepage = "https://github.com/norohind/nebula_confgen" +Issues = "https://github.com/norohind/nebula_confgen/issues" diff --git a/src/nebula_confgen/__init__.py b/src/nebula_confgen/__init__.py new file mode 100644 index 0000000..27dd5a9 --- /dev/null +++ b/src/nebula_confgen/__init__.py @@ -0,0 +1,2 @@ +from .ansible_helper import AnsibleHost, generate_config, generate_inventory +from .netstack import AuthorizedUser, FirewallRule, Host, NetStack, UnsafeRoute diff --git a/src/nebula_confgen/ansible_helper.py b/src/nebula_confgen/ansible_helper.py new file mode 100644 index 0000000..16f3c2d --- /dev/null +++ b/src/nebula_confgen/ansible_helper.py @@ -0,0 +1,65 @@ +import json +from dataclasses import dataclass +from pathlib import Path + +from .netstack import Host, NetStack + + +@dataclass(frozen=True) +class AnsibleHost(Host): + """Represents ansible host""" + + ansible_host: str = None + nebula_groups: str | None = None + inventory_include: bool = True + nebula_service_name: str = None + service_manager: str = None + + def __post_init__(self): + assert self.ansible_host + + +def get_output_dir(output_dir: Path = None) -> Path: + if output_dir is None: + output_dir = Path(__file__).parent.parent + + return output_dir + +def generate_config(stack: NetStack, output_dir: Path = None) -> None: + import yaml + + output_dir = get_output_dir(output_dir) + + generated = output_dir / Path('configs') + generated.mkdir(exist_ok=True) + + for host in stack.hosts: + config = stack.get_config(host) + (generated / (host.name + '.yaml')).write_text(yaml.dump(config)) + +def generate_inventory(stack: NetStack, output_dir: Path = None) -> None: + # Produce inventory for use with ansible + + output_dir = get_output_dir(output_dir) + + inventory_hosts = dict() + for host in stack.hosts: + if not (isinstance(host, AnsibleHost) or getattr(host, 'inventory_include')): + print(f"Skipping host {host.name!r} for ansible inventory") + continue + + host_vars = { + 'ansible_host': host.ansible_host, + 'nebula_addr': f'{host.addr}/{host.subnet}' + } + + for var_name in ('nebula_groups', 'nebula_service_name', 'service_manager'): + if getattr(host, var_name): + host_vars[var_name] = getattr(host, var_name) + + inventory_hosts[host.name] = host_vars + + inventory = {'linux': {'hosts': inventory_hosts}} + + with open(output_dir / 'inventory.json', 'w', encoding='utf-8') as f: + json.dump(inventory, f, indent=2, ensure_ascii=False) diff --git a/src/nebula_confgen/netstack.py b/src/nebula_confgen/netstack.py new file mode 100644 index 0000000..9d3931d --- /dev/null +++ b/src/nebula_confgen/netstack.py @@ -0,0 +1,167 @@ +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Iterable, Literal, NotRequired, TypedDict + + +class FirewallRule(TypedDict): + port: int | str + proto: Literal['any', 'tcp', 'udp', 'icmp'] + ca_name: NotRequired[str] + ca_sha: NotRequired[str] + host: NotRequired[str] + group: NotRequired[str] + groups: NotRequired[list[str]] + cidr: NotRequired[str] + local_cidr: NotRequired[str] + +@dataclass(frozen=True) +class AuthorizedUser: + user: str + keys: tuple[str, ...] + + +@dataclass(frozen=True) +class UnsafeRoute: + route: str # 172.16.1.0/24 + via: str # 192.168.100.99 + mtu: int # 1300 + metric: int # 100 + install: bool = True + +@dataclass(frozen=True) +class Host: + name: str + addr: str + subnet: int = 24 + public_addresses: Iterable[str] = tuple() + inbound_rules: tuple[FirewallRule, ...] = tuple() + merge_stack_inbound_rules: bool = True + config_prefix: str = "/etc/nebula" + am_lighthouse: bool = False + am_relay: bool = False + serve_dns: bool = None + tun_disabled: bool = False + tun_name: str = 'nebula1' + dns_host: str = "self.addr" + dns_port: int = 53 + + +class NetStack: + def __init__( + self, + hosts: list[Host], + ca: list[Path], + listen_port: int = 4242, + pki_blocklist: Iterable[str] = None, + default_inbound_rules: tuple[FirewallRule, ...] = tuple(), + authorized_users: tuple[AuthorizedUser, ...] = tuple() + ): + self.hosts: set[Host] = set() + + self.listen_port = listen_port + self.ca: list[str] = list() + for ca_path in ca: + self.ca.append(ca_path.read_text()) + + if pki_blocklist is None: + pki_blocklist = list() + + self.pki_blocklist = pki_blocklist + self.add_hosts(hosts) + + self.default_inbound_rules = default_inbound_rules + self.authorized_users = authorized_users + + def add_host(self, host: Host) -> None: + self.hosts.add(host) + + def add_hosts(self, hosts: Iterable[Host]) -> None: + for host in hosts: + self.add_host(host) + + def get_static_host_map_for(self, hostname: str) -> dict[str, list[str]]: + res = dict() + for host in self.hosts: + if host.am_lighthouse is True and host.name != hostname: + res[host.addr] = [f'{addr}:{self.listen_port}' for addr in host.public_addresses] + + return res + + def get_lighthouses_for(self, hostname: str) -> list[str]: + return [host.addr for host in self.hosts if host.am_lighthouse and host.name != hostname] + + def get_config(self, host: Host) -> ...: + serve_dns = host.serve_dns if host.serve_dns is not None else host.am_lighthouse + + inbound_rules: list[FirewallRule] = list(host.inbound_rules) + if host.merge_stack_inbound_rules: + inbound_rules.extend(self.default_inbound_rules) + + if serve_dns: + inbound_rules.append({'port': 53, 'proto': 'any', 'group': 'any'}) + + advertise_addrs: list[str] = [] + for addr in host.public_addresses: + if ':' not in addr: + addr = addr + ':0' + + advertise_addrs.append(addr) + + return { + 'pki': { + 'ca': '\n'.join(ca for ca in self.ca), # We do support more than 1 ca for ca rotation + 'cert': f'{host.config_prefix}/{host.name}.crt', + 'key': f'{host.config_prefix}/{host.name}.key', + 'blocklist': self.pki_blocklist, + 'disconnect_invalid': True, + }, + 'static_host_map': self.get_static_host_map_for(host.name), + 'lighthouse': { + 'am_lighthouse': host.am_lighthouse, + 'serve_dns': serve_dns, + 'dns': { + 'host': host.addr if host.dns_host == 'self.addr' else host.dns_host, + 'port': host.dns_port + }, + 'hosts': sorted(self.get_lighthouses_for(host.name)), + 'local_allow_list': {'0.0.0.0/0': False}, + 'advertise_addrs': advertise_addrs + }, + 'listen': { + 'port': self.listen_port + }, + 'punchy': { + 'respond': True + }, + 'preferred_ranges': ['192.168.1.0/24'], + 'relay': { + 'relays': sorted([other_host.addr for other_host in self.hosts if not host.am_relay and other_host.am_relay]), # No relays if the host is relay + 'am_relay': host.am_relay, + }, + 'tun': { + 'disabled': host.tun_disabled, + 'dev': host.tun_name, + 'unsafe_routes': [] # TODO: UnsafeRoute + }, + 'sshd': { + 'enabled': True, + 'listen': host.addr + ':2222', + 'host_key': f'{host.config_prefix}/ssh_host_ed25519_key', + 'authorized_users': [{'user': i.user, 'keys': list(i.keys)} for i in self.authorized_users] + }, + 'firewall': { + 'outbound_action': 'drop', + 'inbound_action': 'drop', + 'conntrack': { + 'tcp_timeout': '12m', + 'udp_timeout': '3m', + 'default_timeout': '10m', + }, + 'outbound': [{ + 'port': 'any', + 'proto': 'any', + 'host': 'any' + }], + 'inbound': inbound_rules + } + }