4 Commits
Author SHA1 Message Date
asminme 3841e93e32 1.0.3 - poprawa wydajności panelu
Wydanie WGTools-Extended / release (push) Successful in 12s
2026-10-30 03:20:21 +01:00
asminme aadc19341d 1.0.2 - fix network settings, permissions and branding
Wydanie WGTools-Extended / release (push) Successful in 14s
2026-10-30 02:14:52 +01:00
asminme 9c23169339 LICENSE and other static stuff (edit, no build) 2026-10-30 00:48:48 +01:00
asminme db262c6607 1.0.1
Wydanie WGTools-Extended / release (push) Successful in 10s
2026-10-30 00:44:56 +01:00
29 changed files with 362 additions and 720 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
*.sh text eol=lf
*.py text eol=lf
*.service text eol=lf
*.timer text eol=lf
scripts/wgtools-* text eol=lf
+1 -1
View File
@@ -11,5 +11,5 @@ jobs:
- uses: actions/checkout@v4
- name: Utwórz wydanie i załącz pakiet
env:
GITEA_RELEASE_TOKEN: ${{ secrets.GITEA_RELEASE_TOKEN || vars.GITEA_RELEASE_TOKEN }}
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN || vars.RELEASE_TOKEN }}
run: python3 scripts/gitea_release.py
+1
View File
@@ -29,6 +29,7 @@ coverage.xml
htmlcov/
.pytest_cache/
.test-deps/
README.local.md
.mypy_cache/
.ruff_cache/
*.log
+15
View File
@@ -1,5 +1,20 @@
# Changelog
## v1.0.3
- Ograniczono odświeżanie panelu w ukrytych kartach i liczbę odczytów bazy danych.
- Przyspieszono wyszukiwanie historii połączeń oraz zmieniono domyślny interwał odświeżania nowych instalacji na 10 sekund.
## v1.0.2
- Poprawiono wybór marki i przypisywanie uprawnień do sieci.
- Przeniesiono ustawienia nasłuchiwania, SNAT i adresów do przekierowań do formularzy sieci.
- Poprawiono dostęp użytkowników do przydzielonych sieci i pulpitu oraz edycję grup adresów.
## v1.0.1
- Poprawiono nazwę tokenu używanego do publikacji wydania.
## v0.40.5
- Added an Audit shortcut to the top bar; the audit dialog can now open on any page.
-1
View File
@@ -2,7 +2,6 @@ MIT License
Copyright (c) 2026 Asmin Studios
Copyright (c) 2026 KindMich and WGTools contributors at https://github.com/KindMich/WGTools
Copyright (c) 2026 WGTools contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+30 -28
View File
@@ -1,59 +1,61 @@
# Privacy and Data Flow
# Prywatność i przepływ danych
WGTools is designed as a self-hosted administration tool.
WGTools-Extended jest narzędziem administracyjnym instalowanym na własnym serwerze.
## No application telemetry
## Telemetria aplikacji
WGTools does not include analytics, advertising SDKs or background telemetry to the project maintainer.
WGTools-Extended nie zawiera analityki, reklamowych zestawów SDK ani działającej w tle telemetrii wysyłanej do opiekuna projektu.
The application does not intentionally upload your:
Aplikacja nie wysyła celowo:
- WireGuard server private key;
- client private keys;
- peer list;
- local network topology;
- WGTools usernames, optional account e-mail addresses and password hashes;
- traffic counters;
- configuration backups.
- klucza prywatnego serwera WireGuard;
- kluczy prywatnych klientów;
- listy połączeń WireGuard;
- topologii sieci lokalnej;
- nazw użytkowników, opcjonalnych adresów e-mail i skrótów haseł;
- liczników ruchu;
- kopii zapasowych konfiguracji.
## External network connections
## Zewnętrzne połączenia sieciowe
### Let’s Encrypt / ACME
### Let's Encrypt / ACME
If and only if an administrator requests a built-in HTTPS certificate, WGTools invokes the locally installed Certbot client to contact Let’s Encrypt ACME services for certificate issuance. While built-in HTTPS remains enabled, a systemd timer runs Certbot renewal automatically. The requested domain or public IP and Let’s Encrypt account e-mail are necessarily sent to the certificate authority as part of the ACME process. TCP port `80` must be reachable from the Internet for the standalone HTTP-01 validation used by WGTools. The resulting certificate and private key remain on the server under `/etc/letsencrypt/live/wgtools/`.
Gdy administrator zażąda wbudowanego certyfikatu HTTPS, aplikacja uruchamia lokalnego klienta Certbot, który łączy się z usługą ACME Let's Encrypt w celu jego uzyskania. Dopóki wbudowane HTTPS jest włączone, timer systemd automatycznie uruchamia odnawianie certyfikatu. W ramach procesu ACME do wystawcy certyfikatu przekazywana jest wybrana domena lub publiczny adres IP oraz adres e-mail konta Let's Encrypt. Do weryfikacji HTTP-01 wykorzystywanej przez aplikację port TCP `80` musi być dostępny z internetu. Certyfikat i klucz prywatny pozostają na serwerze w katalogu `/etc/letsencrypt/live/wgtools/`.
### Mail / SMTP
### Poczta / SMTP
If and only if Mail is configured and used, WGTools connects to the administrator-supplied SMTP server to send test messages and password-recovery codes. SMTP host/login/sender settings and the optional SMTP password are stored locally in the WGTools SQLite database. The password is not returned by the settings API and is redacted from Audit. Password-reset codes are stored only as salted PBKDF2 hashes, expire after 15 minutes and are one-time use.
Jeśli poczta jest skonfigurowana i używana, aplikacja łączy się ze wskazanym przez administratora serwerem SMTP, aby wysyłać wiadomości testowe i kody odzyskiwania hasła. Ustawienia serwera, loginu i nadawcy oraz opcjonalne hasło SMTP są przechowywane lokalnie w bazie SQLite. Hasło nie jest zwracane przez API ustawień i jest ukrywane w dzienniku zdarzeń. Kody resetowania haseł są przechowywane wyłącznie jako skróty PBKDF2 z solą, wygasają po 15 minutach i można ich użyć tylko raz.
### Telegram
If and only if Telegram Bot integration is configured and enabled, WGTools connects to:
Jeśli integracja z botem Telegram jest skonfigurowana i włączona, aplikacja łączy się z:
```text
https://api.telegram.org
```
The bot uses long polling and sends the messages/files necessary for the actions requested by authorized Telegram users.
Bot korzysta z długiego odpytywania i wysyła wiadomości oraz pliki potrzebne do wykonania działań zleconych przez uprawnionych użytkowników Telegrama.
### Optional traceroute map geolocation
### Opcjonalna geolokalizacja trasy
The **Server → Trace** diagnostic can optionally draw public route hops on an interactive map. Only when **Show route on map** is enabled, WGTools sends the public IP addresses returned by traceroute to `https://ipwho.is` to obtain approximate coordinates and network/location labels. Private/local hop addresses are not sent. Results are cached locally in `/run` for up to 24 hours to reduce repeated lookups. The browser also requests map tiles from OpenStreetMap (`tile.openstreetmap.org`), so that service can see the browser IP address and the map tile coordinates being viewed. Ping and traceroute themselves do not use either service.
Narzędzie **Serwer → Trasa** może opcjonalnie wyświetlać publiczne węzły trasy na interaktywnej mapie. Tylko po włączeniu opcji pokazywania trasy na mapie aplikacja wysyła publiczne adresy IP uzyskane z traceroute do `https://ipwho.is`, aby pobrać przybliżone współrzędne i informacje o sieci oraz lokalizacji. Adresy prywatne i lokalne nie są wysyłane. Wyniki są przechowywane lokalnie w `/run` do 24 godzin, aby ograniczyć liczbę zapytań. Przeglądarka pobiera również fragmenty mapy z OpenStreetMap (`tile.openstreetmap.org`); usługa ta może więc zobaczyć adres IP przeglądarki i współrzędne oglądanych fragmentów mapy. Same polecenia ping i traceroute nie korzystają z tych usług.
### Debian / Ubuntu package repositories
### Repozytoria pakietów Debian / Ubuntu
When an administrator installs packages from the UI or runs the installer, `apt` contacts the Debian/Ubuntu repositories configured on the host.
Gdy administrator instaluje pakiety z panelu lub uruchamia instalator, `apt` łączy się z repozytoriami Debian lub Ubuntu skonfigurowanymi na serwerze.
### Instalacja i aktualizacje
Instalator uruchamia się z lokalnych plików projektu. Administrator ręcznie wgrywa pakiet aktualizacji; aplikacja nie sprawdza serwerów aktualizacyjnych oryginalnego projektu.
## Local browser data
## Dane w przeglądarce
The browser may store UI preferences and previously entered endpoint/domain values to make repeated client creation easier. These remain in the browser profile.
Przeglądarka może zapisywać ustawienia interfejsu oraz wcześniej wprowadzone adresy serwera i domeny, aby ułatwić ponowne tworzenie konfiguracji klientów. Dane te pozostają w profilu przeglądarki.
## Local server data
## Dane na serwerze
Persistent application state is stored under `/var/lib/wgtools` and `/etc/wgtools`. This includes WGTools-managed client metadata, client-group policy/default definitions, a rolling 24-hour CPU, memory and network-rate history used only for the local Dashboard graphs, durable per-peer/interface WireGuard traffic counters, and the local Audit journal. Audit records can contain the WGTools username, Telegram `@username` and numeric Telegram user ID for state-changing bot actions, and WireGuard client endpoint IP addresses for connection-history events. Audit events are retained for 30 days with a 10,000-row safety cap. Secret-bearing fields and key/token-like values are redacted or intentionally excluded. Login failures and password-recovery actions may record the connecting IP address for local security auditing. WireGuard configuration remains under `/etc/wireguard`.
Trwałe dane aplikacji są przechowywane w `/var/lib/wgtools` i `/etc/wgtools`. Obejmują one metadane zarządzanych klientów, ustawienia i zasady grup klientów, bieżącą historię użycia procesora i pamięci oraz prędkości sieci z ostatnich 24 godzin, wykorzystywaną wyłącznie do wykresów panelu, trwałe liczniki ruchu poszczególnych połączeń i interfejsów WireGuard oraz lokalny dziennik zdarzeń.
See [README.md](README.md) for the file layout.
Dziennik może zawierać nazwę użytkownika aplikacji, nazwę `@użytkownika` i numeryczny identyfikator Telegrama przy działaniach zmieniających stan oraz adresy IP punktów końcowych klientów WireGuard w historii połączeń. Zdarzenia są przechowywane przez 30 dni, maksymalnie 10 000 wpisów. Dane zawierające sekrety oraz wartości przypominające klucze i tokeny są ukrywane lub pomijane. Dla potrzeb lokalnego audytu bezpieczeństwa błędy logowania i odzyskiwanie haseł mogą powodować zapis adresu IP osoby łączącej się. Konfiguracja WireGuard pozostaje w `/etc/wireguard`.
Układ plików opisano w [README.md](README.md).
+19 -293
View File
@@ -1,311 +1,37 @@
# WGTools-Extended
Projekt jest w trakcie rozbudowy na podstawie WGTools. Aktualizator oryginalnego projektu jest odłączony.
WGTools-Extended to panel WWW do zarządzania serwerem WireGuard na Debianie i Ubuntu. Ułatwia obsługę sieci, klientów i reguł dostępu z poziomu przeglądarki.
Konta istniejące przed rozbudową zachowują rolę administratora. Pierwsze konto jest administratorem, a kolejne są tworzone bez dostępu do sieci. Administrator przypisuje dostęp do sieci oraz osobno zezwala na dodawanie klientów, edycję klientów i zarządzanie przekierowaniami. Mechanizm uprawnień jest w trakcie weryfikacji i nie powinien jeszcze być używany jako zabezpieczenie produkcyjne.
## Możliwości
Na stronie serwera można ustawić podstawowy adres IPv4 SNAT dla wybranej sieci. Adres musi być przypisany do wskazanego interfejsu. Zapis restartuje działający interfejs WireGuard i może na chwilę rozłączyć klientów.
- Zarządzanie sieciami WireGuard i konfiguracjami klientów.
- Przydzielanie użytkownikom dostępu do wybranych sieci i operacji.
- Konfiguracja adresu IPv4 dla ruchu wychodzącego oraz ograniczeń nasłuchiwania.
- Grupowanie publicznych adresów IPv4 i przekierowywanie portów TCP oraz UDP do klientów.
- Podgląd zarządzanych przekierowań, dziennik zdarzeń i kopie zapasowe.
- Własna nazwa, logo i kolor panelu.
- Aktualizacja z pliku wydania w ustawieniach.
Można też ograniczyć przychodzący ruch UDP WireGuard do adresu IPv4, interfejsu wejściowego albo obu jednocześnie. Przy aktywnym ograniczeniu ruch IPv6 na ten port jest blokowany. Zmiana restartuje działający interfejs.
## Instalacja
Workflow Gitea tworzy wydanie dla tagu `vX.Y.Z`, zgodnego z plikiem `VERSION`. Korzysta z runnera `docker-builder` oraz wymaga sekretu repozytorium `GITEA_RELEASE_TOKEN` z prawem tworzenia wydań. Plik `.bin` jest archiwum źródłowym gzip i można go wgrać w ustawieniach. Pakiety nie są podpisywane; administrator musi sam sprawdzić ich pochodzenie. Aktualizacja tworzy kopię zapasową i w razie błędu próbuje przywrócić poprzednią wersję.
Administrator przypisuje publiczne IPv4 do grup i sieci. Użytkownicy danej sieci mogą przekierować TCP, UDP lub oba protokoły z przypisanego adresu na adres klienta tej sieci. Program odrzuca konflikty między swoimi przekierowaniami i sprawdza lokalne nasłuchujące usługi; ręczne reguły zapory trzeba sprawdzić osobno. Zmiana przekierowania restartuje działający interfejs.
# WGTools — WireGuard Web UI & Server Management Panel
**WGTools** is an open-source, self-hosted **WireGuard web UI and server management panel** for **Debian and Ubuntu**. It provides a browser-based WireGuard GUI for day-to-day administration without manually editing `wg-quick` configuration files for routine tasks.
WGTools combines WireGuard installation and multi-interface management, clients and Site-to-Site peers, routing/NAT/firewall policy, VPS Relay, multi-server Nodes, monitoring, TOTP MFA, traceroute/ping route diagnostics, backups, scheduled access, HTTPS, Telegram administration and safe application updates in one UI.
> **Security note:** WGTools performs privileged network administration and its services run as `root`. The bundled web service starts on HTTP port `8341` by default. For Internet-facing installations, enable **Settings → HTTPS** to obtain a Let’s Encrypt certificate and move WGTools directly to a selected HTTPS port and a private access path, or place `8341` behind your own reverse proxy. Do not expose plain HTTP `8341` directly to the public Internet.
[Русская версия README](README.ru.md)
## Supported systems
WGTools supports **Debian and Ubuntu** hosts using `apt` and `systemd`.
The installer and VPS Relay preflight expect the normal Debian/Ubuntu networking toolchain (`iproute2`, `iptables`, `wg`/`wg-quick`, Python 3 and systemd). WireGuard itself can be installed from the WGTools Server page on a clean host.
## Screenshots
<details>
<summary><strong>Show WGTools screenshots</strong></summary>
<br>
### Getting started
#### First-user setup
![WGTools WireGuard web UI first-user setup](docs/screenshots/first-user-setup.png)
### Dashboard and monitoring
#### Dashboard with multiple WireGuard interfaces
![WGTools WireGuard dashboard and interface selector](docs/screenshots/dashboard-interface-selector.png)
### Server management
#### Multiple WireGuard interfaces
![WGTools server manager with multiple WireGuard interfaces](docs/screenshots/server-multi-interface.png)
### Clients and Site-to-Site
#### Client list
![WGTools WireGuard clients and peer status](docs/screenshots/clients-list.png)
#### Create a WireGuard client
![WGTools create WireGuard client dialog](docs/screenshots/create-client.png)
#### Create a Site-to-Site peer
![WGTools create WireGuard Site-to-Site peer dialog](docs/screenshots/create-site-to-site.png)
### Settings and CLI
#### General settings
![WGTools settings for theme language and status refresh](docs/screenshots/settings-general.png)
#### Root management console
![WGTools root CLI management console](docs/screenshots/wgtools-cli.png)
</details>
> Screenshots contain lab/example values. Never publish private keys, real client configuration QR codes, passwords, tokens or `.wgtbackup` contents.
## Highlights
### WireGuard server and interfaces
- Install WireGuard from the UI on a clean Debian/Ubuntu host.
- Create the first server (`wg0`) with an optional friendly **Display name**.
- Default first VPN pool: `10.0.0.0/24`, server address `10.0.0.1/24`.
- Add independent `wg1`, `wg2`, … interfaces with automatic suggestions for a non-overlapping pool, free UDP port and policy table. With the default layout, `wg1` is suggested as `10.0.1.0/24`.
- Global top-bar interface selector; Dashboard, Server, Clients and raw config follow the selected interface.
- Start, restart and stop the selected WireGuard interface.
- Internal Relay transport interfaces (`wgrly*`) are intentionally hidden from normal interface management.
### Routing, NAT and firewall
- IPv4 forwarding and NAT/MASQUERADE management.
- Uplink interface, gateway and local-network settings.
- Optional source policy-routing table per WireGuard interface.
- Managed static/site-to-site routes.
- Server access policy with tagged WGTools firewall rules and live reconciliation.
- Raw `/etc/wireguard/<interface>.conf` editor with validation, backup and rollback protection.
### Clients and site-to-site peers
- Normal WireGuard clients and site-to-site peers.
- Per-client VPN isolation from other WireGuard pool addresses without blocking access to the server itself, LAN, Site-to-site destinations or Internet allowed by the other policies.
- Automatic free VPN-address suggestion.
- Generated `.conf` files and QR codes for WGTools-managed clients.
- Optional PresharedKey (PSK).
- One safe **Rotate keys** action regenerates PrivateKey/PublicKey and also regenerates PSK when PSK is enabled; address, routes, group/policies, expiration/schedule, isolation, last seen and accumulated traffic are preserved, and a new config/QR must be issued afterward.
- PersistentKeepalive and DNS settings.
- Route presets: full tunnel, full tunnel except protected local networks, VPN + local networks, VPN only and custom routes.
- Per-client local-network exceptions and server-side access policy.
- Client groups with reusable policies/defaults and per-client overrides.
- Temporary clients with 1/3/6 hour, 1 day or custom expiration.
- Recurring access schedules by weekday and time, including overnight windows such as `22:00–06:00`.
- Live peer create/edit/delete via `wg syncconf` without restarting the whole interface during normal peer operations.
### VPS Relay
WGTools can use a public Debian/Ubuntu VPS as a WireGuard UDP Relay when the real WGTools server is behind NAT or otherwise hard to reach directly.
```text
WireGuard client
│ encrypted client WireGuard packets
▼
Public VPS Relay Agent
│ protected Home ↔ VPS transport
▼
WGTools / real WireGuard server
├── local networks
└── Internet (when the client policy allows it)
```
The Relay is a transport layer: it does **not** terminate the client's WireGuard session and does not become a separate Internet-exit VPN server. The real WireGuard server remains the WGTools host.
Relay features:
- SSH preflight before installation: OS, privileges, tools and UDP-port checks.
- Password and pasted SSH private key are used only for the current operation and are not stored by WGTools.
- One Relay Agent can keep multiple isolated tenants for different WGTools controllers.
- One WGTools installation can register multiple VPS Relay endpoints and assign clients to a selected Relay.
- Existing Relay Agent installations are reused instead of overwritten; free tenant UDP ports are selected automatically.
- Protected management/transport tunnel with health information.
- **Remove VPS** detaches the Relay from the local WGTools installation but intentionally leaves the remote tenant intact for disaster recovery.
- Adding the same VPS again can reconnect the existing tenant instead of creating another one.
- Migration restore can rebuild the home side of a preserved Relay from the restored WGTools state.
### WGTools Nodes
WGTools installations can be linked through a hidden `wgnode0` Hub-and-Spoke WireGuard network. The HUB uses one Nodes port number for **UDP WireGuard** and **protected TCP pairing**; when the HUB is behind NAT, forward that port for both protocols.
- Spoke setup needs only a node name, HUB `host:port`, one-time code and optional additional routed networks.
- The one-time code pins the HUB Node-control certificate fingerprint before its secret is sent.
- After pairing, topology, status, version and read-only remote-client data synchronize only through `wgnode0`, not through the WGTools web URL.
- Local interface VPN pools and configured Site-to-Site peer remote networks are published automatically; Site-to-Site publication is based on configuration and does not disappear when that peer is offline.
- Ordinary WireGuard clients of a remote Node can access locally published networks without return routes on each LAN router; WGTools applies narrow return-path NAT only to remote VPN client pools.
- The optional panel URL is informational metadata for **Open panel** and may change independently without breaking Nodes.
- Full `.wgtbackup` migration/restore preserves the HUB Node-control identity used by already-paired Spokes.
### Dashboard and monitoring
- WireGuard state, selected-interface address/port, peer counts and durable lifetime handshake/RX/TX statistics. Traffic counters survive WireGuard/host restarts and can be reset manually from the Dashboard.
- CPU, memory and network-rate metrics.
- Rolling 24-hour graphs with minimum/average/maximum summaries.
- Search/filtering for peer lists.
- Dedicated **Server → Trace** diagnostics with ping + traceroute, per-hop RTT/loss, latency-jump highlighting and an interactive OpenStreetMap route view with pan/zoom and clickable hops.
### Terminal console
Run `wgtools` as root to open the local boxed management menu. It shows the current panel URL/private HTTPS path plus WGTools, WireGuard, Nodes, Telegram, timers and local Relay Agent status, and provides panel controls, WireGuard status/start/stop/restart actions, logs, HTTP rescue, emergency MFA disable for a selected user, and two clearly separated removal paths: a soft uninstall that preserves WireGuard/reusable data and a destructive FULL CLEANUP.
### HTTPS
- Optional built-in HTTPS without Nginx/Caddy/Traefik: WGTools can serve TLS directly with Uvicorn on a user-selected TCP port (`443` by default).
- Let’s Encrypt certificates can be requested for a domain or a public IP address. IP certificates use Let’s Encrypt’s short-lived profile and therefore depend on automatic renewal.
- Certificate issuance/renewal uses Certbot standalone validation, so TCP `80` must be reachable from the Internet while ACME validation runs.
- WGTools checks local TCP `80` plus the selected HTTPS port before issuance/enabling and never stops or replaces an unrelated web server.
- Automatic renewal is enabled with a dedicated systemd timer while built-in HTTPS is active; successful renewal reloads WGTools.
- Built-in HTTPS requires an administrator-defined panel path such as `/MyPrivateWGToolsPath/`. Requests outside that prefix receive `404`; authentication is still required normally inside the path.
- Settings shows the `fullchain.pem` and `privkey.pem` paths with copy buttons so the same certificate files can be referenced by other software on the host.
- Built-in HTTPS can be disabled to return WGTools to its normal HTTP port when a user prefers NPM, Caddy, Traefik or another reverse proxy.
### Authentication, mail and Telegram
- First-run admin creation and local WGTools user management with optional per-user e-mail addresses.
- Optional per-user TOTP MFA compatible with **Google Authenticator**, 2FAS, Aegis and other standard authenticator apps. Enrollment uses a QR code (with a manual setup key fallback), and WGTools generates one-time recovery codes. Root can emergency-disable MFA from the local `wgtools` CLI if the authenticator device and recovery codes are lost.
- Optional SMTP password recovery with STARTTLS/TLS/plain SMTP support, a one-time 6-digit code valid for 15 minutes, request/attempt limits, and identical public responses that do not reveal whether an account exists. Password changes invalidate older sessions for that user.
- Administrators can send a reset code directly from Settings → Users; SMTP configuration and test delivery live under Settings → Mail.
- Passwords stored as salted PBKDF2-HMAC-SHA256 hashes.
- Optional Telegram Bot with an allow-list of numeric Telegram user IDs.
- Telegram status, interface selection, client creation/removal and config/QR re-issue. WireGuard Start/Restart/Stop controls are grouped under a dedicated **Server** item beside **Interface**. Navigation appends new bot messages without overwriting earlier screens, keeping the recent history available for reuse. After sending a config/QR, the refreshed client picker appears below the files; destructive confirmations are bound to the current prompt. Cyrillic client names receive readable transliterated `.conf` filenames instead of the generic fallback.
### Audit
- **Settings → Audit** opens a searchable audit journal with timestamp, actor, action, object and result.
- Web changes record the local WGTools username. Telegram state-changing actions record `@username` when available and always include the numeric Telegram user ID.
- The Telegram menu has a read-only **Audit** shortcut and `/audit` command; browse the latest 20 events and older/newer pages (including changes made by other WGTools administrators).
- Telegram client create/delete, explicit config/QR re-issue and WireGuard Start/Stop/Restart actions are audited; meaningful failures and denied mutating attempts are recorded without logging ordinary menu navigation or read-only status views.
- WireGuard client connection history records client name, time and endpoint IP when a client connects after a meaningful offline gap or its endpoint IP changes.
- The last successful client handshake is kept as durable last-seen state, so restarting the host or WireGuard interface does not turn a previously connected client into `Never`.
- Application updates audit the safety `.wgtbackup`, successful completion, useful failures and automatic rollback results.
- Audit retention is 30 days with a 10,000-row safety cap.
- Passwords, reset codes, WireGuard private keys, PSKs, Telegram Bot tokens, SMTP passwords, Relay `control_token`, SSH credentials, full client configs and QR contents are redacted or never written.
### Backups and disaster recovery
WGTools has two backup layers:
1. **Automatic configuration history** before configuration-changing operations.
2. **Portable `.wgtbackup` migration/disaster-recovery archive**.
A full `.wgtbackup` can include:
- all detected WireGuard interface configs and their running/stopped state;
- WGTools SQLite database with users/e-mail addresses, preferences, SMTP settings and VPS Relay records;
- managed client metadata, client private keys and PSKs;
- client groups, schedules/expiration state and interface display-name metadata;
- Telegram configuration/token and SMTP credentials when configured;
- forwarding sysctl state;
- Relay controller/tenant identity, management token and home transport key needed to reconnect a preserved remote Relay tenant.
The remote VPS filesystem itself is not copied into `.wgtbackup`; for transparent Relay disaster recovery, the Relay Agent/tenant must still exist on that VPS.
> Let’s Encrypt certificate lineages under `/etc/letsencrypt` are host-level files and are not copied into `.wgtbackup`. After migrating WGTools to another host, request the built-in HTTPS certificate again. A normal WGTools uninstall intentionally leaves `/etc/letsencrypt` untouched so an existing certificate can still be used by other software.
> `.wgtbackup` files contain secrets, including saved SMTP credentials when configured. Protect them like passwords or private SSH keys and never attach one to a public issue.
### Aktualizacje
Administrator wgrywa zaufany pakiet `.bin` w ustawieniach. Przed instalacją powstają kopia danych i archiwum aplikacji. W razie błędu program próbuje przywrócić poprzednią wersję. Aktualizacje online oryginalnego projektu są odłączone.
## Quick install
Pobierz kod repozytorium na serwer Debian lub Ubuntu, a następnie uruchom w katalogu projektu:
```bash
sudo bash install.sh
```
The local installer runs [`scripts/install.sh`](scripts/install.sh) from the checked-out source tree.
Po instalacji otwórz adres podany przez instalator i utwórz pierwsze konto administratora. WireGuard można zainstalować z panelu.
Open the printed URL (normally `http://SERVER-IP:8341`) and create the first WGTools account.
Podczas tworzenia lub edycji sieci wybierz sposób nasłuchiwania i interfejs albo adres dla ruchu wychodzącego. Osobne pole pozwala wskazać adresy IPv4 lub interfejsy dostępne do przekierowań portów; kolejne wartości oddziel przecinkami.
WireGuard is intentionally not installed silently by the bootstrap installer. On a clean server, use **Server → Install WireGuard**.
W **Ustawienia → Użytkownicy → Uprawnienia** administrator wybiera sieci dostępne dla użytkownika i dozwolone w nich działania. W **Serwer → Grupy publicznych adresów IPv4** można dodatkowo współdzielić adresy między sieciami.
### Inspect before installing
## Aktualizacja
```bash
# Pobierz kod WGTools-Extended z własnego repozytorium.
cd WGTools
less install.sh
less scripts/install.sh
less scripts/wgtools-helper
sudo ./scripts/install.sh
```
Pobierz pakiet `.bin` z wydania WGTools-Extended i wgraj go w ustawieniach panelu. Przed aktualizacją program tworzy kopię zapasową i kopię umożliwiającą przywrócenie poprzedniej wersji.
To install a specific public release:
## Bezpieczeństwo
```bash
git checkout v0.40.4
sudo ./scripts/install.sh
```
Panel zarządza ustawieniami sieci i działa z uprawnieniami administratora systemu. Ogranicz dostęp do niego do zaufanej sieci lub zabezpiecz go przez HTTPS. Przechowuj kopie zapasowe i pliki konfiguracji klientów w bezpiecznym miejscu.
## Installed paths
| Path | Purpose |
|---|---|
| `/opt/wgtools` | Application source and Python virtual environment |
| `/var/lib/wgtools` | SQLite database, session secret, managed client state, backups and Relay home-side metadata |
| `/etc/wgtools/wgtools.env` | Runtime environment settings |
| `/usr/local/libexec/wgtools-helper` | Privileged helper used by the web application |
| `/etc/systemd/system/wgtools*.service` | WGTools web/Telegram/expiry services |
| `/etc/wireguard/*.conf` | User-managed WireGuard interface configurations |
| `/var/lib/wgtools-relay` | VPS Relay Agent state when this host is used as a Relay VPS |
| `/opt/wgtools-relay` | VPS Relay Agent code when this host is used as a Relay VPS |
WGTools does not create an additional Linux user. The services run as root because they manage WireGuard, routes, firewall state and protected configuration files.
## Network and privacy
WGTools has no analytics, advertising or application telemetry to the project maintainer. It does not upload your WireGuard keys, peer list, local topology, users or traffic counters.
Expected outbound connections are limited to enabled features:
- **Gitea:** releases are published by the project workflow; updates are uploaded manually by the administrator.
- **Telegram:** only when Telegram Bot integration is enabled.
- **APT repositories:** package installation on Debian/Ubuntu.
See [PRIVACY.md](PRIVACY.md) and [SECURITY.md](SECURITY.md).
## Uninstall and complete cleanup
Removal is built into the root `wgtools` console, so routine uninstall/cleanup does not require copying shell commands from the documentation.
The CLI provides two deliberately separate actions:
- **Uninstall WGTools** — removes the panel, services, CLI and internal Nodes/local Relay-home transports while preserving normal WireGuard and reusable WGTools state for reinstall/recovery.
- **FULL CLEANUP** — destructive cleanup for a dedicated host. It removes WGTools state/backups, Nodes, local Relay state, WireGuard interfaces/configuration and WireGuard packages. It requires typing `DELETE ALL` before execution. Remote Relay VPS hosts are never contacted automatically.
Run the local management console as `root` with `wgtools` and choose the required removal action from the **Removal** section.
## Security
WGTools is a privileged administration application. Before exposing it outside a trusted network, read [SECURITY.md](SECURITY.md).
For security reports, do not publish private keys, `.wgtbackup` archives, passwords, bot tokens or production configuration in a public issue.
## License
See [LICENSE](LICENSE).
Więcej informacji znajdziesz w [zasadach bezpieczeństwa](SECURITY.md). Projekt bazuje na WGTools; informacje o autorstwie znajdują się w [licencji](LICENSE).
-296
View File
@@ -1,296 +0,0 @@
# WGTools — веб-панель управления WireGuard
**WGTools** — open-source self-hosted **WireGuard Web UI / GUI и панель управления WireGuard-сервером** для **Debian и Ubuntu**. Она позволяет выполнять повседневное администрирование через браузер и не редактировать `wg-quick` конфиги вручную для обычных операций.
В одном интерфейсе собраны установка и несколько WireGuard-интерфейсов, клиенты и Site-to-Site, маршрутизация/NAT/firewall, VPS Relay, связь нескольких серверов через Nodes, мониторинг, TOTP MFA, traceroute/ping с интерактивной картой маршрута, резервные копии, расписания доступа, HTTPS, Telegram и безопасные обновления.
> **Важно по безопасности:** WGTools выполняет привилегированные сетевые операции, поэтому его службы работают от `root`. Встроенный web-сервис стартует на HTTP-порту `8341`. Для установки, доступной из Интернета, включите **Настройки → HTTPS**: WGTools получит сертификат Let’s Encrypt и перейдёт на выбранный HTTPS-порт с отдельным приватным путём доступа, либо оставьте `8341` за своим reverse proxy. Не публикуйте обычный HTTP `8341` напрямую в Интернет.
[English README](README.md)
## Поддерживаемые системы
WGTools поддерживает **Debian и Ubuntu** с `apt` и `systemd`.
Установщик и проверка VPS Relay рассчитывают на стандартный стек Debian/Ubuntu: `iproute2`, `iptables`, `wg`/`wg-quick`, Python 3 и systemd. На чистой машине WireGuard можно установить прямо со страницы **Сервер**.
## Скриншоты
<details>
<summary><strong>Показать скриншоты WGTools</strong></summary>
<br>
### Первый запуск
#### Создание первого пользователя
![Первичная настройка пользователя в веб-панели WireGuard WGTools](docs/screenshots/first-user-setup.png)
### Главная и мониторинг
#### Главная с несколькими WireGuard-интерфейсами
![Главная WGTools и переключатель WireGuard-интерфейсов](docs/screenshots/dashboard-interface-selector.png)
### Управление сервером
#### Несколько WireGuard-интерфейсов
![Управление несколькими WireGuard-интерфейсами в WGTools](docs/screenshots/server-multi-interface.png)
### Клиенты и Site-to-Site
#### Список клиентов
![Клиенты WireGuard и состояние peer в WGTools](docs/screenshots/clients-list.png)
#### Создание WireGuard-клиента
![Создание WireGuard-клиента в WGTools](docs/screenshots/create-client.png)
#### Создание Site-to-Site peer
![Создание WireGuard Site-to-Site подключения в WGTools](docs/screenshots/create-site-to-site.png)
### Настройки и CLI
#### Основные настройки
![Настройки темы языка и обновления статуса WGTools](docs/screenshots/settings-general.png)
#### Консоль управления root
![Консоль управления WGTools для WireGuard](docs/screenshots/wgtools-cli.png)
</details>
> На скриншотах используются лабораторные/примерные значения. Никогда не публикуйте приватные ключи, реальные QR-коды клиентских конфигураций, пароли, токены или содержимое `.wgtbackup`.
## Основные возможности
### WireGuard-сервер и интерфейсы
- Установка WireGuard из UI на чистой Debian/Ubuntu машине.
- Создание первого сервера (`wg0`) с необязательным понятным **Display name**.
- Пул по умолчанию для первого интерфейса: `10.0.0.0/24`, адрес сервера `10.0.0.1/24`.
- Добавление независимых `wg1`, `wg2`, … с автоматическим предложением непересекающегося пула, свободного UDP-порта и policy table. При стандартной схеме для `wg1` предлагается `10.0.1.0/24`.
- Глобальный переключатель интерфейсов в верхней панели; Dashboard, Server, Clients и raw config работают с выбранным интерфейсом.
- Start / Restart / Stop выбранного WireGuard-интерфейса.
- Внутренние Relay-интерфейсы `wgrly*` скрыты из обычного пользовательского управления.
### Маршрутизация, NAT и firewall
- IPv4 forwarding и NAT/MASQUERADE.
- Uplink-интерфейс, gateway и локальная сеть.
- Необязательная отдельная таблица source policy routing для каждого WireGuard-интерфейса.
- Управляемые маршруты и Site-to-site сети.
- Серверные правила доступа с собственными тегами WGTools и синхронизацией live `iptables`.
- Raw-редактор `/etc/wireguard/<interface>.conf` с проверкой, backup и rollback.
### Клиенты и Site-to-site
- Обычные WireGuard-клиенты и Site-to-site peer'ы.
- Персональная изоляция VPN-клиента от других адресов WireGuard-пула без блокировки доступа к самому серверу, LAN, Site-to-site сетям или Интернету, разрешённым остальными политиками.
- Автоматическое предложение первого свободного VPN-адреса.
- Генерация `.conf` и QR-кода для WGTools-managed клиентов.
- Необязательный PresharedKey (PSK).
- Единая безопасная кнопка **«Сменить ключи»** создаёт новые PrivateKey/PublicKey и, если PSK включён, новый PSK; адрес, маршруты, группа/политики, срок/расписание, изоляция, last seen и накопленный трафик сохраняются, после чего требуется новый конфиг/QR.
- DNS и PersistentKeepalive.
- Пресеты маршрутов: весь трафик, весь трафик кроме защищённых локальных сетей, VPN + локальные сети, только VPN и Custom.
- Исключения доступа к отдельным локальным IP/CIDR и серверная политика доступа.
- Группы клиентов с общими политиками/defaults и индивидуальными override'ами.
- Временные клиенты: 1/3/6 часов, 1 день или произвольная дата/время.
- Повторяющиеся расписания доступа по дням недели и времени, включая окна через полночь, например `22:00–06:00`.
- Обычные операции с peer'ами применяются через `wg syncconf` без перезапуска всего интерфейса.
### VPS Relay
WGTools может использовать публичный Debian/Ubuntu VPS как UDP Relay, если реальный WGTools/WireGuard-сервер находится за NAT или напрямую недоступен извне.
```text
WireGuard-клиент
│ зашифрованные WireGuard-пакеты клиента
▼
Публичный VPS Relay Agent
│ защищённый транспорт Home ↔ VPS
▼
WGTools / реальный WireGuard-сервер
├── локальные сети
└── Интернет, если это разрешено политикой клиента
```
Relay является транспортом: он **не завершает клиентский WireGuard-туннель** и не превращается в отдельный VPN-шлюз для выхода в Интернет. Реальным WireGuard-сервером остаётся машина WGTools.
Возможности Relay:
- SSH preflight перед установкой: ОС, права, инструменты и свободные UDP-порты.
- Пароль и вставленный приватный SSH-ключ используются только для текущей операции и не сохраняются WGTools.
- Один Relay Agent хранит несколько изолированных tenant'ов для разных экземпляров WGTools.
- Один WGTools может иметь несколько VPS Relay и назначать клиенту конкретный Relay.
- Существующий Relay Agent не перезаписывается; для нового tenant автоматически выбираются свободные UDP-порты.
- Защищённый management/transport туннель и health-проверка.
- **Удалить VPS** отсоединяет Relay от текущего WGTools, но специально оставляет remote tenant на VPS для аварийного восстановления.
- Повторное добавление того же VPS умеет подключиться к существующему tenant, не создавая новый.
- Restore полной резервной копии может восстановить домашнюю сторону transport к сохранившемуся tenant на VPS.
### Узлы WGTools
Несколько установок WGTools можно связать через скрытую Hub-and-Spoke сеть `wgnode0`. HUB использует один номер порта одновременно для **UDP WireGuard** и **защищённого TCP pairing**; если HUB находится за NAT, этот порт нужно пробросить по обоим протоколам.
- На Spoke нужны только имя узла, HUB `host:port`, одноразовый код и при необходимости дополнительные маршрутизируемые сети.
- Одноразовый код закрепляет fingerprint служебного сертификата HUB до отправки секрета подключения.
- После pairing топология, статусы, версии и read-only данные удалённых клиентов синхронизируются только внутри `wgnode0`, а не через адрес веб-панели WGTools.
- VPN-пулы локальных интерфейсов и настроенные удалённые сети Site-to-Site клиентов публикуются автоматически; Site-to-Site сеть остаётся в топологии даже когда соответствующий peer офлайн.
- Обычные WireGuard-клиенты удалённого узла могут ходить в локально опубликованные сети без ручных обратных маршрутов на LAN-роутерах; WGTools применяет узкий return-path NAT только к удалённым VPN-пулам клиентов.
- Необязательный адрес панели остаётся информационным полем для кнопки **«Открыть панель»** и может меняться независимо от Nodes.
- Полный `.wgtbackup` сохраняет служебную identity HUB, которой уже доверяют подключённые Spoke.
### Dashboard и мониторинг
- Состояние WireGuard, адрес/порт выбранного интерфейса, peer'ы и долговременная статистика handshake/RX/TX. Счётчики трафика переживают перезапуски WireGuard/сервера и вручную сбрасываются с Главной.
- CPU, RAM и скорость сети.
- 24-часовые графики с min/avg/max.
- Поиск по спискам peer'ов.
- Отдельная вкладка **Сервер → Маршрут**: ping + traceroute, RTT и потери по каждому узлу, подсветка скачков задержки и интерактивная карта OpenStreetMap с масштабированием, перемещением и деталями по узлам.
### Консоль управления
Команда `wgtools` от root открывает локальное меню управления со сводной таблицей состояний. В нём видны текущий URL/приватный HTTPS-путь, WGTools, WireGuard, Nodes, Telegram, таймеры и локальный Relay Agent; доступны управление панелью, статус/запуск/остановка/перезапуск WireGuard, логи, аварийный возврат на HTTP, аварийное отключение MFA для выбранного пользователя и два явно разделённых сценария удаления: мягкий uninstall с сохранением WireGuard/данных и разрушительный FULL CLEANUP.
### HTTPS
- Необязательный встроенный HTTPS без Nginx/Caddy/Traefik: WGTools может сам обслуживать TLS через Uvicorn на выбранном пользователем TCP-порту (`443` по умолчанию).
- Сертификат Let’s Encrypt можно получить для домена или публичного IP. Для IP используются короткоживущие сертификаты Let’s Encrypt, поэтому автопродление обязательно.
- Выпуск и продление идут через Certbot standalone, поэтому TCP-порт `80` должен быть доступен из Интернета во время ACME-проверки.
- Перед выпуском/включением WGTools проверяет локальный TCP `80` и выбранный HTTPS-порт и не останавливает/не перенастраивает чужой web-сервис.
- Пока встроенный HTTPS включён, отдельный systemd timer автоматически проверяет продление сертификата; после успешного renewal WGTools перечитывает сертификат.
- Для встроенного HTTPS администратор сам задаёт путь панели, например `/MyPrivateWGToolsPath/`. Запросы вне этого пути получают `404`; внутри пути обычная авторизация WGTools остаётся обязательной.
- Во вкладке HTTPS ненавязчиво показываются пути к `fullchain.pem` и `privkey.pem` с кнопками копирования — их можно использовать в других сервисах на этом же сервере.
- Встроенный HTTPS можно отключить и вернуть WGTools на обычный HTTP-порт, если пользователь предпочитает NPM, Caddy, Traefik или другой reverse proxy.
### Пользователи, почта и Telegram
- Создание первого администратора и локальное управление пользователями WGTools; для каждой учётной записи можно указать необязательный E-mail.
- Необязательная MFA для каждого пользователя по стандарту TOTP, совместимая с **Google Authenticator**, 2FAS, Aegis и другими приложениями. Подключение через QR-код (есть ключ для ручного ввода), при включении выдаются одноразовые резервные коды. Если устройство и резервные коды потеряны, root может аварийно отключить MFA через локальную команду `wgtools`.
- Необязательное восстановление пароля через SMTP: STARTTLS/TLS/обычный SMTP, одноразовый 6-значный код на 15 минут, лимиты запросов/попыток и одинаковый публичный ответ без раскрытия существования учётной записи. После смены или восстановления пароля старые web-сессии пользователя инвалидируются.
- Администратор может отправить код сброса прямо из **Настройки → Пользователи**; SMTP и тестовая отправка настраиваются во вкладке **Настройки → Почта**.
- Пароли хранятся как salted PBKDF2-HMAC-SHA256 hashes.
- Необязательный Telegram Bot с allow-list числовых Telegram user ID.
- Через Telegram доступны статус, выбор интерфейса, создание/удаление клиента и повторная выдача config/QR. Пуск/Перезапуск/Стоп WireGuard собраны в отдельном пункте «Сервер» рядом с выбором интерфейса. Навигация идёт по шагам: после отправки config/QR обновлённый список клиентов появляется ниже файлов, а вложенные подтверждения возвращают на родительский список. Кириллические имена клиентов получают читаемые транслитерированные имена `.conf`-файлов вместо общего имени по умолчанию.
### Аудит
- **Настройки → Аудит** открывает журнал с поиском: дата/время, источник/пользователь, действие, объект и результат.
- Для действий из web-панели сохраняется локальный пользователь WGTools. Для действий Telegram показывается `@username`, если он есть, и обязательно числовой Telegram user ID.
- В аудит попадают создание/удаление клиентов через Telegram, явная повторная выдача config/QR и Start/Stop/Restart WireGuard; полезные ошибки и запрещённые изменяющие действия тоже фиксируются, а обычная навигация по меню и просмотр статусов журнал не засоряют.
- История подключений WireGuard хранит имя клиента, время и endpoint IP при подключении после заметного перерыва или смене IP.
- Последний успешный handshake клиента хранится отдельно как долговременный `last seen`: после перезапуска сервера или WireGuard-интерфейса ранее подключавшийся клиент больше не превращается в «Никогда».
- Для обновлений в Аудите фиксируются созданная перед update полная `.wgtbackup`, успешное завершение, полезные ошибки и результат автоматического rollback.
- Срок хранения — 30 дней, дополнительный защитный лимит — 10 000 записей.
- Пароли, коды сброса, приватные ключи WireGuard, PSK, Telegram Bot token, SMTP-пароль, Relay `control_token`, SSH credentials, полные client config и QR в аудит не записываются.
### Резервное копирование и восстановление
WGTools использует два уровня backup:
1. **Автоматическая история конфигурации** перед изменяющими конфиг операциями.
2. **Полная переносимая `.wgtbackup`** для миграции/аварийного восстановления.
Полная `.wgtbackup` может содержать:
- конфиги всех обнаруженных WireGuard-интерфейсов и их running/stopped state;
- SQLite WGTools с пользователями/E-mail, настройками, SMTP и записями VPS Relay;
- managed-client metadata, приватные клиентские ключи и PSK;
- группы, расписания/сроки действия и Display name интерфейсов;
- настройки/токен Telegram и SMTP credentials, если они настроены;
- sysctl-состояние forwarding;
- controller/tenant identity Relay, management token и домашний transport private key, необходимые для подключения к сохранившемуся remote tenant.
Файловая система удалённого VPS внутрь `.wgtbackup` не копируется. Для бесшовного аварийного восстановления Relay Agent/tenant должен продолжать существовать на VPS.
> Сертификаты Let’s Encrypt из `/etc/letsencrypt` относятся к самому хосту и не копируются в `.wgtbackup`. После переноса WGTools на другой сервер встроенный HTTPS нужно выпустить заново. Обычное удаление WGTools намеренно не трогает `/etc/letsencrypt`, чтобы существующий сертификат можно было продолжить использовать в других сервисах.
> `.wgtbackup` содержит секреты, включая сохранённые SMTP credentials. Храните такой файл как пароль или приватный SSH-ключ и никогда не прикладывайте его к публичному issue.
### Обновления
Администратор загружает доверенный пакет `.bin` в настройках. Автоматическая проверка релизов исходного проекта отключена.
## Быстрая установка
```bash
sudo bash install.sh
```
Локальный установщик запускает `scripts/install.sh` из текущего каталога исходников.
Откройте показанный установщиком адрес (обычно `http://IP-СЕРВЕРА:8341`) и создайте первого пользователя.
WireGuard специально не ставится молча bootstrap-скриптом. На чистом сервере используйте **Сервер → Установить WireGuard**.
### Проверить код до установки
```bash
# Pobierz kod WGTools-Extended z własnego repozytorium.
cd WGTools
less install.sh
less scripts/install.sh
less scripts/wgtools-helper
sudo ./scripts/install.sh
```
Установка конкретного публичного релиза:
```bash
git checkout v0.40.4
sudo ./scripts/install.sh
```
## Что устанавливается
| Путь | Назначение |
|---|---|
| `/opt/wgtools` | Исходники приложения и Python virtualenv |
| `/var/lib/wgtools` | SQLite, session secret, managed-client state, backup и домашние данные Relay |
| `/etc/wgtools/wgtools.env` | Runtime-настройки |
| `/usr/local/libexec/wgtools-helper` | Привилегированный helper веб-приложения |
| `/etc/systemd/system/wgtools*.service` | Web/Telegram/expiry службы WGTools |
| `/etc/wireguard/*.conf` | Пользовательские WireGuard-конфиги |
| `/var/lib/wgtools-relay` | Состояние VPS Relay Agent, если машина используется как Relay VPS |
| `/opt/wgtools-relay` | Код VPS Relay Agent, если машина используется как Relay VPS |
Отдельный Linux-пользователь не создаётся. Службы работают от root, потому что управляют WireGuard, маршрутизацией, firewall и защищёнными конфигурационными файлами.
## Сеть и приватность
В WGTools нет аналитики, рекламы или телеметрии, отправляемой разработчику проекта. Приложение не выгружает ваши WireGuard-ключи, peer list, локальную топологию, пользователей или traffic counters.
Ожидаемые исходящие соединения ограничены включёнными функциями:
- **Gitea:** публикация релизов проекта; обновления загружаются администратором вручную.
- **Telegram:** только когда Telegram Bot включён.
- **APT repositories:** установка пакетов на Debian/Ubuntu.
Подробнее: [PRIVACY.md](PRIVACY.md) и [SECURITY.md](SECURITY.md).
## Удаление и полная очистка
Удаление встроено в root-консоль `wgtools`, поэтому для обычного uninstall/cleanup не нужно копировать длинные shell-команды из документации.
В CLI специально разделены два сценария:
- **Uninstall WGTools** — удаляет панель, службы, CLI и внутренние Nodes/локальные Relay-home transport, но сохраняет обычный WireGuard и пригодное для повторной установки состояние WGTools.
- **FULL CLEANUP** — разрушительная полная очистка выделенного сервера: удаляются состояние и backup WGTools, Nodes, локальный Relay, WireGuard-интерфейсы/конфиги и пакеты WireGuard. Перед выполнением нужно вручную ввести `DELETE ALL`. Удалённые Relay VPS автоматически не затрагиваются.
Запустите локальную консоль `wgtools` от `root` и выберите нужный вариант в разделе **Removal**.
## Безопасность
WGTools — привилегированное приложение администрирования. Перед публикацией веб-панели за пределами доверенной сети прочитайте [SECURITY.md](SECURITY.md).
При сообщении об уязвимости не публикуйте приватные ключи, `.wgtbackup`, пароли, bot token или production-конфигурацию в открытом issue.
## Лицензия
См. [LICENSE](LICENSE).
+1
View File
@@ -0,0 +1 @@
Improves panel performance and reduces unnecessary background refreshes.
+1 -1
View File
@@ -1 +1 @@
1.0.0
1.0.3
+1
View File
@@ -98,6 +98,7 @@ def init_audit_database() -> None:
details TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_audit_log_created_at ON audit_log(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_connection_lookup ON audit_log(action, object, created_at DESC, id DESC);
CREATE TABLE IF NOT EXISTS audit_wg_connection_state (
interface TEXT NOT NULL,
public_key TEXT NOT NULL,
+2 -1
View File
@@ -76,7 +76,8 @@ def init_database() -> None:
conn.execute("ALTER TABLE user_access ADD COLUMN permissions TEXT NOT NULL DEFAULT '{}'")
def get_user_access(user_id: int) -> dict[str, Any]:
def get_user_access(user_id: int, *, initialize: bool = True) -> dict[str, Any]:
if initialize:
init_database()
with _connect() as conn:
row = conn.execute("SELECT role,interfaces,permissions FROM user_access WHERE user_id=?", (int(user_id),)).fetchone()
+1
View File
@@ -37,6 +37,7 @@ ALLOWED_ACTIONS = {
"raw_config_apply",
"server_settings_apply",
"extended_snat_get",
"extended_host_ips",
"extended_snat_apply",
"extended_listen_get",
"extended_listen_apply",
+14 -6
View File
@@ -13,9 +13,8 @@ DEFAULT_BACKUP_RETENTION = 20
def get_branding() -> dict[str, Any]:
return {"name": _get("brand_name", "WGTools-Extended"),
"color": _get("brand_color", "#8f1f27"),
"logo": _get("brand_logo", "")}
values = _get_many({"brand_name": "WGTools-Extended", "brand_color": "#8f1f27", "brand_logo": ""})
return {"name": values["brand_name"], "color": values["brand_color"], "logo": values["brand_logo"]}
def update_branding(name: str, color: str, logo: str) -> dict[str, Any]:
@@ -68,6 +67,14 @@ def _get(key: str, default: str) -> str:
return str(row["value"]) if row else default
def _get_many(defaults: dict[str, str]) -> dict[str, str]:
init_preferences()
with _connect() as conn:
placeholders = ",".join("?" for _ in defaults)
rows = conn.execute(f"SELECT key,value FROM app_settings WHERE key IN ({placeholders})", tuple(defaults)).fetchall()
return {**defaults, **{str(row["key"]): str(row["value"]) for row in rows}}
def _set(key: str, value: str) -> None:
init_preferences()
with _connect() as conn:
@@ -81,9 +88,10 @@ def _set(key: str, value: str) -> None:
def get_preferences() -> dict[str, Any]:
refresh = int(_get("refresh_seconds", str(REFRESH_SECONDS)))
threshold = int(_get("online_threshold_seconds", str(ONLINE_THRESHOLD_SECONDS)))
retention = int(_get("backup_retention", str(DEFAULT_BACKUP_RETENTION)))
values = _get_many({"refresh_seconds": str(REFRESH_SECONDS), "online_threshold_seconds": str(ONLINE_THRESHOLD_SECONDS), "backup_retention": str(DEFAULT_BACKUP_RETENTION)})
refresh = int(values["refresh_seconds"])
threshold = int(values["online_threshold_seconds"])
retention = int(values["backup_retention"])
return {
"refresh_seconds": max(2, min(refresh, 60)),
"online_threshold_seconds": max(30, min(threshold, 3600)),
+1 -1
View File
@@ -7,7 +7,7 @@ APP_NAME = "WGTools-Extended"
VERSION = Path(__file__).resolve().parents[2].joinpath("VERSION").read_text().strip()
WG_INTERFACE = os.getenv("WGTOOLS_INTERFACE", "wg0")
HELPER_PATH = os.getenv("WGTOOLS_HELPER", "/usr/local/libexec/wgtools-helper")
REFRESH_SECONDS = int(os.getenv("WGTOOLS_REFRESH_SECONDS", "5"))
REFRESH_SECONDS = int(os.getenv("WGTOOLS_REFRESH_SECONDS", "10"))
ONLINE_THRESHOLD_SECONDS = int(os.getenv("WGTOOLS_ONLINE_THRESHOLD_SECONDS", "180"))
DATABASE_PATH = os.getenv("WGTOOLS_DATABASE", "/var/lib/wgtools/wgtools.db")
SESSION_KEY_FILE = os.getenv("WGTOOLS_SESSION_KEY_FILE", "/var/lib/wgtools/session.key")
+27 -11
View File
@@ -192,6 +192,10 @@ class CreateServerRequest(BaseModel):
policy_table: str = Field(default="", max_length=12)
nat_enabled: bool = True
ip_forwarding: bool = True
listen_address: str = Field(default="", max_length=15)
listen_interface: str = Field(default="", max_length=15)
snat_address: str = Field(default="", max_length=15)
forward_sources: str = Field(default="", max_length=4096)
class CreateInterfaceRequest(CreateServerRequest):
@@ -220,6 +224,10 @@ class ServerSettingsRequest(BaseModel):
ip_forwarding: bool = True
forward_from_vpn: bool = True
forward_to_vpn: bool = True
listen_address: str | None = Field(default=None, max_length=15)
listen_interface: str | None = Field(default=None, max_length=15)
snat_address: str | None = Field(default=None, max_length=15)
forward_sources: str | None = Field(default=None, max_length=4096)
class HttpsRequest(BaseModel):
@@ -428,7 +436,7 @@ class NodeSettingsRequest(BaseModel):
class AppSettingsRequest(BaseModel):
refresh_seconds: int = Field(default=5, ge=2, le=60)
refresh_seconds: int = Field(default=10, ge=2, le=60)
online_threshold_seconds: int = Field(default=180, ge=30, le=3600)
backup_retention: int = Field(default=20, ge=1, le=200)
@@ -514,9 +522,11 @@ def is_internal_interface(name: str) -> bool:
def request_interface(request: Request) -> str:
current = getattr(request.state, "current_user", None)
access = get_user_access(int(current["id"])) if current else {"role": "admin", "interfaces": []}
access = getattr(request.state, "access", None) or (get_user_access(int(current["id"])) if current else {"role": "admin", "interfaces": []})
default_iface = (access["interfaces"][0] if access["role"] == "user" and access["interfaces"] else WG_INTERFACE)
value = (request.cookies.get("wgtools_interface") or default_iface).strip()
if access["role"] == "user" and access["interfaces"] and value not in access["interfaces"]:
value = default_iface
if not IFACE_RE.fullmatch(value) or is_internal_interface(value):
fallback = str(WG_INTERFACE or "wg0").strip()
return fallback if IFACE_RE.fullmatch(fallback) and not is_internal_interface(fallback) else "wg0"
@@ -570,7 +580,7 @@ def render(request: Request, template: str, page: str, title_key: str) -> HTMLRe
"language": language,
"messages_json": messages_json,
"tr": tr,
"current_user": get_user(int(request.session.get("user_id", 0))) if request.session.get("user_id") else None,
"current_user": getattr(request.state, "current_user", None),
"help_sections": get_help_sections(language) if request.state.access['role'] == 'admin' else [],
},
headers={"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet"},
@@ -639,9 +649,9 @@ async def require_authentication(request: Request, call_next):
if path in PUBLIC_PATHS or path.startswith(PUBLIC_PREFIXES):
return await call_next(request)
users_exist = user_count() > 0
user_id = request.session.get("user_id")
current = get_user(int(user_id)) if user_id else None
users_exist = bool(current) or user_count() > 0
if user_id and not current:
request.session.clear()
if current:
@@ -672,18 +682,16 @@ async def require_authentication(request: Request, call_next):
return RedirectResponse(url=f"{app_url(request, '/login')}?next={next_path}", status_code=303)
request.state.current_user = current
access = get_user_access(int(current["id"]))
access = get_user_access(int(current["id"]), initialize=False)
request.state.access = access
if access["role"] != "admin":
allowed = {"/clients", "/api/interfaces", "/api/snapshot", "/api/app-settings", "/api/auth/logout", "/api/clients/create", "/api/clients/update", "/api/clients/credentials/rotate", "/api/clients/config", "/api/clients/config/download", "/api/clients/qr", "/api/extended/forwardings", "/api/extended/forwardings/delete"}
if path == "/":
return RedirectResponse(url=app_url(request, "/clients"), status_code=303)
allowed = {"/", "/clients", "/api/interfaces", "/api/snapshot", "/api/metrics/history", "/api/app-settings", "/api/auth/logout", "/api/clients/create", "/api/clients/update", "/api/clients/credentials/rotate", "/api/clients/config", "/api/clients/config/download", "/api/clients/qr", "/api/extended/forwardings", "/api/extended/forwardings/delete"}
if path not in allowed or (path == "/api/app-settings" and request.method != "GET"):
return JSONResponse(status_code=403, content={"ok": False, "error": "Brak uprawnień"})
if path.startswith("/api/clients/") or path.startswith("/api/extended/forwardings") or path == "/api/snapshot":
iface = request_interface(request)
if iface not in access["interfaces"]:
return JSONResponse(status_code=403, content={"ok": False, "error": "Brak dostępu do tej sieci"})
return JSONResponse(status_code=403, content={"ok": False, "error": "Administrator nie przydzielił Ci jeszcze żadnej sieci."})
required = None
if path == '/api/clients/create':
required = 'add'
@@ -1593,7 +1601,7 @@ def api_snapshot(request: Request, view: str = "full"):
iface = request_interface(request)
selected_view = str(view or "full").strip().lower()
if request.state.access["role"] != "admin":
selected_view = "clients"
selected_view = "dashboard" if selected_view == "dashboard" else "clients"
if selected_view not in {"full", "clients", "dashboard", "server"}:
selected_view = "full"
data = run_helper("snapshot", {"view": selected_view}, interface=iface)
@@ -1771,6 +1779,14 @@ def api_extended_forward_delete(payload: ExtendedForwardDeleteRequest, request:
return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)})
@app.get("/api/server/host-ips")
def api_host_ips(request: Request):
try:
return run_helper("extended_host_ips", interface=request_interface(request))
except HelperError as exc:
return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)})
@app.get("/api/server/extended-listen")
def api_extended_listen_get(request: Request):
try:
@@ -1811,7 +1827,7 @@ def api_extended_snat_apply(payload: ExtendedSnatRequest, request: Request):
def api_server_settings_apply(payload: ServerSettingsRequest, request: Request):
try:
iface = request_interface(request)
result = run_helper("server_settings_apply", payload.model_dump(), interface=iface)
result = run_helper("server_settings_apply", payload.model_dump(exclude_none=True), interface=iface)
reconcile_node()
audit_action(request, "server.settings_applied", object=iface, result="applied", details=payload.model_dump())
return result
+51 -24
View File
@@ -11,7 +11,7 @@
return nativeFetch(input, init);
};
const page = document.body.dataset.page;
const refreshSeconds = Number(document.body.dataset.refresh || '5');
const refreshSeconds = Number(document.body.dataset.refresh || '10');
const threshold = Number(document.body.dataset.onlineThreshold || '180');
let snapshot = null;
let interfacesData = {interfaces:[], suggested:null};
@@ -625,7 +625,7 @@
function activateSettingsTab(name,{updateHash=true}={}){
if(page!=='settings')return;
const allowed=['general','backups','telegram','mail','https','users','about'];
const allowed=['general','backups','telegram','mail','https','users','branding','about'];
activeSettingsTab=allowed.includes(name)?name:'general';
document.querySelectorAll('[data-settings-tab]').forEach(button=>{
const active=button.dataset.settingsTab===activeSettingsTab;
@@ -642,7 +642,7 @@
function bindSettingsTabs(){
if(page!=='settings')return;
const allowed=['general','backups','telegram','mail','https','users','about'];
const allowed=['general','backups','telegram','mail','https','users','branding','about'];
document.querySelectorAll('[data-settings-tab]').forEach(button=>{
button.addEventListener('click',()=>activateSettingsTab(button.dataset.settingsTab));
button.addEventListener('keydown',event=>{
@@ -966,7 +966,19 @@
const box=$('server-policy-fields'); if(box)box.classList.toggle('disabled-fields',!enabled);
}
function openServerEditor(){
let hostIpDevices = {};
function syncNetworkBinding(prefix){
const mode=$(`${prefix}-listen-mode`)?.value||'all';
const address=mode==='address'||mode==='both', device=mode==='interface'||mode==='both';
$(`${prefix}-listen-address-wrap`).hidden=!address;$(`${prefix}-listen-address`).required=address;
$(`${prefix}-listen-interface-wrap`).hidden=!device;$(`${prefix}-listen-interface`).required=device;
const snat=$(`${prefix}-snat-mode`).value==='address';$(`${prefix}-snat-address-wrap`).hidden=!snat;$(`${prefix}-snat-address`).required=snat;
}
function networkBindingPayload(prefix){
const mode=$(`${prefix}-listen-mode`).value;
return {listen_address:['address','both'].includes(mode)?$(`${prefix}-listen-address`).value.trim():'',listen_interface:['interface','both'].includes(mode)?$(`${prefix}-listen-interface`).value.trim():'',snat_address:$(`${prefix}-snat-mode`).value==='address'?$(`${prefix}-snat-address`).value.trim():'',forward_sources:$(`${prefix}-forward-sources`).value.trim()};
}
async function openServerEditor(){
if(!snapshot?.wireguard?.config_exists)return;
const i=snapshot.config?.interface||{}, x=snapshot.config?.detected||{};
$('server-edit-interface').value=snapshot.interface||'wg0';
@@ -987,6 +999,14 @@
$('server-edit-forward-from').checked=x.forward_from_vpn !== false;
$('server-edit-forward-to').checked=x.forward_to_vpn !== false;
$('server-edit-nat').checked=Boolean(x.nat_enabled);
try{
const [lr,sr,gr]=await Promise.all([fetch(appUrl('/api/server/extended-listen')),fetch(appUrl('/api/server/extended-snat')),fetch(appUrl('/api/extended/ip-groups'))]);
const [listen,snat,groups]=await Promise.all([lr.json(),sr.json(),gr.json()]);if(!lr.ok||!sr.ok||!gr.ok)throw new Error(listen.error||snat.error||groups.error||'Nie udało się odczytać ustawień sieci.');
$('server-edit-listen-address').value=listen.address||'';$('server-edit-listen-interface').value=listen.interface||'';
$('server-edit-listen-mode').value=listen.address?(listen.interface?'both':'address'):(listen.interface?'interface':'all');
$('server-edit-snat-address').value=snat.address||'';$('server-edit-snat-mode').value=snat.address?'address':'auto';syncNetworkBinding('server-edit');
$('server-edit-forward-sources').value=(groups.groups?.[`_wgext_network_${snapshot.interface}`]?.sources||[]).join(', ');
}catch(err){toast(err.message);return;}
setPolicyFieldsEnabled(policy);
operationStatus('server-edit-status','');
modalShow('server-edit-modal',true);
@@ -1034,6 +1054,7 @@
ip_forwarding:$('server-edit-ip-forwarding').checked,
forward_from_vpn:$('server-edit-forward-from').checked,
forward_to_vpn:$('server-edit-forward-to').checked,
...networkBindingPayload('server-edit'),
};
if(!confirm(t('server.apply_confirm','Save these server settings and apply them now? WireGuard will be restarted briefly. A backup is created first and WGTools will roll back automatically if the new configuration does not start.')))return;
button.disabled=true;
@@ -1054,17 +1075,21 @@
}
function bindServerEditor(){
if(page==='server'){
for(const prefix of ['setup','new-interface','server-edit']){for(const name of ['listen-mode','snat-mode'])$(`${prefix}-${name}`)?.addEventListener('change',()=>syncNetworkBinding(prefix));$(`${prefix}-snat-address`)?.addEventListener('change',e=>{const device=hostIpDevices[e.target.value.trim()];if(device)$(`${prefix}-uplink`).value=device;});syncNetworkBinding(prefix);}
fetch(appUrl('/api/server/host-ips')).then(async r=>{const d=await r.json();if(!r.ok)throw new Error(d.error);hostIpDevices=d.addresses||{};const items=Object.entries(hostIpDevices),devices=[...new Set(items.map(([,dev])=>dev))];$('host-ip-options').innerHTML=items.map(([ip,dev])=>`<option value="${esc(ip)}">${esc(dev)}</option>`).join('');$('host-interface-options').innerHTML=devices.map(dev=>`<option value="${esc(dev)}"></option>`).join('');$('host-forward-options').innerHTML=[...items.map(([ip])=>ip),...devices].map(value=>`<option value="${esc(value)}"></option>`).join('');}).catch(err=>toast(err.message));
}
if(page==='server' && $('extended-group-form')){
const loadGroups=async()=>{
try{const r=await fetch(appUrl('/api/extended/ip-groups'));const d=await r.json();if(!r.ok)throw new Error(d.error);
$('extended-groups-list').innerHTML=Object.entries(d.groups||{}).map(([name,g])=>`<div class="group-row"><div><b>${esc(name)}</b><p>${esc((g.addresses||[]).join(', '))}</p><p>Sieci: ${esc((g.interfaces||[]).join(', '))}</p></div><div class="action-row"><button class="btn small" type="button" data-ext-group-edit="${esc(name)}">Edytuj</button><button class="btn small danger" type="button" data-ext-group-delete="${esc(name)}">Usuń</button></div></div>`).join('')||'<p>Brak grup adresów.</p>';
$('extended-groups-list').innerHTML=Object.entries(d.groups||{}).filter(([name])=>!name.startsWith('_wgext_network_')).map(([name,g])=>`<div class="group-row"><div><b>${esc(name)}</b><p>${esc((g.addresses||[]).join(', '))}</p><p>Sieci: ${esc((g.interfaces||[]).join(', '))}</p></div><div class="action-row"><button class="btn small" type="button" data-ext-group-edit="${esc(name)}">Edytuj</button><button class="btn small danger" type="button" data-ext-group-delete="${esc(name)}">Usuń</button></div></div>`).join('')||'<p>Brak grup adresów.</p>';
$('extended-groups-list').insertAdjacentHTML('beforeend',`<h3>Przegląd przekierowań</h3>`+(d.forwards||[]).map(f=>`<p>${esc(f.interface)}: ${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}</p>`).join(''));
return d.groups||{};
}catch(err){operationStatus('extended-group-status',err.message,'error');return {};}
};
const save=async p=>{const r=await fetch(appUrl('/api/extended/ip-groups'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(p)});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadGroups();};
$('extended-group-form').addEventListener('submit',async e=>{e.preventDefault();try{await save({name:$('extended-group-name').value.trim(),addresses:$('extended-group-addresses').value.split(',').map(x=>x.trim()).filter(Boolean),interfaces:$('extended-group-interfaces').value.split(',').map(x=>x.trim()).filter(Boolean)});operationStatus('extended-group-status','Zapisano grupę.','success');}catch(err){operationStatus('extended-group-status',err.message,'error');}});
$('extended-groups-list').addEventListener('click',async e=>{const edit=e.target.closest('[data-ext-group-edit]'), del=e.target.closest('[data-ext-group-delete]');try{if(edit){const groups=await loadGroups(),name=edit.dataset.extGroupEdit,g=groups[name];if(g){$('extended-group-name').value=name;$('extended-group-addresses').value=g.addresses.join(', ');$('extended-group-interfaces').value=g.interfaces.join(', ');}}else if(del && confirm('Usunąć grupę adresów?')){await save({name:del.dataset.extGroupDelete,delete:true});}}catch(err){operationStatus('extended-group-status',err.message,'error');}});
$('extended-groups-list').addEventListener('click',async e=>{const edit=e.target.closest('[data-ext-group-edit]'), del=e.target.closest('[data-ext-group-delete]');try{if(edit){const groups=await loadGroups(),name=edit.dataset.extGroupEdit,g=groups[name];if(g){$('extended-group-name').value=name;$('extended-group-addresses').value=g.addresses.join(', ');$('extended-group-interfaces').value=g.interfaces.join(', ');operationStatus('extended-group-status',`Edytujesz grupę ${name}. Zmień pola i kliknij Zapisz grupę.`, 'working');$('extended-group-form').scrollIntoView({behavior:'smooth',block:'center'});$('extended-group-addresses').focus();}}else if(del && confirm('Usunąć grupę adresów?')){await save({name:del.dataset.extGroupDelete,delete:true});}}catch(err){operationStatus('extended-group-status',err.message,'error');}});
loadGroups();
}
if(page==='clients' && $('extended-forward-form')){
@@ -1751,6 +1776,7 @@
policy_table:$('setup-policy-table').value.trim(),
nat_enabled:$('setup-nat').checked,
ip_forwarding:$('setup-forwarding').checked,
...networkBindingPayload('setup'),
};
const ok=confirm(t('server.create_confirm','Create and start the WireGuard server with these settings?'));
if(!ok)return;
@@ -1849,7 +1875,7 @@
const resetTitle=!mailConfigured?t('settings.user_reset_mail_not_configured','Configure and enable mail first.'):(!email?t('settings.user_reset_email_missing','Add an email address first.'):'');
const mfaBadge=mfaEnabled?`<span class="badge success">${esc(t('settings.mfa_enabled','Enabled'))}</span>`:`<span class="badge">${esc(t('settings.mfa_disabled','Disabled'))}</span>`;
const mfaButton=isCurrent?`<button class="btn small" data-user-action="mfa" data-user-id="${Number(u.id)}" data-user-name="${esc(u.username)}" data-mfa-enabled="${mfaEnabled?'1':'0'}" data-mfa-recovery="${Number(u.mfa_recovery_remaining||0)}">${esc(t('settings.mfa_button','MFA'))}</button>`:'';
return `<tr><td><div class="peer-name">${esc(u.username)}</div>${isCurrent?`<div class="subtle">${esc(t('settings.current_user','Current user'))}</div>`:''}</td><td>${email?esc(email):'<span class="subtle">—</span>'}</td><td>${mfaBadge}</td><td>${esc(formatDate(u.created_at))}</td><td>${esc(formatDate(u.last_login))}</td><td><div class="action-row">${mfaButton}<button class="btn small" data-user-action="access" data-user-id="${Number(u.id)}" data-role="${esc(u.access?.role||'user')}" data-interfaces="${esc((u.access?.interfaces||[]).join(', '))}" data-permissions="${esc(JSON.stringify(u.access?.permissions||{}))}">Uprawnienia: ${u.access?.role==='admin'?'administrator':'użytkownik'}</button><button class="btn small" data-user-action="email" data-user-id="${Number(u.id)}" data-user-name="${esc(u.username)}" data-user-email="${esc(email)}">${esc(t('settings.change_email','E-mail'))}</button><button class="btn small" data-user-action="password" data-user-id="${Number(u.id)}" data-user-name="${esc(u.username)}">${esc(t('settings.change_password','Change password'))}</button><button class="btn small" data-user-action="reset" data-user-id="${Number(u.id)}" data-user-name="${esc(u.username)}" data-user-email="${esc(email)}" ${resetDisabled?'disabled':''} title="${esc(resetTitle)}">${esc(t('settings.send_password_reset','Send reset'))}</button><button class="btn small danger" data-user-action="delete" data-user-id="${Number(u.id)}" data-user-name="${esc(u.username)}" ${isCurrent?'disabled':''}>${esc(t('settings.delete_user','Delete'))}</button></div></td></tr>`;
return `<tr><td><div class="peer-name">${esc(u.username)}</div>${isCurrent?`<div class="subtle">${esc(t('settings.current_user','Current user'))}</div>`:''}</td><td>${email?esc(email):'<span class="subtle">—</span>'}</td><td>${mfaBadge}</td><td>${esc(formatDate(u.created_at))}</td><td>${esc(formatDate(u.last_login))}</td><td><div class="action-row">${mfaButton}<button class="btn small" data-user-action="access" data-user-name="${esc(u.username)}" data-user-id="${Number(u.id)}" data-role="${esc(u.access?.role||'user')}" data-interfaces="${esc((u.access?.interfaces||[]).join(', '))}" data-permissions="${esc(JSON.stringify(u.access?.permissions||{}))}">Uprawnienia: ${u.access?.role==='admin'?'administrator':'użytkownik'}</button><button class="btn small" data-user-action="email" data-user-id="${Number(u.id)}" data-user-name="${esc(u.username)}" data-user-email="${esc(email)}">${esc(t('settings.change_email','E-mail'))}</button><button class="btn small" data-user-action="password" data-user-id="${Number(u.id)}" data-user-name="${esc(u.username)}">${esc(t('settings.change_password','Change password'))}</button><button class="btn small" data-user-action="reset" data-user-id="${Number(u.id)}" data-user-name="${esc(u.username)}" data-user-email="${esc(email)}" ${resetDisabled?'disabled':''} title="${esc(resetTitle)}">${esc(t('settings.send_password_reset','Send reset'))}</button><button class="btn small danger" data-user-action="delete" data-user-id="${Number(u.id)}" data-user-name="${esc(u.username)}" ${isCurrent?'disabled':''}>${esc(t('settings.delete_user','Delete'))}</button></div></td></tr>`;
}).join('') || `<tr><td colspan="6" class="empty">—</td></tr>`;
}catch(e){body.innerHTML=`<tr><td colspan="6" class="empty">${esc(e.message)}</td></tr>`;}
}
@@ -2027,19 +2053,13 @@
$('add-user-button')?.addEventListener('click',openAddUser); $('user-form')?.addEventListener('submit',createUser); $('password-form')?.addEventListener('submit',saveUserPassword); $('email-form')?.addEventListener('submit',saveUserEmail); $('logout-button')?.addEventListener('click',logout);
$('mfa-start-button')?.addEventListener('click',startMfaSetup); $('mfa-confirm-button')?.addEventListener('click',confirmMfaSetup); $('mfa-disable-button')?.addEventListener('click',disableMfa); $('mfa-regenerate-button')?.addEventListener('click',regenerateMfaRecovery); $('mfa-copy-recovery-button')?.addEventListener('click',copyMfaRecovery);
$('users-table-body')?.addEventListener('click',async e=>{const b=e.target.closest('[data-user-action]');if(!b||b.disabled)return;const id=Number(b.dataset.userId),name=b.dataset.userName||'',email=b.dataset.userEmail||'';if(b.dataset.userAction==='access'){
const roleInput=prompt('Rola: administrator albo użytkownik',b.dataset.role==='admin'?'administrator':'użytkownik'); if(roleInput===null)return;
const role=({administrator:'admin',użytkownik:'user',admin:'admin',user:'user'})[roleInput.trim().toLowerCase()]||roleInput.trim();
const interfaces=prompt('Dozwolone interfejsy, oddzielone przecinkami (np. wg1, wg2)',b.dataset.interfaces||''); if(interfaces===null)return;
const names=interfaces.split(',').map(s=>s.trim()).filter(Boolean), permissions={};
let previous={};try{previous=JSON.parse(b.dataset.permissions||'{}');}catch(_){}
if(role==='user')for(const iface of names){
const labels={add:'dodawanie',edit:'edycja',forward:'porty'}, reverse={dodawanie:'add',edycja:'edit',porty:'forward'};
const defaults=(previous[iface]||['add','edit','forward']).map(x=>labels[x]||x).join(', ');
const answer=prompt(`Uprawnienia dla ${iface}: dodawanie, edycja, porty (oddziel przecinkami; puste = tylko podgląd)`,defaults);if(answer===null)return;
permissions[iface]=answer.split(',').map(x=>x.trim().toLowerCase()).filter(Boolean).map(x=>reverse[x]||x);
} else for(const iface of names)permissions[iface]=[];
try{const r=await fetch(appUrl(`/api/users/${id}/access`),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({role,interfaces:names,permissions})});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadUsers();}catch(err){alert(err.message);}
try{const data=await fetchInterfaces(false);if(!data)throw new Error('Nie udało się pobrać sieci.');const selected=(b.dataset.interfaces||'').split(',').map(x=>x.trim());let previous={};try{previous=JSON.parse(b.dataset.permissions||'{}');}catch(_){}
$('user-access-id').value=String(id);$('user-access-name').textContent=name;$('user-access-role').value=b.dataset.role||'user';
$('user-access-networks').innerHTML=(data.interfaces||[]).filter(x=>x.configured).map(x=>{const checked=selected.includes(x.name),p=previous[x.name]||[];return `<div class="group-row" data-access-network="${esc(x.name)}"><div><label class="check-label"><input type="checkbox" data-access-enabled ${checked?'checked':''}><strong>${esc(x.display_name||x.name)} (${esc(x.name)})</strong></label><div class="action-row">${[['add','Dodawanie klientów'],['edit','Edycja klientów'],['forward','Przekierowania portów']].map(([key,label])=>`<label class="check-label"><input type="checkbox" data-access-permission="${key}" ${p.includes(key)?'checked':''}>${label}</label>`).join('')}</div></div></div>`;}).join('')||'<p>Brak skonfigurowanych sieci WireGuard.</p>';
operationStatus('user-access-status','');modalShow('user-access-modal',true);
}catch(err){alert(err.message);}
}else if(b.dataset.userAction==='mfa')openMfaUser(id,name,b.dataset.mfaEnabled==='1',Number(b.dataset.mfaRecovery||0));else if(b.dataset.userAction==='password')openPasswordUser(id,name);else if(b.dataset.userAction==='email')openEmailUser(id,name,email);else if(b.dataset.userAction==='reset')sendUserPasswordReset(id,name,email);else if(b.dataset.userAction==='delete')deleteUser(id,name);});
$('user-access-form')?.addEventListener('submit',async e=>{e.preventDefault();const interfaces=[],permissions={};document.querySelectorAll('[data-access-network]').forEach(row=>{if(row.querySelector('[data-access-enabled]').checked){const name=row.dataset.accessNetwork;interfaces.push(name);permissions[name]=[...row.querySelectorAll('[data-access-permission]:checked')].map(x=>x.dataset.accessPermission);}});try{const r=await fetch(appUrl(`/api/users/${Number($('user-access-id').value)}/access`),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({role:$('user-access-role').value,interfaces,permissions})});const d=await r.json();if(!r.ok)throw new Error(d.error);modalShow('user-access-modal',false);await loadUsers();}catch(err){operationStatus('user-access-status',err.message,'error');}});
if(page==='settings')loadUsers();
}
@@ -2075,6 +2095,7 @@
auditAutoRefreshTimer=setInterval(()=>{
const modal=$('audit-modal');
if(!modal||modal.hidden){stopAuditAutoRefresh();return;}
if(document.hidden)return;
loadAudit({showLoading:false});
},interval);
}
@@ -2914,6 +2935,7 @@
vpn_network:$('new-interface-vpn-network').value.trim(),server_address:$('new-interface-server-address').value.trim(),listen_port:Number($('new-interface-port').value),mtu:Number($('new-interface-mtu').value||0),
uplink_interface:$('new-interface-uplink').value.trim(),gateway:$('new-interface-gateway').value.trim(),local_network:$('new-interface-local-network').value.trim(),policy_table:$('new-interface-policy-table').value.trim(),
nat_enabled:$('new-interface-nat').checked,ip_forwarding:$('new-interface-forwarding').checked,
...networkBindingPayload('new-interface'),
};
const label=payload.display_name?`${payload.interface} · ${payload.display_name}`:payload.interface;
if(!confirm(t('interfaces.create_confirm','Create and start interface {name}?').replace('{name}',label)))return;
@@ -2971,15 +2993,20 @@
if(snapshot)renderHeader(snapshot);
if(page==='dashboard'){
loadMetricsHistory();
loadDashboardDiagnostics();
historyTimer=setInterval(loadMetricsHistory,60*1000);
dashboardDiagnosticsTimer=setInterval(loadDashboardDiagnostics,60*1000);
if(document.body.dataset.role==='admin')loadDashboardDiagnostics();
historyTimer=setInterval(()=>{if(!document.hidden)loadMetricsHistory();},60*1000);
if(document.body.dataset.role==='admin')dashboardDiagnosticsTimer=setInterval(()=>{if(!document.hidden)loadDashboardDiagnostics();},60*1000);
}
if(page==='server'){
loadServerDiagnostics();
serverDiagnosticsTimer=setInterval(loadServerDiagnostics,60*1000);
serverDiagnosticsTimer=setInterval(()=>{if(!document.hidden)loadServerDiagnostics();},60*1000);
}
if(page!=='settings'){
let refreshing=false;
const refreshVisible=async()=>{if(document.hidden||refreshing)return;refreshing=true;try{await fetchSnapshot(false);}finally{refreshing=false;}};
timer=setInterval(refreshVisible,Math.max(2,refreshSeconds)*1000);
document.addEventListener('visibilitychange',()=>{if(!document.hidden)refreshVisible();});
}
if(page!=='settings') timer=setInterval(()=>fetchSnapshot(false),Math.max(2,refreshSeconds)*1000);
}
boot();
})();
+16 -27
View File
@@ -1,5 +1,15 @@
{% extends "base.html" %}
{% block content %}
{% macro network_binding_fields(prefix) %}
<label><span>Nasłuchiwanie WireGuard</span><select id="{{ prefix }}-listen-mode"><option value="all">Wszystkie adresy i interfejsy</option><option value="address">Wybrany adres IPv4</option><option value="interface">Wybrany interfejs</option><option value="both">Adres IPv4 i interfejs</option></select><small>Port ustawisz w polu „Port nasłuchiwania”. Przy ograniczeniu dostęp przez IPv6 jest blokowany.</small></label>
<label id="{{ prefix }}-listen-address-wrap" hidden><span>Adres IPv4 nasłuchiwania</span><input id="{{ prefix }}-listen-address" list="host-ip-options" placeholder="np. 203.0.113.10"></label>
<label id="{{ prefix }}-listen-interface-wrap" hidden><span>Interfejs wejściowy</span><input id="{{ prefix }}-listen-interface" list="host-interface-options" placeholder="np. eth0"></label>
<label><span>Ruch wychodzący (SNAT)</span><select id="{{ prefix }}-snat-mode"><option value="auto">Adres interfejsu wyjściowego (automatycznie)</option><option value="address">Wybrany główny adres IPv4</option></select></label>
<label id="{{ prefix }}-snat-address-wrap" hidden><span>Główny adres IPv4</span><input id="{{ prefix }}-snat-address" list="host-ip-options" placeholder="np. 203.0.113.10"><small>Adres musi należeć do wybranego interfejsu wyjściowego.</small></label>
<label><span>Adresy lub interfejsy do przekierowania portów</span><input id="{{ prefix }}-forward-sources" list="host-forward-options" placeholder="np. 203.0.113.10, eth1"><small>Wybierz lub wpisz adresy IPv4 albo nazwy interfejsów oddzielone przecinkami. Możesz użyć adresu SNAT.</small></label>
{% endmacro %}
<datalist id="host-ip-options"></datalist><datalist id="host-interface-options"></datalist><datalist id="host-forward-options"></datalist>
<section class="page-head page-head-actions">
<div>
<h1 data-i18n="server.title">{{ tr('server.title') }}</h1>
@@ -11,30 +21,6 @@
</div>
</section>
<section class="card" id="extended-snat-card">
<div class="card-head"><div><h2>Główny adres IPv4 dla ruchu wychodzącego</h2><p>Adres musi być przypisany do interfejsu wyjściowego serwera. Puste pole wyłącza regułę SNAT.</p></div></div>
<form id="extended-snat-form" class="settings-form-pad">
<div class="setup-grid">
<label><span>Publiczny adres IPv4</span><input id="extended-snat-address" placeholder="203.0.113.10" maxlength="15"></label>
<label><span>Interfejs wyjściowy</span><input id="extended-snat-uplink" placeholder="eth0" maxlength="15"></label>
</div>
<button class="btn primary" type="submit">Zapisz adres SNAT</button>
<div id="extended-snat-status" class="operation-status" hidden></div>
</form>
</section>
<section class="card" id="extended-listen-card">
<div class="card-head"><div><h2>Ograniczenie nasłuchiwania WireGuard</h2><p>Wybierz adres IPv4, interfejs wejściowy lub oba. Dla tego ograniczenia IPv6 zostanie zablokowane. Puste pola wyłączają ograniczenie.</p></div></div>
<form id="extended-listen-form" class="settings-form-pad">
<div class="setup-grid">
<label><span>Adres IPv4</span><input id="extended-listen-address" placeholder="203.0.113.10" maxlength="15"></label>
<label><span>Interfejs wejściowy</span><input id="extended-listen-interface" placeholder="eth0" maxlength="15"></label>
</div>
<button class="btn primary" type="submit">Zapisz ograniczenie</button>
<div id="extended-listen-status" class="operation-status" hidden></div>
</form>
</section>
<section class="card">
<div class="card-head"><div><h2>Grupy publicznych adresów IPv4</h2><p>Grupy przydzielają adresy do sieci. Ten sam adres może należeć do wielu grup.</p></div></div>
<form id="extended-group-form" class="settings-form-pad">
@@ -90,6 +76,7 @@
<span data-i18n="server.listen_port">{{ tr('server.listen_port') }}</span>
<input id="setup-port" type="number" min="1" max="65535" value="51820" required>
</label>
{{ network_binding_fields('setup') }}
<label>
<span data-i18n="interfaces.display_name">{{ tr('interfaces.display_name') }}</span>
<input id="setup-display-name" maxlength="64" placeholder="Home">
@@ -118,7 +105,7 @@
<div class="setup-grid">
<label>
<span data-i18n="server.uplink">{{ tr('server.uplink') }}</span>
<input id="setup-uplink" class="mono" placeholder="enp6s18" required>
<input id="setup-uplink" list="host-interface-options" class="mono" placeholder="enp6s18" required>
</label>
<label>
<span data-i18n="server.gateway">{{ tr('server.gateway') }}</span>
@@ -491,6 +478,7 @@
<input id="new-interface-port" type="number" min="1" max="65535" required>
<small>{{ tr('interfaces.unique_port_hint') }}</small>
</label>
{{ network_binding_fields('new-interface') }}
<label>
<span>{{ tr('server.mtu') }}</span>
<input id="new-interface-mtu" type="number" min="576" max="65535" placeholder="1420">
@@ -498,7 +486,7 @@
</label>
<label>
<span>{{ tr('server.uplink') }}</span>
<input id="new-interface-uplink" class="mono" placeholder="enp6s18" required>
<input id="new-interface-uplink" list="host-interface-options" class="mono" placeholder="enp6s18" required>
</label>
<label>
<span>{{ tr('server.gateway') }}</span>
@@ -555,6 +543,7 @@
<span>{{ tr('server.listen_port') }}</span>
<input id="server-edit-port" type="number" min="1" max="65535" required>
</label>
{{ network_binding_fields('server-edit') }}
<label>
<span>{{ tr('server.mtu') }}</span>
<input id="server-edit-mtu" type="number" min="576" max="65535" placeholder="1420">
@@ -577,7 +566,7 @@
<div class="setup-grid">
<label>
<span>{{ tr('server.uplink') }}</span>
<input id="server-edit-uplink" class="mono" placeholder="enp6s18" required>
<input id="server-edit-uplink" list="host-interface-options" class="mono" placeholder="enp6s18" required>
</label>
<label>
<span>{{ tr('server.local_network') }}</span>
+13 -1
View File
@@ -232,7 +232,7 @@
<div class="card-head">
<div>
<h2>{{ tr('settings.users') }}</h2>
<p>{{ tr('settings.users_subtitle') }}</p>
<p>{{ tr('settings.users_subtitle') }} Wybierz „Uprawnienia”, aby przydzielić użytkownikowi sieci i dozwolone działania.</p>
</div>
<button type="button" class="btn" id="add-user-button">{{ tr('settings.add_user') }}</button>
</div>
@@ -274,6 +274,18 @@
</section>
</div>
<div class="modal-backdrop" id="user-access-modal" hidden>
<div class="modal-card" role="dialog" aria-modal="true" aria-labelledby="user-access-title">
<div class="modal-head"><div><h2 id="user-access-title">Uprawnienia użytkownika</h2><p id="user-access-name"></p></div><button class="icon-btn" type="button" data-modal-close="user-access-modal" aria-label="Zamknij">×</button></div>
<form id="user-access-form"><div class="modal-body">
<input type="hidden" id="user-access-id">
<label><span>Rola</span><select id="user-access-role"><option value="user">Użytkownik</option><option value="admin">Administrator</option></select></label>
<p>Wybierz sieci i działania, które użytkownik może wykonywać w każdej z nich.</p>
<div id="user-access-networks"></div><div id="user-access-status" class="operation-status" hidden></div>
</div><div class="modal-actions"><button type="button" class="btn" data-modal-close="user-access-modal">Anuluj</button><button type="submit" class="btn primary">Zapisz uprawnienia</button></div></form>
</div>
</div>
<div class="modal-backdrop" id="user-modal" hidden>
<div class="modal-card user-modal" role="dialog" aria-modal="true" aria-labelledby="user-modal-title">
<div class="modal-head">
+5 -3
View File
@@ -23,9 +23,9 @@ def main() -> None:
repo = os.environ['GITHUB_REPOSITORY']
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', repo):
raise ValueError('Nieprawidłowa nazwa repozytorium')
token = os.environ['GITEA_RELEASE_TOKEN']
token = os.environ.get('RELEASE_TOKEN', '')
if not token:
raise ValueError('Brakuje sekretu GITEA_RELEASE_TOKEN')
raise ValueError('Brakuje sekretu lub zmiennej RELEASE_TOKEN')
api = f'{server}/api/v1/repos/{repo}/releases'
def request(url: str, method: str, data: bytes, content_type: str) -> dict:
@@ -39,7 +39,9 @@ def main() -> None:
subprocess.run(['git', 'cat-file', '-e', f'HEAD:{required}'], check=True)
subprocess.run(['git', 'archive', '--format=tar.gz', f'--output={package}', 'HEAD'], check=True)
title = f'WGTools-Extended wersja {tag[1:]}'
release = request(api, 'POST', json.dumps({'tag_name': tag, 'name': title, 'body': title, 'draft': True}).encode(), 'application/json')
notes_file = Path('RELEASE_NOTES.md')
notes = notes_file.read_text(encoding='utf-8').strip() if notes_file.is_file() else title
release = request(api, 'POST', json.dumps({'tag_name': tag, 'name': title, 'body': notes or title, 'draft': True}).encode(), 'application/json')
boundary = 'wgtools' + uuid.uuid4().hex
body = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{package.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()
+ package.read_bytes() + f'\r\n--{boundary}--\r\n'.encode())
+1 -1
View File
@@ -78,7 +78,7 @@ if [[ ! -f /etc/wgtools/wgtools.env ]]; then
WGTOOLS_INTERFACE=$WG_INTERFACE
WGTOOLS_PORT=$WEB_PORT
WGTOOLS_HELPER=/usr/local/libexec/wgtools-helper
WGTOOLS_REFRESH_SECONDS=5
WGTOOLS_REFRESH_SECONDS=10
WGTOOLS_ONLINE_THRESHOLD_SECONDS=180
WGTOOLS_DATABASE=/var/lib/wgtools/wgtools.db
WGTOOLS_SESSION_KEY_FILE=/var/lib/wgtools/session.key
+91 -17
View File
@@ -28,6 +28,7 @@ from typing import Any
ALLOWED_ACTIONS = {"snapshot", "interfaces_list", "interface_meta_set", "interface_delete", "metrics_sample", "metrics_history", "diagnostics", "network_trace", "wireguard_start", "wireguard_stop", "wireguard_restart", "install_wireguard", "create_server", "create_client", "update_client", "delete_client", "rotate_client_credentials", "expire_clients", "client_config", "group_create", "group_update", "group_delete", "raw_config_get", "raw_config_apply", "server_settings_apply", "route_create", "route_update", "route_delete", "access_rule_create", "access_rule_update", "access_rule_delete", "migration_backup_create", "migration_restore", "update_check", "update_notice", "update_status", "update_schedule", "update_apply", "traffic_reset", "https_status", "https_ports", "https_issue", "https_enable", "https_disable", "https_switch_commit"}
ALLOWED_ACTIONS.update({"extended_snat_get", "extended_snat_apply"})
ALLOWED_ACTIONS.add("extended_host_ips")
ALLOWED_ACTIONS.update({"extended_listen_get", "extended_listen_apply"})
ALLOWED_ACTIONS.update({"extended_ip_groups_get", "extended_ip_groups_set", "extended_forward_get", "extended_forward_add", "extended_forward_delete"})
ALLOWED_ACTIONS.update({"update_file_schedule", "update_file_apply"})
@@ -2121,6 +2122,7 @@ def create_server(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
raise RuntimeError(f"{config_path} already exists; WGTools will not overwrite an existing server configuration")
settings = validate_server_payload(iface, payload)
source_groups = _prepare_network_sources(iface, str(payload.get("forward_sources") or "")) if payload.get("forward_sources") else None
private_key = generate_private_key()
public_key = private_to_public(private_key)
network = settings["network"]
@@ -2173,6 +2175,10 @@ def create_server(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
lines.extend(f"PostDown = {cmd}" for cmd in post_down)
lines.append("")
config_text = "\n".join(lines)
if payload.get("listen_address") or payload.get("listen_interface"):
config_text = extended_listen_apply(iface, {"address": payload.get("listen_address"), "interface": payload.get("listen_interface")}, text_override=config_text, prepare_only=True)["content"]
if payload.get("snat_address"):
config_text = extended_snat_apply(iface, {"address": payload.get("snat_address"), "uplink": uplink}, text_override=config_text, prepare_only=True)["content"]
WG_DIR.mkdir(parents=True, exist_ok=True)
os.chmod(WG_DIR, 0o700)
@@ -2204,6 +2210,15 @@ def create_server(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
if not dump.get("running"):
raise RuntimeError("wg-quick started without an error, but the WireGuard interface is not visible in wg show")
if source_groups is not None:
try:
_save_extended_groups(source_groups)
except Exception as exc:
run([systemctl, "disable", "--now", f"wg-quick@{iface}.service"], timeout=30)
failed_path = WG_DIR / f"{iface}.failed-{time.strftime('%Y%m%d-%H%M%S')}.conf"
os.replace(config_path, failed_path)
raise RuntimeError(f"Nie zapisano adresów do przekierowań; interfejs zatrzymano, konfigurację zachowano w {failed_path}: {exc}") from exc
interface_meta_set(iface, {"display_name": str(payload.get("display_name") or iface)})
return {
@@ -4335,7 +4350,54 @@ def _extended_configured() -> set[str]:
def _extended_allowed(groups: dict[str, Any], iface: str) -> set[str]:
return {addr for group in groups.values() if iface in group.get("interfaces", []) for addr in group.get("addresses", [])}
allowed: set[str] = set()
host_ips = None
for group in groups.values():
if iface not in group.get("interfaces", []):
continue
if "sources" in group:
if host_ips is None:
host_ips = _extended_host_ips()
allowed.update(ip for ip, dev in host_ips.items() if ip in group["sources"] or dev in group["sources"])
else:
allowed.update(group.get("addresses", []))
return allowed
def _network_sources_name(iface: str) -> str:
return f"_wgext_network_{iface}"
def _prepare_network_sources(iface: str, text: str) -> dict[str, Any]:
sources = list(dict.fromkeys(item.strip() for item in text.split(',') if item.strip()))
if len(sources) > 256:
raise ValueError("Zbyt wiele adresów lub interfejsów")
host = _extended_host_ips()
for source in sources:
if source not in host and source not in host.values():
raise ValueError(f"Adres lub interfejs {source} nie ma przypisanego IPv4 na serwerze")
groups = _extended_groups()
key = _network_sources_name(iface)
if sources:
groups[key] = {"addresses": sorted(ip for ip, dev in host.items() if ip in sources or dev in sources), "interfaces": [iface], "sources": sources}
else:
groups.pop(key, None)
if (WG_DIR / f"{iface}.conf").is_file():
for row in _extended_forwards(iface):
if row["public_ip"] not in _extended_allowed(groups, iface):
raise ValueError("Najpierw usuń przekierowania korzystające z odbieranego adresu")
return groups
def _save_extended_groups(groups: dict[str, Any]) -> None:
EXT_IP_GROUPS_PATH.parent.mkdir(parents=True, exist_ok=True)
temp = EXT_IP_GROUPS_PATH.with_name(f".{EXT_IP_GROUPS_PATH.name}.{os.getpid()}.tmp")
try:
temp.write_text(json.dumps(groups, ensure_ascii=False), encoding="utf-8")
os.chmod(temp, 0o600)
os.replace(temp, EXT_IP_GROUPS_PATH)
finally:
temp.unlink(missing_ok=True)
def _extended_host_ips() -> dict[str, str]:
@@ -4401,6 +4463,8 @@ def extended_ip_groups_set(payload: dict[str, Any]) -> dict[str, Any]:
name = str(payload.get("name") or "").strip()
if not re.fullmatch(r"[A-Za-z0-9_. -]{1,64}", name):
raise ValueError("Nieprawidłowa nazwa grupy")
if name.startswith('_wgext_network_'):
raise ValueError("Tą grupą zarządza formularz sieci")
groups = _extended_groups()
if payload.get("delete"):
if name not in groups:
@@ -4426,14 +4490,7 @@ def extended_ip_groups_set(payload: dict[str, Any]) -> dict[str, Any]:
for row in _extended_forwards(iface):
if row["public_ip"] not in _extended_allowed(groups, iface):
raise ValueError(f"Zmiana odebrałaby adres używany przez przekierowanie w {iface}; usuń najpierw przekierowanie")
EXT_IP_GROUPS_PATH.parent.mkdir(parents=True, exist_ok=True)
temp = EXT_IP_GROUPS_PATH.with_name(f".{EXT_IP_GROUPS_PATH.name}.{os.getpid()}.tmp")
try:
temp.write_text(json.dumps(groups, ensure_ascii=False), encoding="utf-8")
os.chmod(temp, 0o600)
os.replace(temp, EXT_IP_GROUPS_PATH)
finally:
temp.unlink(missing_ok=True)
_save_extended_groups(groups)
return {"ok": True, "groups": groups}
@@ -4544,9 +4601,9 @@ def extended_listen_get(iface: str) -> dict[str, Any]:
return {"ok": True, "address": match.group(1), "interface": match.group(2)}
def extended_listen_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
def extended_listen_apply(iface: str, payload: dict[str, Any], *, text_override: str | None = None, prepare_only: bool = False) -> dict[str, Any]:
require_valid_iface(iface)
text = read_config_text(iface)
text = text_override if text_override is not None else read_config_text(iface)
cfg = parse_config(text, iface)
address = str(payload.get("address") or "").strip()
device = str(payload.get("interface") or "").strip()
@@ -4586,14 +4643,15 @@ def extended_listen_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]
section.extend([metadata + f"address={address} interface={device}",
f"PostUp = iptables -w -I INPUT 1 {drop4} && ip6tables -w -I INPUT 1 {drop6} && iptables -w -I INPUT 1 {allow4} || {{ {cleanup}; false; }}",
f"PostDown = {cleanup}"])
result = raw_config_apply(iface, {"content": "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"})
new_text = "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"
result = {"ok": True, "content": new_text} if prepare_only else raw_config_apply(iface, {"content": new_text})
result.update({"address": address, "interface": device})
return result
def extended_snat_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
def extended_snat_apply(iface: str, payload: dict[str, Any], *, text_override: str | None = None, prepare_only: bool = False) -> dict[str, Any]:
require_valid_iface(iface)
text = read_config_text(iface)
text = text_override if text_override is not None else read_config_text(iface)
cfg = parse_config(text, iface)
address = str(payload.get("address") or "").strip()
uplink = str(payload.get("uplink") or "").strip()
@@ -4626,7 +4684,7 @@ def extended_snat_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
rule = f"-s {network} -o {uplink} -m comment --comment {marker} -j SNAT --to-source {address}"
section.extend([f"PostUp = iptables -t nat -I POSTROUTING 1 {rule}", f"PostDown = iptables -t nat -D POSTROUTING {rule}"])
new_text = "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"
result = raw_config_apply(iface, {"content": new_text})
result = {"ok": True, "content": new_text} if prepare_only else raw_config_apply(iface, {"content": new_text})
result.update({"address": address, "uplink": uplink if address else ""})
return result
@@ -4641,15 +4699,16 @@ def server_settings_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]
old_text = read_config_text(iface)
old_cfg = parse_config(old_text, iface)
source_groups = _prepare_network_sources(iface, str(payload.get("forward_sources") or "")) if "forward_sources" in payload else None
normalized = dict(payload)
normalized["forward_from_vpn"] = bool(payload.get("forward_from_vpn", True))
normalized["forward_to_vpn"] = bool(payload.get("forward_to_vpn", True))
settings = validate_server_payload(iface, normalized)
listen = extended_listen_get(iface)
if (listen["address"] or listen["interface"]) and settings["listen_port"] != (old_cfg.get("interface") or {}).get("listen_port"):
if "listen_address" not in payload and (listen["address"] or listen["interface"]) and settings["listen_port"] != (old_cfg.get("interface") or {}).get("listen_port"):
raise ValueError("Przed zmianą portu wyłącz ograniczenie nasłuchiwania i ustaw je ponownie")
snat = extended_snat_get(iface)
if snat["address"] and (settings["network"] != str((old_cfg.get("detected") or {}).get("vpn_network") or "") or settings["uplink_interface"] != snat["uplink"]):
if "snat_address" not in payload and snat["address"] and (settings["network"] != str((old_cfg.get("detected") or {}).get("vpn_network") or "") or settings["uplink_interface"] != snat["uplink"]):
raise ValueError("Przed zmianą sieci VPN lub interfejsu wyjściowego usuń podstawowy adres SNAT i ustaw go ponownie po zapisaniu zmian")
settings["forward_from_vpn"] = normalized["forward_from_vpn"]
settings["forward_to_vpn"] = normalized["forward_to_vpn"]
@@ -4710,7 +4769,20 @@ def server_settings_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]
new_lines = [*prefix, *new_section, *suffix]
new_text = "\n".join(new_lines).rstrip() + "\n"
new_text = sync_managed_client_policies(new_text, iface)
if "listen_address" in payload:
new_text = extended_listen_apply(iface, {"address": payload.get("listen_address"), "interface": payload.get("listen_interface")}, text_override=new_text, prepare_only=True)["content"]
if "snat_address" in payload:
new_text = extended_snat_apply(iface, {"address": payload.get("snat_address"), "uplink": settings["uplink_interface"]}, text_override=new_text, prepare_only=True)["content"]
result = raw_config_apply(iface, {"content": new_text})
if source_groups is not None:
try:
_save_extended_groups(source_groups)
except Exception as exc:
try:
raw_config_apply(iface, {"content": old_text})
except Exception as rollback:
raise RuntimeError(f"Nie zapisano adresów do przekierowań i nie udało się przywrócić konfiguracji: {rollback}") from exc
raise RuntimeError(f"Nie zapisano adresów do przekierowań; przywrócono poprzednią konfigurację: {exc}") from exc
sysctl_file = Path("/etc/sysctl.d/99-wgtools-wireguard.conf")
sysctl_value = "1" if settings["ip_forwarding"] else "0"
@@ -6642,6 +6714,8 @@ def main() -> int:
result = locked_call(lambda: server_settings_apply(iface, payload))
elif action == "extended_snat_get":
result = extended_snat_get(iface)
elif action == "extended_host_ips":
result = {"ok": True, "addresses": _extended_host_ips()}
elif action == "extended_snat_apply":
payload = read_json_stdin()
result = locked_call(lambda: extended_snat_apply(iface, payload))
+16 -5
View File
@@ -24,8 +24,8 @@ def test_user_is_restricted_to_assigned_interface(tmp_path):
if action == 'interfaces_list':
return {'ok': True, 'interfaces': [{'name': 'wg1'}, {'name': 'wg2'}]}
if action == 'snapshot':
return {'ok': True, 'config': {'interface': {'post_up': ['secret hook']}}, 'peers': []}
return {'ok': True}
return {'ok': True, 'interface': kwargs.get('interface'), 'config': {'interface': {'post_up': ['secret hook']}}, 'peers': []}
return {'ok': True, 'interface': kwargs.get('interface')}
with patch.object(m, 'run_helper', side_effect=helper), patch.object(m, 'merge_wireguard_last_seen', return_value=[]), patch.object(m, 'list_vps', return_value=[]):
c = TestClient(m.app)
assert 'WGTools' not in c.get('/login').text
@@ -41,9 +41,9 @@ def test_user_is_restricted_to_assigned_interface(tmp_path):
assert c.get('/api/extended/ip-groups').status_code == 403
assert [x['name'] for x in c.get('/api/interfaces').json()['interfaces']] == ['wg1']
c.cookies.set('wgtools_interface', 'wg2')
assert c.get('/api/snapshot').status_code == 403
assert c.get('/api/extended/forwardings').status_code == 403
assert c.post('/api/clients/create', json={'name':'bad','type':'client'}).status_code == 403
assert c.get('/api/snapshot').json()['interface'] == 'wg1'
assert c.get('/api/extended/forwardings').json()['interface'] == 'wg1'
assert c.get('/').status_code == 200
c.cookies.set('wgtools_interface', 'wg1')
response = c.get('/api/snapshot')
assert response.status_code == 200
@@ -52,5 +52,16 @@ def test_user_is_restricted_to_assigned_interface(tmp_path):
set_user_access(user['id'], 'user', ['wg1'], {'wg1':['add']})
assert c.post('/api/extended/forwardings', json={'public_ip':'192.0.2.1','public_port':1234,'target_ip':'10.0.0.2','target_port':1234,'protocol':'tcp'}).status_code == 403
assert c.post('/api/clients/update', json={'name':'peer','public_key':'x'*44}).status_code == 403
c.post('/api/auth/logout')
assert c.post('/api/auth/login', json={'username':'admin','password':'password123'}).status_code == 200
server = c.get('/server')
assert server.status_code == 200
for prefix in ['setup', 'new-interface', 'server-edit']:
assert f'id="{prefix}-listen-mode"' in server.text
assert f'id="{prefix}-snat-mode"' in server.text
assert f'id="{prefix}-forward-sources"' in server.text
settings = c.get('/settings')
assert 'id="user-access-modal"' in settings.text
assert 'data-settings-tab="branding"' in settings.text
''')
subprocess.run([sys.executable, '-c', script], cwd=root, env=env, check=True, timeout=30)
+10
View File
@@ -70,6 +70,16 @@ def test_server_editor_preserves_extended_firewall_hooks(network):
assert m['_managed_hook_kind'](command, 'wg1', {}, set()) is None
def test_network_sources_allow_addresses_and_interfaces(network):
m, _ = network
groups = m['_prepare_network_sources']('wg1', '192.0.2.10, eth0')
assert groups['_wgext_network_wg1']['sources'] == ['192.0.2.10', 'eth0']
assert m['_extended_allowed'](groups, 'wg1') == {'192.0.2.10', '192.0.2.20'}
assert m['_extended_allowed'](groups, 'wg2') == set()
with pytest.raises(ValueError, match='nie ma przypisanego IPv4'):
m['_prepare_network_sources']('wg1', '192.0.2.99')
def test_migration_backup_includes_address_groups(network, tmp_path, monkeypatch):
m, _ = network
gl = m['_build_migration_archive'].__globals__
+7
View File
@@ -29,3 +29,10 @@ def test_listen_rejects_unassigned_or_invalid_inputs(helper):
for address, interface in [('192.0.2.11', 'eth0'), ('192.0.2.10', 'eth0;id'), ('bad', '')]:
with pytest.raises(ValueError):
helper['extended_listen_apply']('wg1', {'address': address, 'interface': interface})
def test_prepare_listen_uses_new_port_without_applying(helper):
config = '[Interface]\nAddress = 10.0.0.1/24\nListenPort = 51821\nPrivateKey = key\n'
result = helper['extended_listen_apply']('wg1', {'address':'192.0.2.10', 'interface':'eth0'}, text_override=config, prepare_only=True)
assert '--dport 51821' in result['content']
assert '# WGEXT-LISTEN-wg1 ' in result['content']
+3 -1
View File
@@ -9,7 +9,8 @@ from scripts import gitea_release
def test_release_creates_draft_uploads_and_publishes(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
Path('VERSION').write_text('1.2.3', encoding='utf-8')
for key, value in {'GITHUB_REF_NAME':'v1.2.3', 'GITHUB_SERVER_URL':'https://git.example', 'GITHUB_REPOSITORY':'owner/project', 'GITEA_RELEASE_TOKEN':'test-token'}.items():
Path('RELEASE_NOTES.md').write_text('Fixes network settings.', encoding='utf-8')
for key, value in {'GITHUB_REF_NAME':'v1.2.3', 'GITHUB_SERVER_URL':'https://git.example', 'GITHUB_REPOSITORY':'owner/project', 'RELEASE_TOKEN':'test-token'}.items():
monkeypatch.setenv(key, value)
calls = []
def archive(args, **kwargs):
@@ -28,6 +29,7 @@ def test_release_creates_draft_uploads_and_publishes(tmp_path, monkeypatch):
gitea_release.main()
assert [r.method for r in calls] == ['POST', 'POST', 'PATCH']
assert json.loads(calls[0].data)['draft'] is True
assert json.loads(calls[0].data)['body'] == 'Fixes network settings.'
assert b'test archive' in calls[1].data
assert json.loads(calls[2].data)['draft'] is False
+1 -1
View File
@@ -36,7 +36,7 @@ class HelpTranslationTests(unittest.TestCase):
def test_unknown_language_defaults_to_english(self):
self.assertEqual(get_help_sections('non-existent-language'), HELP['en'])
def test_version(self):
self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.0')
self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.3')
if __name__ == '__main__':
unittest.main()
+28
View File
@@ -0,0 +1,28 @@
from app.core import audit, preferences
def test_settings_are_loaded_in_batches(tmp_path, monkeypatch):
monkeypatch.setattr(preferences, 'DATABASE_PATH', str(tmp_path / 'settings.db'))
original = preferences._connect
connections = []
def connect():
connections.append(1)
return original()
monkeypatch.setattr(preferences, '_connect', connect)
assert preferences.get_preferences()['refresh_seconds'] == max(2, min(preferences.REFRESH_SECONDS, 60))
assert len(connections) == 2
connections.clear()
assert preferences.get_branding()['name'] == 'WGTools-Extended'
assert len(connections) == 2
def test_historical_connection_lookup_uses_index(tmp_path, monkeypatch):
monkeypatch.setattr(audit, 'DATABASE_PATH', str(tmp_path / 'audit.db'))
audit.init_audit_database()
with audit._connection() as conn:
plan = conn.execute(
"EXPLAIN QUERY PLAN SELECT created_at,details FROM audit_log "
"WHERE action='wireguard.client_connected' AND object=? "
"ORDER BY created_at DESC,id DESC LIMIT 1", ('wg0 · klient',)
).fetchall()
assert any('idx_audit_connection_lookup' in str(row[3]) for row in plan)
+1 -1
View File
@@ -15,7 +15,7 @@ LANGS = ('en', 'ru', 'de', 'fr', 'it', 'es', 'pl')
class CandidateTests(unittest.TestCase):
def test_versions_and_locale_fallback_contract(self):
self.assertEqual((ROOT / 'VERSION').read_text().strip(), '1.0.0')
self.assertEqual((ROOT / 'VERSION').read_text().strip(), '1.0.3')
en = json.loads((ROOT/'app/locales/en.json').read_text())
self.assertGreaterEqual(len(en), 1098)
for lang in LANGS: