2020-11-16 03:40:33 +01:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
|
|
Name: Database Manager
|
2021-01-13 02:47:40 +01:00
|
|
|
Creator: K4YT3X
|
2020-11-16 03:40:33 +01:00
|
|
|
Date Created: July 19, 2020
|
2021-05-29 19:04:21 +02:00
|
|
|
Last Modified: May 29, 2021
|
2020-11-16 03:40:33 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
# built-in imports
|
2021-01-13 03:30:57 +01:00
|
|
|
import contextlib
|
2020-11-16 03:40:33 +01:00
|
|
|
import copy
|
2021-05-29 19:04:21 +02:00
|
|
|
import csv
|
2020-11-16 03:40:33 +01:00
|
|
|
import pathlib
|
|
|
|
import sys
|
|
|
|
|
|
|
|
# third party imports
|
2021-01-13 03:30:57 +01:00
|
|
|
with contextlib.suppress(ImportError):
|
|
|
|
from prettytable import PrettyTable
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
# local imports
|
2021-05-29 19:04:21 +02:00
|
|
|
from .wireguard import WireGuard
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
INTERFACE_ATTRIBUTES = [
|
|
|
|
"Address",
|
|
|
|
"ListenPort",
|
|
|
|
"FwMark",
|
|
|
|
"PrivateKey",
|
|
|
|
"DNS",
|
|
|
|
"MTU",
|
|
|
|
"Table",
|
|
|
|
"PreUp",
|
|
|
|
"PostUp",
|
|
|
|
"PreDown",
|
|
|
|
"PostDown",
|
|
|
|
"SaveConfig",
|
|
|
|
]
|
|
|
|
|
|
|
|
INTERFACE_OPTIONAL_ATTRIBUTES = [
|
|
|
|
"ListenPort",
|
|
|
|
"FwMark",
|
|
|
|
"DNS",
|
|
|
|
"MTU",
|
|
|
|
"Table",
|
|
|
|
"PreUp",
|
|
|
|
"PostUp",
|
|
|
|
"PreDown",
|
|
|
|
"PostDown",
|
|
|
|
"SaveConfig",
|
|
|
|
]
|
|
|
|
|
|
|
|
PEER_ATTRIBUTES = [
|
|
|
|
"PublicKey",
|
|
|
|
"PresharedKey",
|
|
|
|
"AllowedIPs",
|
|
|
|
"Endpoint",
|
|
|
|
"PersistentKeepalive",
|
|
|
|
]
|
|
|
|
|
2021-05-21 23:37:28 +02:00
|
|
|
PEER_OPTIONAL_ATTRIBUTES = [
|
|
|
|
"PersistentKeepalive",
|
|
|
|
]
|
|
|
|
|
2021-05-29 19:04:21 +02:00
|
|
|
KEY_TYPE = {
|
|
|
|
"name": str,
|
|
|
|
"Address": list,
|
|
|
|
"Endpoint": str,
|
|
|
|
"AllowedIPs": list,
|
|
|
|
"ListenPort": int,
|
|
|
|
"PersistentKeepalive": int,
|
|
|
|
"FwMark": str,
|
|
|
|
"PrivateKey": str,
|
|
|
|
"DNS": str,
|
|
|
|
"MTU": int,
|
|
|
|
"Table": str,
|
|
|
|
"PreUp": str,
|
|
|
|
"PostUp": str,
|
|
|
|
"PreDown": str,
|
|
|
|
"PostDown": str,
|
|
|
|
"SaveConfig": bool,
|
|
|
|
}
|
|
|
|
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
class DatabaseManager:
|
|
|
|
def __init__(self, database_path: pathlib.Path):
|
|
|
|
self.database_path = database_path
|
|
|
|
self.database_template = {"peers": {}}
|
|
|
|
self.wireguard = WireGuard()
|
|
|
|
|
|
|
|
def read_database(self):
|
2021-01-13 02:47:40 +01:00
|
|
|
"""read database file into dict
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
Returns:
|
|
|
|
dict: content of database file in dict format
|
|
|
|
"""
|
|
|
|
if not self.database_path.is_file():
|
|
|
|
return self.database_template
|
|
|
|
|
2021-05-29 19:04:21 +02:00
|
|
|
database = copy.deepcopy(self.database_template)
|
|
|
|
|
2020-11-16 03:40:33 +01:00
|
|
|
with self.database_path.open(mode="r", encoding="utf-8") as database_file:
|
2021-05-29 19:04:21 +02:00
|
|
|
peers = csv.DictReader(database_file)
|
|
|
|
for peer in peers:
|
|
|
|
for key in peer:
|
|
|
|
if peer[key] == "":
|
|
|
|
peer[key] = None
|
|
|
|
elif KEY_TYPE[key] == list:
|
|
|
|
peer[key] = peer[key].split(",")
|
|
|
|
elif KEY_TYPE[key] == int:
|
|
|
|
peer[key] = int(peer[key])
|
|
|
|
elif KEY_TYPE[key] == bool:
|
|
|
|
peer[key] = peer[key].lower() == "true"
|
|
|
|
database["peers"][peer.pop("name")] = peer
|
|
|
|
|
|
|
|
return database
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
def write_database(self, data: dict):
|
2021-01-13 02:47:40 +01:00
|
|
|
"""dump data into database file
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
Args:
|
|
|
|
data (dict): content of database
|
|
|
|
"""
|
2021-05-29 19:04:21 +02:00
|
|
|
|
2020-11-16 03:40:33 +01:00
|
|
|
with self.database_path.open(mode="w", encoding="utf-8") as database_file:
|
2021-05-29 19:04:21 +02:00
|
|
|
writer = csv.DictWriter(
|
|
|
|
database_file, KEY_TYPE.keys(), quoting=csv.QUOTE_ALL
|
|
|
|
)
|
|
|
|
writer.writeheader()
|
|
|
|
data = copy.deepcopy(data)
|
|
|
|
for peer in data["peers"]:
|
|
|
|
data["peers"][peer]["name"] = peer
|
|
|
|
for key in data["peers"][peer]:
|
|
|
|
if isinstance(data["peers"][peer][key], list):
|
|
|
|
data["peers"][peer][key] = ",".join(data["peers"][peer][key])
|
|
|
|
elif isinstance(data["peers"][peer][key], int):
|
|
|
|
data["peers"][peer][key] = str(data["peers"][peer][key])
|
|
|
|
elif isinstance(data["peers"][peer][key], bool):
|
|
|
|
data["peers"][peer][key] = str(data["peers"][peer][key])
|
|
|
|
writer.writerow(data["peers"][peer])
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
def addpeer(
|
|
|
|
self,
|
|
|
|
name: str,
|
|
|
|
Address: list,
|
|
|
|
Endpoint: str = None,
|
2020-11-16 18:23:58 +01:00
|
|
|
AllowedIPs: list = None,
|
2020-11-16 03:40:33 +01:00
|
|
|
ListenPort: int = None,
|
2021-05-21 23:37:28 +02:00
|
|
|
PersistentKeepalive: int = None,
|
2020-11-16 03:40:33 +01:00
|
|
|
FwMark: str = None,
|
|
|
|
PrivateKey: str = None,
|
|
|
|
DNS: str = None,
|
|
|
|
MTU: int = None,
|
|
|
|
Table: str = None,
|
|
|
|
PreUp: str = None,
|
|
|
|
PostUp: str = None,
|
|
|
|
PreDown: str = None,
|
|
|
|
PostDown: str = None,
|
|
|
|
SaveConfig: bool = None,
|
|
|
|
):
|
2021-05-29 19:04:21 +02:00
|
|
|
database = self.read_database()
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
if name in database["peers"]:
|
|
|
|
print(f"Peer with name {name} already exists")
|
|
|
|
return
|
|
|
|
|
|
|
|
database["peers"][name] = {}
|
|
|
|
|
|
|
|
# if private key is not specified, generate one
|
|
|
|
if locals().get("PrivateKey") is None:
|
|
|
|
privatekey = self.wireguard.genkey()
|
|
|
|
database["peers"][name]["PrivateKey"] = privatekey
|
|
|
|
|
|
|
|
for key in INTERFACE_ATTRIBUTES + PEER_ATTRIBUTES:
|
|
|
|
if locals().get(key) is not None:
|
|
|
|
database["peers"][name][key] = locals().get(key)
|
|
|
|
|
|
|
|
self.write_database(database)
|
|
|
|
|
|
|
|
def updatepeer(
|
|
|
|
self,
|
|
|
|
name: str,
|
|
|
|
Address: list = None,
|
|
|
|
Endpoint: str = None,
|
2020-11-16 18:23:58 +01:00
|
|
|
AllowedIPs: list = None,
|
2020-11-16 03:40:33 +01:00
|
|
|
ListenPort: int = None,
|
2021-05-21 23:37:28 +02:00
|
|
|
PersistentKeepalive: int = None,
|
2020-11-16 03:40:33 +01:00
|
|
|
FwMark: str = None,
|
|
|
|
PrivateKey: str = None,
|
|
|
|
DNS: str = None,
|
|
|
|
MTU: int = None,
|
|
|
|
Table: str = None,
|
|
|
|
PreUp: str = None,
|
|
|
|
PostUp: str = None,
|
|
|
|
PreDown: str = None,
|
|
|
|
PostDown: str = None,
|
|
|
|
SaveConfig: bool = None,
|
|
|
|
):
|
2021-05-29 19:04:21 +02:00
|
|
|
database = self.read_database()
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
if name not in database["peers"]:
|
|
|
|
print(f"Peer with name {name} does not exist")
|
|
|
|
return
|
|
|
|
|
|
|
|
for key in INTERFACE_ATTRIBUTES + PEER_ATTRIBUTES:
|
|
|
|
if locals().get(key) is not None:
|
|
|
|
database["peers"][name][key] = locals().get(key)
|
|
|
|
|
|
|
|
self.write_database(database)
|
|
|
|
|
|
|
|
def delpeer(self, name: str):
|
2021-05-29 19:04:21 +02:00
|
|
|
database = self.read_database()
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
# abort if user doesn't exist
|
|
|
|
if name not in database["peers"]:
|
|
|
|
print(f"Peer with ID {name} does not exist")
|
|
|
|
return
|
|
|
|
|
|
|
|
database["peers"].pop(name, None)
|
|
|
|
|
|
|
|
# write changes into database
|
|
|
|
self.write_database(database)
|
|
|
|
|
|
|
|
def showpeers(self, name: str, style: str = "table", simplify: bool = False):
|
|
|
|
database = self.read_database()
|
|
|
|
|
|
|
|
# if name is specified, show the specified peer
|
|
|
|
if name is not None:
|
|
|
|
if name not in database["peers"]:
|
|
|
|
print(f"Peer with ID {name} does not exist")
|
|
|
|
return
|
|
|
|
peers = [name]
|
|
|
|
|
|
|
|
# otherwise, show all peers
|
|
|
|
else:
|
|
|
|
peers = [p for p in database["peers"]]
|
|
|
|
|
|
|
|
field_names = ["name"]
|
|
|
|
|
|
|
|
# exclude all columns that only have None's in simplified mode
|
|
|
|
if simplify is True:
|
|
|
|
for peer in peers:
|
|
|
|
for key in INTERFACE_ATTRIBUTES + PEER_ATTRIBUTES:
|
|
|
|
if (
|
|
|
|
database["peers"][peer].get(key) is not None
|
|
|
|
and key not in field_names
|
|
|
|
):
|
|
|
|
field_names.append(key)
|
|
|
|
|
|
|
|
# include all columns by default
|
|
|
|
else:
|
|
|
|
field_names += INTERFACE_ATTRIBUTES + PEER_ATTRIBUTES
|
|
|
|
|
|
|
|
# if the style is table
|
|
|
|
# print with prettytable
|
|
|
|
if style == "table":
|
2021-05-29 19:04:21 +02:00
|
|
|
try:
|
|
|
|
table = PrettyTable()
|
|
|
|
table.field_names = field_names
|
|
|
|
|
|
|
|
for peer in peers:
|
|
|
|
table.add_row(
|
|
|
|
[peer]
|
|
|
|
+ [
|
|
|
|
database["peers"][peer].get(k)
|
|
|
|
if not isinstance(database["peers"][peer].get(k), list)
|
|
|
|
else ",".join(database["peers"][peer].get(k))
|
|
|
|
for k in [i for i in table.field_names if i != "name"]
|
|
|
|
]
|
|
|
|
)
|
2020-11-16 03:40:33 +01:00
|
|
|
|
2021-05-29 19:04:21 +02:00
|
|
|
print(table)
|
|
|
|
except NameError:
|
|
|
|
print("PrettyTable is not installed", sys.stderr)
|
|
|
|
print("Displaying in table mode is not available", sys.stderr)
|
|
|
|
sys.exit(1)
|
2020-11-16 03:40:33 +01:00
|
|
|
|
|
|
|
# if the style is text
|
|
|
|
# print in plaintext format
|
|
|
|
elif style == "text":
|
|
|
|
for peer in peers:
|
|
|
|
print(f"{'peer': <14}{peer}")
|
|
|
|
for key in field_names:
|
|
|
|
print(
|
|
|
|
f"{key: <14}{database['peers'][peer].get(key)}"
|
|
|
|
) if not isinstance(
|
|
|
|
database["peers"][peer].get(key), list
|
|
|
|
) else print(
|
|
|
|
f"{key: <14}{','.join(database['peers'][peer].get(key))}"
|
|
|
|
)
|
|
|
|
print()
|
|
|
|
|
|
|
|
def genconfig(self, name: str, output: pathlib.Path):
|
|
|
|
database = self.read_database()
|
|
|
|
|
|
|
|
# check if peer ID is specified
|
|
|
|
if name is not None:
|
|
|
|
peers = [name]
|
|
|
|
else:
|
|
|
|
peers = [p for p in database["peers"]]
|
|
|
|
|
|
|
|
# check if output directory is valid
|
|
|
|
# create output directory if it does not exist
|
|
|
|
if output.exists() and not output.is_dir():
|
|
|
|
print(
|
|
|
|
"Error: output path already exists and is not a directory",
|
|
|
|
file=sys.stderr,
|
|
|
|
)
|
|
|
|
raise FileExistsError
|
|
|
|
elif not output.exists():
|
2021-05-29 19:04:21 +02:00
|
|
|
print(f"Creating output directory: {output}", sys.stderr)
|
2020-11-16 03:40:33 +01:00
|
|
|
output.mkdir(exist_ok=True)
|
|
|
|
|
|
|
|
# for every peer in the database
|
|
|
|
for peer in peers:
|
|
|
|
with (output / f"{peer}.conf").open("w") as config:
|
|
|
|
config.write("[Interface]\n")
|
|
|
|
config.write("# Name: {}\n".format(peer))
|
|
|
|
config.write(
|
|
|
|
"Address = {}\n".format(
|
|
|
|
", ".join(database["peers"][peer]["Address"])
|
|
|
|
)
|
|
|
|
)
|
|
|
|
config.write(
|
|
|
|
"PrivateKey = {}\n".format(database["peers"][peer]["PrivateKey"])
|
|
|
|
)
|
|
|
|
|
|
|
|
for key in INTERFACE_OPTIONAL_ATTRIBUTES:
|
|
|
|
if database["peers"][peer].get(key) is not None:
|
|
|
|
config.write(
|
|
|
|
"{} = {}\n".format(key, database["peers"][peer][key])
|
|
|
|
)
|
|
|
|
|
|
|
|
# generate [Peer] sections for all other peers
|
|
|
|
for p in [i for i in database["peers"] if i != peer]:
|
|
|
|
config.write("\n[Peer]\n")
|
|
|
|
config.write("# Name: {}\n".format(p))
|
|
|
|
config.write(
|
|
|
|
"PublicKey = {}\n".format(
|
|
|
|
self.wireguard.pubkey(database["peers"][p]["PrivateKey"])
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
if database["peers"][p].get("Endpoint") is not None:
|
|
|
|
config.write(
|
|
|
|
"Endpoint = {}:{}\n".format(
|
|
|
|
database["peers"][p]["Endpoint"],
|
|
|
|
database["peers"][p]["ListenPort"],
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
if database["peers"][p].get("Address") is not None:
|
2020-11-16 18:23:58 +01:00
|
|
|
if database["peers"][p].get("AllowedIPs") is not None:
|
|
|
|
allowed_ips = ", ".join(
|
|
|
|
database["peers"][p]["Address"]
|
|
|
|
+ database["peers"][p]["AllowedIPs"]
|
2020-11-16 03:40:33 +01:00
|
|
|
)
|
2020-11-16 18:23:58 +01:00
|
|
|
else:
|
|
|
|
allowed_ips = ", ".join(database["peers"][p]["Address"])
|
|
|
|
config.write("AllowedIPs = {}\n".format(allowed_ips))
|
2021-05-21 23:37:28 +02:00
|
|
|
|
|
|
|
for key in PEER_OPTIONAL_ATTRIBUTES:
|
|
|
|
if database["peers"][p].get(key) is not None:
|
|
|
|
config.write(
|
|
|
|
"{} = {}\n".format(key, database["peers"][p][key])
|
|
|
|
)
|