mirror of
https://github.com/donaldzou/WGDashboard.git
synced 2026-11-20 12:43:17 +01:00
+1






![dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>](/assets/img/avatar_default.png)


DaanSelen
GitHub
dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
neolegshishov
unixro
LEE Kai-Ze
Mikhail Solovev
Evgeny Volferts
Theroxenes
torms
dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
8d21152947
* Fix: batch IP geolocation requests (limit 100), add deduplication and caching (#1232) - Added batching of IP addresses into chunks of 100 to comply with ip-api limits - Implemented deduplication to avoid repeated geolocation requests for identical IPs - Added in-memory cache to reuse results across batches - Preserved original order and length of geolocation list in API response - Improved error handling around external API failures * fix: addPeers uses OverridePeerSettings for DNS and AllowedIPs fallback (#1310) * fix: addPeers uses OverridePeerSettings for DNS and AllowedIPs fallback When adding a peer via the API without explicit DNS or endpoint_allowed_ip values, the endpoint fell back directly to global wg-dashboard.ini defaults, ignoring any per-configuration OverridePeerSettings. This caused new peers to be stored with the wrong DNS and AllowedIPs in the database even when the configuration had overrides set. Resolve by fetching the configuration's OverridePeerSettings before the global defaults. The priority is now: request body → OverridePeerSettings → global default. The existing config lookup that happened later in the function is removed as it is now done earlier. Note: downloadPeer already applied OverridePeerSettings at download time, so client configs were correct; only the stored peer data was affected. * fix: addPeers applies OverridePeerSettings for MTU and PersistentKeepalive Extend the peer-settings priority chain (request body → OverridePeerSettings → global default) to MTU and PersistentKeepalive, matching the same pattern already applied to DNS and EndpointAllowedIPs. * style: align addPeers OverridePeerSettings fallback with project code style * Fix: backup regex, SQL cleanup, and restore metadata conflict (#1324) * fix: backup filename regex dot escaping * fix: delete paired .sql file when removing backup * fix: restore backup metadata conflict * Bug fix. Remove redundant break statement in IP allocation loop. (#1294) * Remove redundant break statement in IP allocation loop. * Fix: append IP to allowed_ips list instead of overwriting it * fix: clean up endpoint history tables on rename and delete (#1367) * Add new AmneziaWG parameters (implemented in 3.0/3.1) (#1363) * fix: add button type to accountSettingsInputPassword submission button (#1321) * fix: handle instantiated SQLAlchemy column types (#1400) * feat(docker): run drop-in scripts from /data/custom-init.d at startup (#1401) Allows users to install additional packages or apply custom setup by placing scripts in /data/custom-init.d, executed in alphabetical order before WGDashboard starts. * fix: handle existing endpoint history table during AmneziaWG restore (#1368) * build(deps): bump pydantic from 2.14.1 to 2.14.2 in /src (#1403) Bumps [pydantic](https://github.com/pydantic/pydantic) from 2.14.1 to 2.14.2. - [Release notes](https://github.com/pydantic/pydantic/releases) - [Changelog](https://github.com/pydantic/pydantic/blob/v2.14.2/HISTORY.md) - [Commits](https://github.com/pydantic/pydantic/compare/v2.14.1...v2.14.2) --- updated-dependencies: - dependency-name: pydantic dependency-version: 2.14.2 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * build(deps): bump @vue/language-server in /src/static/app (#1404) Bumps [@vue/language-server](https://github.com/vuejs/language-tools/tree/HEAD/packages/language-server) from 3.3.13 to 3.3.14. - [Release notes](https://github.com/vuejs/language-tools/releases) - [Changelog](https://github.com/vuejs/language-tools/blob/master/CHANGELOG.md) - [Commits](https://github.com/vuejs/language-tools/commits/v3.3.14/packages/language-server) --- updated-dependencies: - dependency-name: "@vue/language-server" dependency-version: 3.3.14 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * build(deps): bump axios from 1.20.0 to 1.21.0 in /src/static/client (#1405) Bumps [axios](https://github.com/axios/axios) from 1.20.0 to 1.21.0. - [Release notes](https://github.com/axios/axios/releases) - [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) - [Commits](https://github.com/axios/axios/compare/v1.20.0...v1.21.0) --- updated-dependencies: - dependency-name: axios dependency-version: 1.21.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: neolegshishov <143963760+neolegshishov@users.noreply.github.com> Co-authored-by: unixro <mihaivint@users.noreply.github.com> Co-authored-by: LEE Kai-Ze <mail@leekaize.com> Co-authored-by: Mikhail Solovev <mike@solovjov.net> Co-authored-by: Evgeny Volferts <eugene.wolferz@gmail.com> Co-authored-by: Theroxenes <theroxenes@proton.me> Co-authored-by: torms <8841885+torms@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
338 lines
14 KiB
Python
338 lines
14 KiB
Python
"""
|
|
Dashboard Configuration
|
|
"""
|
|
import configparser, secrets, os, pyotp, ipaddress, bcrypt
|
|
from sqlalchemy_utils import database_exists, create_database
|
|
import sqlalchemy as db
|
|
from datetime import datetime
|
|
from typing import Any
|
|
from flask import current_app
|
|
from .DatabaseConnection import ConnectionString
|
|
from .Utilities import (GetRemoteEndpoint, ValidateDNSAddress)
|
|
from .DashboardAPIKey import DashboardAPIKey
|
|
|
|
class DashboardConfig:
|
|
DashboardVersion = 'v4.3.4'
|
|
ConfigurationPath = os.getenv('CONFIGURATION_PATH', '.')
|
|
ConfigurationFilePath = os.path.join(ConfigurationPath, 'wg-dashboard.ini')
|
|
|
|
def __init__(self):
|
|
if not os.path.exists(DashboardConfig.ConfigurationFilePath):
|
|
open(DashboardConfig.ConfigurationFilePath, "x")
|
|
self.__config = configparser.RawConfigParser(strict=False)
|
|
self.__config.read_file(open(DashboardConfig.ConfigurationFilePath, "r+"))
|
|
self.hiddenAttribute = ["totp_key", "auth_req"]
|
|
self.__default = {
|
|
"Account": {
|
|
"username": "admin",
|
|
"password": "admin",
|
|
"enable_totp": "false",
|
|
"totp_verified": "false",
|
|
"totp_key": pyotp.random_base32()
|
|
},
|
|
"Server": {
|
|
"wg_conf_path": "/etc/wireguard",
|
|
"awg_conf_path": "/etc/amnezia/amneziawg",
|
|
"app_prefix": "",
|
|
"app_ip": "0.0.0.0",
|
|
"app_port": "10086",
|
|
"auth_req": "true",
|
|
"version": DashboardConfig.DashboardVersion,
|
|
"dashboard_refresh_interval": "60000",
|
|
"dashboard_peer_list_display": "grid",
|
|
"dashboard_sort": "status",
|
|
"dashboard_theme": "dark",
|
|
"dashboard_api_key": "false",
|
|
"dashboard_language": "en-US"
|
|
},
|
|
"Peers": {
|
|
"peer_global_DNS": "1.1.1.1",
|
|
"peer_endpoint_allowed_ip": "0.0.0.0/0",
|
|
"peer_display_mode": "grid",
|
|
"remote_endpoint": GetRemoteEndpoint(),
|
|
"peer_MTU": "1420",
|
|
"peer_keep_alive": "21",
|
|
"peer_preshared_key_default": "false"
|
|
},
|
|
"Other": {
|
|
"welcome_session": "true"
|
|
},
|
|
"Database":{
|
|
"type": "sqlite",
|
|
"host": "",
|
|
"port": "",
|
|
"username": "",
|
|
"password": ""
|
|
},
|
|
"Email":{
|
|
"server": "",
|
|
"port": "",
|
|
"encryption": "",
|
|
"username": "",
|
|
"email_password": "",
|
|
"authentication_required": "true",
|
|
"send_from": "",
|
|
"email_template": ""
|
|
},
|
|
"OIDC": {
|
|
"admin_enable": "false",
|
|
"client_enable": "false"
|
|
},
|
|
"Clients": {
|
|
"enable": "true",
|
|
"sign_up": "true"
|
|
},
|
|
"WireGuardConfiguration": {
|
|
"autostart": "",
|
|
"peer_tracking": "false"
|
|
}
|
|
}
|
|
|
|
for section, keys in self.__default.items():
|
|
for key, value in keys.items():
|
|
exist, currentData = self.GetConfig(section, key)
|
|
if not exist:
|
|
self.SetConfig(section, key, value, True)
|
|
|
|
self.engine = db.create_engine(ConnectionString('wgdashboard'))
|
|
self.dbMetadata = db.MetaData()
|
|
self.__createAPIKeyTable()
|
|
self.DashboardAPIKeys = self.__getAPIKeys()
|
|
self.APIAccessed = False
|
|
self.SetConfig("Server", "version", DashboardConfig.DashboardVersion)
|
|
|
|
def EnsureDatabaseIntegrity(self, wireguardConfigurations):
|
|
expected_columns = {
|
|
'id': db.String(255),
|
|
'private_key': db.String(255),
|
|
'DNS': db.Text,
|
|
'endpoint_allowed_ip': db.Text,
|
|
'name': db.Text,
|
|
'total_receive': db.Float,
|
|
'total_sent': db.Float,
|
|
'total_data': db.Float,
|
|
'endpoint': db.String(255),
|
|
'status': db.String(255),
|
|
'latest_handshake': db.String(255),
|
|
'allowed_ip': db.String(255),
|
|
'cumu_receive': db.Float,
|
|
'cumu_sent': db.Float,
|
|
'cumu_data': db.Float,
|
|
'mtu': db.Integer,
|
|
'keepalive': db.Integer,
|
|
'notes': db.Text,
|
|
'remote_endpoint': db.String(255),
|
|
'preshared_key': db.String(255)
|
|
}
|
|
|
|
inspector = db.inspect(self.engine)
|
|
|
|
with self.engine.begin() as conn:
|
|
for cfg_name, cfg_obj in wireguardConfigurations.items():
|
|
tables_to_check = [
|
|
cfg_name,
|
|
f'{cfg_name}_restrict_access',
|
|
f'{cfg_name}_deleted'
|
|
]
|
|
|
|
for table_name in tables_to_check:
|
|
if not table_name:
|
|
continue
|
|
if not inspector.has_table(table_name):
|
|
continue
|
|
|
|
existing_columns = [c['name'] for c in inspector.get_columns(table_name)]
|
|
|
|
for col_name, col_type in expected_columns.items():
|
|
if col_name not in existing_columns:
|
|
type_str = (
|
|
col_type if isinstance(col_type, db.types.TypeEngine) else col_type()
|
|
).compile(dialect=self.engine.dialect)
|
|
current_app.logger.info(f"Adding missing column '{col_name}' to table '{table_name}'")
|
|
preparer = self.engine.dialect.identifier_preparer
|
|
quoted_table = preparer.quote_identifier(table_name)
|
|
quoted_column = preparer.quote_identifier(col_name)
|
|
conn.execute(db.text(f"ALTER TABLE {quoted_table} ADD COLUMN {quoted_column} {type_str}"))
|
|
|
|
def getConnectionString(self, database) -> str or None:
|
|
sqlitePath = os.path.join(DashboardConfig.ConfigurationPath, "db")
|
|
|
|
if not os.path.isdir(sqlitePath):
|
|
os.mkdir(sqlitePath)
|
|
|
|
if self.GetConfig("Database", "type")[1] == "postgresql":
|
|
cn = f'postgresql+psycopg2://{self.GetConfig("Database", "username")[1]}:{self.GetConfig("Database", "password")[1]}@{self.GetConfig("Database", "host")[1]}/{database}'
|
|
elif self.GetConfig("Database", "type")[1] == "mysql":
|
|
cn = f'mysql+mysqldb://{self.GetConfig("Database", "username")[1]}:{self.GetConfig("Database", "password")[1]}@{self.GetConfig("Database", "host")[1]}/{database}'
|
|
else:
|
|
cn = f'sqlite:///{os.path.join(sqlitePath, f"{database}.db")}'
|
|
if not database_exists(cn):
|
|
create_database(cn)
|
|
return cn
|
|
|
|
def __createAPIKeyTable(self):
|
|
self.apiKeyTable = db.Table('DashboardAPIKeys', self.dbMetadata,
|
|
db.Column("Key", db.String(255), nullable=False, primary_key=True),
|
|
db.Column("CreatedAt",
|
|
(db.DATETIME if self.GetConfig('Database', 'type')[1] == 'sqlite' else db.TIMESTAMP),
|
|
server_default=db.func.now()
|
|
),
|
|
db.Column("ExpiredAt",
|
|
(db.DATETIME if self.GetConfig('Database', 'type')[1] == 'sqlite' else db.TIMESTAMP)
|
|
)
|
|
)
|
|
self.dbMetadata.create_all(self.engine)
|
|
def __getAPIKeys(self) -> list[DashboardAPIKey]:
|
|
try:
|
|
with self.engine.connect() as conn:
|
|
keys = conn.execute(self.apiKeyTable.select().where(
|
|
db.or_(self.apiKeyTable.columns.ExpiredAt.is_(None), self.apiKeyTable.columns.ExpiredAt > datetime.now())
|
|
)).fetchall()
|
|
fKeys = []
|
|
for k in keys:
|
|
fKeys.append(DashboardAPIKey(k[0], k[1].strftime("%Y-%m-%d %H:%M:%S"), (k[2].strftime("%Y-%m-%d %H:%M:%S") if k[2] else None)))
|
|
return fKeys
|
|
except Exception as e:
|
|
current_app.logger.error("API Keys error", e)
|
|
return []
|
|
|
|
def createAPIKeys(self, ExpiredAt = None):
|
|
newKey = secrets.token_urlsafe(32)
|
|
with self.engine.begin() as conn:
|
|
conn.execute(
|
|
self.apiKeyTable.insert().values({
|
|
"Key": newKey,
|
|
"ExpiredAt": ExpiredAt
|
|
})
|
|
)
|
|
|
|
self.DashboardAPIKeys = self.__getAPIKeys()
|
|
|
|
def deleteAPIKey(self, key):
|
|
with self.engine.begin() as conn:
|
|
conn.execute(
|
|
self.apiKeyTable.update().values({
|
|
"ExpiredAt": datetime.now(),
|
|
}).where(self.apiKeyTable.columns.Key == key)
|
|
)
|
|
|
|
self.DashboardAPIKeys = self.__getAPIKeys()
|
|
|
|
def __configValidation(self, section : str, key: str, value: Any) -> tuple[bool, str]:
|
|
if (type(value) is str and len(value) == 0
|
|
and section not in ['Email', 'WireGuardConfiguration'] and
|
|
(section == 'Peer' and key == 'peer_global_dns')):
|
|
return False, "Field cannot be empty!"
|
|
if section == "Peers" and key == "peer_global_dns" and len(value) > 0:
|
|
return ValidateDNSAddress(value)
|
|
if section == "Peers" and key == "peer_endpoint_allowed_ip":
|
|
value = value.split(",")
|
|
for i in value:
|
|
i = i.strip()
|
|
try:
|
|
ipaddress.ip_network(i, strict=False)
|
|
except Exception as e:
|
|
return False, str(e)
|
|
if section == "Server" and key == "wg_conf_path":
|
|
if not os.path.exists(value):
|
|
return False, f"{value} is not a valid path"
|
|
if section == "Account" and key == "password":
|
|
if self.GetConfig("Account", "password")[0]:
|
|
if not self.__checkPassword(
|
|
value["currentPassword"], self.GetConfig("Account", "password")[1].encode("utf-8")):
|
|
return False, "Current password does not match."
|
|
if value["newPassword"] != value["repeatNewPassword"]:
|
|
return False, "New passwords does not match"
|
|
return True, ""
|
|
|
|
def generatePassword(self, plainTextPassword: str):
|
|
return bcrypt.hashpw(plainTextPassword.encode("utf-8"), bcrypt.gensalt())
|
|
|
|
def __checkPassword(self, plainTextPassword: str, hashedPassword: bytes):
|
|
return bcrypt.checkpw(plainTextPassword.encode("utf-8"), hashedPassword)
|
|
|
|
def SetConfig(self, section: str, key: str, value: str | bool | list[str] | dict[str, str], init: bool = False) -> tuple[bool, str] | tuple[bool, None]:
|
|
if key in self.hiddenAttribute and not init:
|
|
return False, None
|
|
|
|
if not init:
|
|
valid, msg = self.__configValidation(section, key, value)
|
|
if not valid:
|
|
return False, msg
|
|
|
|
if section == "Account" and key == "password":
|
|
if not init:
|
|
value = self.generatePassword(value["newPassword"]).decode("utf-8")
|
|
else:
|
|
value = self.generatePassword(value).decode("utf-8")
|
|
|
|
if section == "Email" and key == "email_template":
|
|
value = value.encode('unicode_escape').decode('utf-8')
|
|
|
|
if section == "Server" and key == "wg_conf_path":
|
|
if not os.path.exists(value):
|
|
return False, "Path does not exist"
|
|
|
|
if section not in self.__config:
|
|
if init:
|
|
self.__config[section] = {}
|
|
else:
|
|
return False, "Section does not exist"
|
|
|
|
if ((key not in self.__config[section].keys() and init) or
|
|
(key in self.__config[section].keys())):
|
|
if type(value) is bool:
|
|
if value:
|
|
self.__config[section][key] = "true"
|
|
else:
|
|
self.__config[section][key] = "false"
|
|
elif type(value) in [int, float]:
|
|
self.__config[section][key] = str(value)
|
|
elif type(value) is list:
|
|
self.__config[section][key] = "||".join(value).strip("||")
|
|
else:
|
|
self.__config[section][key] = fr"{value}"
|
|
return self.SaveConfig(), ""
|
|
else:
|
|
return False, f"{key} does not exist under {section}"
|
|
|
|
def SaveConfig(self) -> bool:
|
|
try:
|
|
with open(DashboardConfig.ConfigurationFilePath, "w+", encoding='utf-8') as configFile:
|
|
self.__config.write(configFile)
|
|
return True
|
|
except Exception as e:
|
|
return False
|
|
|
|
def GetConfig(self, section, key) ->tuple[bool, bool] | tuple[bool, str] | tuple[bool, list[str]] | tuple[bool, None]:
|
|
if section not in self.__config:
|
|
return False, None
|
|
|
|
if key not in self.__config[section]:
|
|
return False, None
|
|
|
|
if section == "Email" and key == "email_template":
|
|
return True, self.__config[section][key].encode('utf-8').decode('unicode_escape')
|
|
|
|
if section == "WireGuardConfiguration" and key == "autostart":
|
|
return True, list(filter(lambda x: len(x) > 0, self.__config[section][key].split("||")))
|
|
|
|
if self.__config[section][key] in ["1", "yes", "true", "on"]:
|
|
return True, True
|
|
|
|
if self.__config[section][key] in ["0", "no", "false", "off"]:
|
|
return True, False
|
|
|
|
|
|
return True, self.__config[section][key]
|
|
|
|
def toJson(self) -> dict[str, dict[Any, Any]]:
|
|
the_dict = {}
|
|
|
|
for section in self.__config.sections():
|
|
the_dict[section] = {}
|
|
for key, val in self.__config.items(section):
|
|
if key not in self.hiddenAttribute:
|
|
the_dict[section][key] = self.GetConfig(section, key)[1]
|
|
return the_dict
|