mirror of
https://github.com/norohind/nebula_confgen.git
synced 2026-11-24 00:16:41 +03:00
init
This commit is contained in:
6 files changed
+282
No files matched your search
@@ -0,0 +1 @@
|
||||
__pycache__
|
||||
@@ -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.
|
||||
@@ -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"
|
||||
@@ -0,0 +1,2 @@
|
||||
from .ansible_helper import AnsibleHost, generate_config, generate_inventory
|
||||
from .netstack import AuthorizedUser, FirewallRule, Host, NetStack, UnsafeRoute
|
||||
@@ -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)
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user