2 Commits
Author SHA1 Message Date
asminme 6e7eaa9282 1.0.4 - ograniczenia IP i edycja przekierowań
Wydanie WGTools-Extended / release (push) Successful in 15s
2026-10-30 05:12:47 +01:00
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
19 changed files with 183 additions and 36 deletions

No files matched your search

+10
View File
@@ -1,5 +1,15 @@
# Changelog # Changelog
## v1.0.4
- Dodano ograniczanie dostępu do przekierowanych portów według adresów źródłowych IPv4.
- Dodano edycję przekierowań i wybór adresu klienta z listy.
## 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 ## v1.0.2
- Poprawiono wybór marki i przypisywanie uprawnień do sieci. - Poprawiono wybór marki i przypisywanie uprawnień do sieci.
+2
View File
@@ -26,6 +26,8 @@ Podczas tworzenia lub edycji sieci wybierz sposób nasłuchiwania i interfejs al
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. 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.
Przy dodawaniu lub edycji przekierowania portu można wybrać klienta z listy i ograniczyć dostęp do wskazanych adresów źródłowych IPv4. Kilka adresów należy oddzielić przecinkami; bez ograniczenia port jest dostępny ze wszystkich adresów.
## Aktualizacja ## Aktualizacja
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. 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.
+1 -1
View File
@@ -1 +1 @@
Fixes bugs and improves network configuration, user permissions and branding. Adds source IP restrictions, editing for port forwarding, and a client selector.
+1 -1
View File
@@ -1 +1 @@
1.0.2 1.0.4
+1
View File
@@ -98,6 +98,7 @@ def init_audit_database() -> None:
details TEXT NOT NULL DEFAULT '' 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_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 ( CREATE TABLE IF NOT EXISTS audit_wg_connection_state (
interface TEXT NOT NULL, interface TEXT NOT NULL,
public_key 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 '{}'") 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() init_database()
with _connect() as conn: with _connect() as conn:
row = conn.execute("SELECT role,interfaces,permissions FROM user_access WHERE user_id=?", (int(user_id),)).fetchone() row = conn.execute("SELECT role,interfaces,permissions FROM user_access WHERE user_id=?", (int(user_id),)).fetchone()
+2 -1
View File
@@ -45,6 +45,7 @@ ALLOWED_ACTIONS = {
"extended_ip_groups_set", "extended_ip_groups_set",
"extended_forward_get", "extended_forward_get",
"extended_forward_add", "extended_forward_add",
"extended_forward_update",
"extended_forward_delete", "extended_forward_delete",
"route_create", "route_create",
"route_update", "route_update",
@@ -87,7 +88,7 @@ def run_helper(action: str, payload: dict[str, Any] | None = None, *, interface:
# helper enough time to finish its transactional rollback/commit path # helper enough time to finish its transactional rollback/commit path
# instead of killing it mid-update. # instead of killing it mid-update.
timeout = 120 timeout = 120
elif action in {"raw_config_apply", "server_settings_apply", "extended_snat_apply", "extended_listen_apply", "extended_forward_add", "extended_forward_delete", "route_create", "route_update", "route_delete", "access_rule_create", "access_rule_update", "access_rule_delete"}: elif action in {"raw_config_apply", "server_settings_apply", "extended_snat_apply", "extended_listen_apply", "extended_forward_add", "extended_forward_update", "extended_forward_delete", "route_create", "route_update", "route_delete", "access_rule_create", "access_rule_update", "access_rule_delete"}:
timeout = 90 timeout = 90
elif action == "migration_backup_create": elif action == "migration_backup_create":
timeout = 45 timeout = 45
+14 -6
View File
@@ -13,9 +13,8 @@ DEFAULT_BACKUP_RETENTION = 20
def get_branding() -> dict[str, Any]: def get_branding() -> dict[str, Any]:
return {"name": _get("brand_name", "WGTools-Extended"), values = _get_many({"brand_name": "WGTools-Extended", "brand_color": "#8f1f27", "brand_logo": ""})
"color": _get("brand_color", "#8f1f27"), return {"name": values["brand_name"], "color": values["brand_color"], "logo": values["brand_logo"]}
"logo": _get("brand_logo", "")}
def update_branding(name: str, color: str, logo: str) -> dict[str, Any]: 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 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: def _set(key: str, value: str) -> None:
init_preferences() init_preferences()
with _connect() as conn: with _connect() as conn:
@@ -81,9 +88,10 @@ def _set(key: str, value: str) -> None:
def get_preferences() -> dict[str, Any]: def get_preferences() -> dict[str, Any]:
refresh = int(_get("refresh_seconds", str(REFRESH_SECONDS))) values = _get_many({"refresh_seconds": str(REFRESH_SECONDS), "online_threshold_seconds": str(ONLINE_THRESHOLD_SECONDS), "backup_retention": str(DEFAULT_BACKUP_RETENTION)})
threshold = int(_get("online_threshold_seconds", str(ONLINE_THRESHOLD_SECONDS))) refresh = int(values["refresh_seconds"])
retention = int(_get("backup_retention", str(DEFAULT_BACKUP_RETENTION))) threshold = int(values["online_threshold_seconds"])
retention = int(values["backup_retention"])
return { return {
"refresh_seconds": max(2, min(refresh, 60)), "refresh_seconds": max(2, min(refresh, 60)),
"online_threshold_seconds": max(30, min(threshold, 3600)), "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() VERSION = Path(__file__).resolve().parents[2].joinpath("VERSION").read_text().strip()
WG_INTERFACE = os.getenv("WGTOOLS_INTERFACE", "wg0") WG_INTERFACE = os.getenv("WGTOOLS_INTERFACE", "wg0")
HELPER_PATH = os.getenv("WGTOOLS_HELPER", "/usr/local/libexec/wgtools-helper") 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")) ONLINE_THRESHOLD_SECONDS = int(os.getenv("WGTOOLS_ONLINE_THRESHOLD_SECONDS", "180"))
DATABASE_PATH = os.getenv("WGTOOLS_DATABASE", "/var/lib/wgtools/wgtools.db") 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") SESSION_KEY_FILE = os.getenv("WGTOOLS_SESSION_KEY_FILE", "/var/lib/wgtools/session.key")
+22 -6
View File
@@ -436,7 +436,7 @@ class NodeSettingsRequest(BaseModel):
class AppSettingsRequest(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) online_threshold_seconds: int = Field(default=180, ge=30, le=3600)
backup_retention: int = Field(default=20, ge=1, le=200) backup_retention: int = Field(default=20, ge=1, le=200)
@@ -476,6 +476,12 @@ class ExtendedForwardRequest(BaseModel):
target_ip: str = Field(max_length=15) target_ip: str = Field(max_length=15)
target_port: int = Field(ge=1, le=65535) target_port: int = Field(ge=1, le=65535)
protocol: str = Field(max_length=4) protocol: str = Field(max_length=4)
restrict_sources: bool = False
allowed_sources: list[str] = Field(default_factory=list, max_length=32)
class ExtendedForwardUpdateRequest(ExtendedForwardRequest):
id: str = Field(pattern=r"^[0-9a-f]{16}$")
class ExtendedForwardDeleteRequest(BaseModel): class ExtendedForwardDeleteRequest(BaseModel):
@@ -522,7 +528,7 @@ def is_internal_interface(name: str) -> bool:
def request_interface(request: Request) -> str: def request_interface(request: Request) -> str:
current = getattr(request.state, "current_user", None) 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) 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() value = (request.cookies.get("wgtools_interface") or default_iface).strip()
if access["role"] == "user" and access["interfaces"] and value not in access["interfaces"]: if access["role"] == "user" and access["interfaces"] and value not in access["interfaces"]:
@@ -580,7 +586,7 @@ def render(request: Request, template: str, page: str, title_key: str) -> HTMLRe
"language": language, "language": language,
"messages_json": messages_json, "messages_json": messages_json,
"tr": tr, "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 [], "help_sections": get_help_sections(language) if request.state.access['role'] == 'admin' else [],
}, },
headers={"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet"}, headers={"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet"},
@@ -649,9 +655,9 @@ async def require_authentication(request: Request, call_next):
if path in PUBLIC_PATHS or path.startswith(PUBLIC_PREFIXES): if path in PUBLIC_PATHS or path.startswith(PUBLIC_PREFIXES):
return await call_next(request) return await call_next(request)
users_exist = user_count() > 0
user_id = request.session.get("user_id") user_id = request.session.get("user_id")
current = get_user(int(user_id)) if user_id else None 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: if user_id and not current:
request.session.clear() request.session.clear()
if current: if current:
@@ -682,10 +688,10 @@ async def require_authentication(request: Request, call_next):
return RedirectResponse(url=f"{app_url(request, '/login')}?next={next_path}", status_code=303) return RedirectResponse(url=f"{app_url(request, '/login')}?next={next_path}", status_code=303)
request.state.current_user = current 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 request.state.access = access
if access["role"] != "admin": if access["role"] != "admin":
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"} 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/update", "/api/extended/forwardings/delete"}
if path not in allowed or (path == "/api/app-settings" and request.method != "GET"): 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ń"}) 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": if path.startswith("/api/clients/") or path.startswith("/api/extended/forwardings") or path == "/api/snapshot":
@@ -1769,6 +1775,16 @@ def api_extended_forward_add(payload: ExtendedForwardRequest, request: Request):
return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)}) return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)})
@app.post("/api/extended/forwardings/update")
def api_extended_forward_update(payload: ExtendedForwardUpdateRequest, request: Request):
try:
result = run_helper("extended_forward_update", payload.model_dump(), interface=request_interface(request))
audit_action(request, "network.forward_updated", object=request_interface(request), result="saved", details=payload.model_dump())
return result
except HelperError as exc:
return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)})
@app.post("/api/extended/forwardings/delete") @app.post("/api/extended/forwardings/delete")
def api_extended_forward_delete(payload: ExtendedForwardDeleteRequest, request: Request): def api_extended_forward_delete(payload: ExtendedForwardDeleteRequest, request: Request):
try: try:
+20 -8
View File
@@ -11,7 +11,7 @@
return nativeFetch(input, init); return nativeFetch(input, init);
}; };
const page = document.body.dataset.page; 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'); const threshold = Number(document.body.dataset.onlineThreshold || '180');
let snapshot = null; let snapshot = null;
let interfacesData = {interfaces:[], suggested:null}; let interfacesData = {interfaces:[], suggested:null};
@@ -1093,9 +1093,13 @@
loadGroups(); loadGroups();
} }
if(page==='clients' && $('extended-forward-form')){ if(page==='clients' && $('extended-forward-form')){
const loadForwards=async()=>{const r=await fetch(appUrl('/api/extended/forwardings'));const d=await r.json();if(!r.ok)throw new Error(d.error);$('extended-forward-public').innerHTML=(d.addresses||[]).map(ip=>`<option value="${esc(ip)}">${esc(ip)}</option>`).join('');$('extended-forward-list').innerHTML=(d.forwards||[]).map(f=>`<div class="group-row"><span>${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}</span><button class="btn small danger" type="button" data-ext-forward-delete="${esc(f.id)}">Usuń</button></div>`).join('')||'<p>Brak przekierowań.</p>';}; let forwards=[], editing='';
$('extended-forward-form').addEventListener('submit',async e=>{e.preventDefault();try{const r=await fetch(appUrl('/api/extended/forwardings'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_ip:$('extended-forward-public').value,public_port:Number($('extended-forward-public-port').value),target_ip:$('extended-forward-target').value.trim(),target_port:Number($('extended-forward-target-port').value),protocol:$('extended-forward-protocol').value})});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadForwards();operationStatus('extended-forward-status','Dodano przekierowanie.','success');}catch(err){operationStatus('extended-forward-status',err.message,'error');}}); const reset=()=>{editing='';$('extended-forward-form').reset();$('extended-forward-restrict').checked=false;syncSources();$('extended-forward-submit').textContent='Dodaj przekierowanie';$('extended-forward-cancel').hidden=true;};
$('extended-forward-list').addEventListener('click',async e=>{const b=e.target.closest('[data-ext-forward-delete]');if(!b||!confirm('Usunąć przekierowanie?'))return;try{const r=await fetch(appUrl('/api/extended/forwardings/delete'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:b.dataset.extForwardDelete})});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadForwards();}catch(err){operationStatus('extended-forward-status',err.message,'error');}}); const syncSources=()=>{const enabled=$('extended-forward-restrict').checked;$('extended-forward-sources-wrap').hidden=!enabled;$('extended-forward-sources').required=enabled;};
const loadForwards=async()=>{const r=await fetch(appUrl('/api/extended/forwardings'));const d=await r.json();if(!r.ok)throw new Error(d.error);forwards=d.forwards||[];const current=$('extended-forward-public').value;$('extended-forward-public').innerHTML=(d.addresses||[]).map(ip=>`<option value="${esc(ip)}">${esc(ip)}</option>`).join('');if((d.addresses||[]).includes(current))$('extended-forward-public').value=current;$('extended-forward-list').innerHTML=forwards.map(f=>`<div class="group-row"><div><span>${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}</span><p>${f.allowed_sources?.length?'Dozwolone adresy: '+esc(f.allowed_sources.join(', ')):'Dostęp ze wszystkich adresów'}</p></div><div class="action-row"><button class="btn small" type="button" data-ext-forward-edit="${esc(f.id)}">Edytuj</button><button class="btn small danger" type="button" data-ext-forward-delete="${esc(f.id)}">Usuń</button></div></div>`).join('')||'<p>Brak przekierowań.</p>';};
$('extended-forward-restrict').addEventListener('change',syncSources);$('extended-forward-cancel').addEventListener('click',reset);
$('extended-forward-form').addEventListener('submit',async e=>{e.preventDefault();const restricted=$('extended-forward-restrict').checked;const payload={public_ip:$('extended-forward-public').value,public_port:Number($('extended-forward-public-port').value),target_ip:$('extended-forward-target').value,target_port:Number($('extended-forward-target-port').value),protocol:$('extended-forward-protocol').value,restrict_sources:restricted,allowed_sources:restricted?$('extended-forward-sources').value.split(',').map(x=>x.trim()).filter(Boolean):[]};if(editing)payload.id=editing;const button=$('extended-forward-submit');button.disabled=true;try{const r=await fetch(appUrl(editing?'/api/extended/forwardings/update':'/api/extended/forwardings'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error);reset();await loadForwards();operationStatus('extended-forward-status','Zapisano przekierowanie.','success');}catch(err){operationStatus('extended-forward-status',err.message,'error');}finally{button.disabled=false;}});
$('extended-forward-list').addEventListener('click',async e=>{const edit=e.target.closest('[data-ext-forward-edit]'),del=e.target.closest('[data-ext-forward-delete]');if(edit){const f=forwards.find(x=>x.id===edit.dataset.extForwardEdit);if(!f)return;editing=f.id;$('extended-forward-public').value=f.public_ip;$('extended-forward-public-port').value=f.public_port;$('extended-forward-target').value=f.target_ip;$('extended-forward-target-port').value=f.target_port;$('extended-forward-protocol').value=f.protocol;$('extended-forward-restrict').checked=Boolean(f.allowed_sources?.length);$('extended-forward-sources').value=(f.allowed_sources||[]).join(', ');syncSources();$('extended-forward-submit').textContent='Zapisz zmiany';$('extended-forward-cancel').hidden=false;operationStatus('extended-forward-status','Edytujesz przekierowanie.','working');$('extended-forward-form').scrollIntoView({behavior:'smooth',block:'center'});return;}if(!del||!confirm('Usunąć przekierowanie?'))return;try{const r=await fetch(appUrl('/api/extended/forwardings/delete'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:del.dataset.extForwardDelete})});const d=await r.json();if(!r.ok)throw new Error(d.error);if(editing===del.dataset.extForwardDelete)reset();await loadForwards();}catch(err){operationStatus('extended-forward-status',err.message,'error');}});
loadForwards().catch(err=>operationStatus('extended-forward-status',err.message,'error')); loadForwards().catch(err=>operationStatus('extended-forward-status',err.message,'error'));
} }
if(page==='server' && $('extended-listen-form')){ if(page==='server' && $('extended-listen-form')){
@@ -1154,6 +1158,8 @@
} }
function renderClients(d){ function renderClients(d){
const peers=d.peers||[]; const body=$('client-body'); const add=$('add-client-button'); const manage=$('manage-groups-button'); const peers=d.peers||[]; const body=$('client-body'); const add=$('add-client-button'); const manage=$('manage-groups-button');
const targets=$('extended-forward-target');if(targets){const selected=targets.value;const valid=peers.map(p=>({ip:String(p.vpn_address||'').split('/')[0],name:p.name||'Klient'})).filter(p=>/^\d{1,3}(?:\.\d{1,3}){3}$/.test(p.ip));targets.innerHTML='<option value="">Wybierz klienta</option>'+valid.map(p=>`<option value="${esc(p.ip)}">${esc(p.name)} · ${esc(p.ip)}</option>`).join('');if(valid.some(p=>p.ip===selected))targets.value=selected;}
if(add)add.disabled=!d.wireguard?.config_exists; if(manage)manage.disabled=!d.wireguard?.config_exists; syncClientQuickSearchClear(); if(add)add.disabled=!d.wireguard?.config_exists; if(manage)manage.disabled=!d.wireguard?.config_exists; syncClientQuickSearchClear();
if(!peers.length){body.innerHTML=`<tr><td colspan="9" class="empty">${esc(t('clients.no_peers','No peers found'))}</td></tr>`;return;} if(!peers.length){body.innerHTML=`<tr><td colspan="9" class="empty">${esc(t('clients.no_peers','No peers found'))}</td></tr>`;return;}
const visible=peers.map((p,index)=>({p,index})).filter(item=>clientMatchesQuickSearch(item.p)); const visible=peers.map((p,index)=>({p,index})).filter(item=>clientMatchesQuickSearch(item.p));
@@ -2095,6 +2101,7 @@
auditAutoRefreshTimer=setInterval(()=>{ auditAutoRefreshTimer=setInterval(()=>{
const modal=$('audit-modal'); const modal=$('audit-modal');
if(!modal||modal.hidden){stopAuditAutoRefresh();return;} if(!modal||modal.hidden){stopAuditAutoRefresh();return;}
if(document.hidden)return;
loadAudit({showLoading:false}); loadAudit({showLoading:false});
},interval); },interval);
} }
@@ -2993,14 +3000,19 @@
if(page==='dashboard'){ if(page==='dashboard'){
loadMetricsHistory(); loadMetricsHistory();
if(document.body.dataset.role==='admin')loadDashboardDiagnostics(); if(document.body.dataset.role==='admin')loadDashboardDiagnostics();
historyTimer=setInterval(loadMetricsHistory,60*1000); historyTimer=setInterval(()=>{if(!document.hidden)loadMetricsHistory();},60*1000);
if(document.body.dataset.role==='admin')dashboardDiagnosticsTimer=setInterval(loadDashboardDiagnostics,60*1000); if(document.body.dataset.role==='admin')dashboardDiagnosticsTimer=setInterval(()=>{if(!document.hidden)loadDashboardDiagnostics();},60*1000);
} }
if(page==='server'){ if(page==='server'){
loadServerDiagnostics(); 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(); boot();
})(); })();
+5 -2
View File
@@ -17,11 +17,14 @@
<div class="setup-grid"> <div class="setup-grid">
<label><span>Publiczny adres IPv4</span><select id="extended-forward-public" required></select></label> <label><span>Publiczny adres IPv4</span><select id="extended-forward-public" required></select></label>
<label><span>Port publiczny</span><input id="extended-forward-public-port" type="number" min="1" max="65535" required></label> <label><span>Port publiczny</span><input id="extended-forward-public-port" type="number" min="1" max="65535" required></label>
<label><span>Adres IPv4 klienta</span><input id="extended-forward-target" placeholder="10.0.2.2" maxlength="15" required></label> <label><span>Klient i jego adres IPv4</span><select id="extended-forward-target" required><option value="">Wybierz klienta</option></select></label>
<label><span>Port klienta</span><input id="extended-forward-target-port" type="number" min="1" max="65535" required></label> <label><span>Port klienta</span><input id="extended-forward-target-port" type="number" min="1" max="65535" required></label>
<label><span>Protokół</span><select id="extended-forward-protocol"><option value="tcp">TCP</option><option value="udp">UDP</option><option value="both">TCP i UDP</option></select></label> <label><span>Protokół</span><select id="extended-forward-protocol"><option value="tcp">TCP</option><option value="udp">UDP</option><option value="both">TCP i UDP</option></select></label>
</div> </div>
<button class="btn primary" type="submit">Dodaj przekierowanie</button> <label class="check-label"><input id="extended-forward-restrict" type="checkbox"><span>Ogranicz dostęp do wybranych adresów IP</span></label>
<label id="extended-forward-sources-wrap" hidden><span>Dozwolone adresy IPv4, oddzielone przecinkami</span><input id="extended-forward-sources" placeholder="89.144.32.110, 89.144.32.172"><small>Pozostałe adresy nie uzyskają dostępu do tego przekierowania.</small></label>
<button class="btn primary" type="submit" id="extended-forward-submit">Dodaj przekierowanie</button>
<button class="btn" type="button" id="extended-forward-cancel" hidden>Anuluj edycję</button>
<div id="extended-forward-status" class="operation-status" hidden></div> <div id="extended-forward-status" class="operation-status" hidden></div>
</form> </form>
<div id="extended-forward-list" class="settings-form-pad"></div> <div id="extended-forward-list" class="settings-form-pad"></div>
+1 -1
View File
@@ -78,7 +78,7 @@ if [[ ! -f /etc/wgtools/wgtools.env ]]; then
WGTOOLS_INTERFACE=$WG_INTERFACE WGTOOLS_INTERFACE=$WG_INTERFACE
WGTOOLS_PORT=$WEB_PORT WGTOOLS_PORT=$WEB_PORT
WGTOOLS_HELPER=/usr/local/libexec/wgtools-helper WGTOOLS_HELPER=/usr/local/libexec/wgtools-helper
WGTOOLS_REFRESH_SECONDS=5 WGTOOLS_REFRESH_SECONDS=10
WGTOOLS_ONLINE_THRESHOLD_SECONDS=180 WGTOOLS_ONLINE_THRESHOLD_SECONDS=180
WGTOOLS_DATABASE=/var/lib/wgtools/wgtools.db WGTOOLS_DATABASE=/var/lib/wgtools/wgtools.db
WGTOOLS_SESSION_KEY_FILE=/var/lib/wgtools/session.key WGTOOLS_SESSION_KEY_FILE=/var/lib/wgtools/session.key
+43 -6
View File
@@ -31,6 +31,7 @@ ALLOWED_ACTIONS.update({"extended_snat_get", "extended_snat_apply"})
ALLOWED_ACTIONS.add("extended_host_ips") ALLOWED_ACTIONS.add("extended_host_ips")
ALLOWED_ACTIONS.update({"extended_listen_get", "extended_listen_apply"}) 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({"extended_ip_groups_get", "extended_ip_groups_set", "extended_forward_get", "extended_forward_add", "extended_forward_delete"})
ALLOWED_ACTIONS.add("extended_forward_update")
ALLOWED_ACTIONS.update({"update_file_schedule", "update_file_apply"}) ALLOWED_ACTIONS.update({"update_file_schedule", "update_file_apply"})
ALLOWED_IFACE_RE = re.compile(r"^[A-Za-z0-9_.-]{1,15}$") ALLOWED_IFACE_RE = re.compile(r"^[A-Za-z0-9_.-]{1,15}$")
INTERNAL_INTERFACE_PREFIXES = ("wgrly", "wgnode") INTERNAL_INTERFACE_PREFIXES = ("wgrly", "wgnode")
@@ -4449,6 +4450,10 @@ def _extended_forwards(iface: str) -> list[dict[str, Any]]:
raise ValueError() raise ValueError()
if row["protocol"] not in {"tcp", "udp", "both"} or not ALLOWED_IFACE_RE.fullmatch(row["device"]) or row["device"].startswith('-'): if row["protocol"] not in {"tcp", "udp", "both"} or not ALLOWED_IFACE_RE.fullmatch(row["device"]) or row["device"].startswith('-'):
raise ValueError() raise ValueError()
sources = row.get("allowed_sources", [])
if not isinstance(sources, list) or len(sources) > 32:
raise ValueError()
row["allowed_sources"] = sorted({str(ipaddress.IPv4Address(value)) for value in sources})
except (KeyError, ValueError, TypeError) as exc: except (KeyError, ValueError, TypeError) as exc:
raise ValueError(f"Nieprawidłowy wpis przekierowania w {iface}") from exc raise ValueError(f"Nieprawidłowy wpis przekierowania w {iface}") from exc
result.append(row) result.append(row)
@@ -4500,6 +4505,9 @@ def extended_forward_get(iface: str) -> dict[str, Any]:
def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str, Any]: def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str, Any]:
complexity = sum((len(row.get('allowed_sources', [])) or 1) * (2 if row['protocol'] == 'both' else 1) for row in rows)
if complexity > 100:
raise ValueError("Zbyt wiele adresów źródłowych w przekierowaniach tej sieci")
prefix, section, suffix = _interface_section_parts(read_config_text(iface)) prefix, section, suffix = _interface_section_parts(read_config_text(iface))
marker = f"wgext-forward-{iface}" marker = f"wgext-forward-{iface}"
section = [line for line in section if not (line.strip().startswith("# WGEXT-FORWARD ") or (re.match(r"\s*Post(?:Up|Down)\s*=", line, re.I) and f"--comment {marker}-" in line))] section = [line for line in section if not (line.strip().startswith("# WGEXT-FORWARD ") or (re.match(r"\s*Post(?:Up|Down)\s*=", line, re.I) and f"--comment {marker}-" in line))]
@@ -4510,9 +4518,19 @@ def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str
for proto in (["tcp", "udp"] if row["protocol"] == "both" else [row["protocol"]]): for proto in (["tcp", "udp"] if row["protocol"] == "both" else [row["protocol"]]):
tag = f"{marker}-{row['id']}-{proto}" tag = f"{marker}-{row['id']}-{proto}"
nat = f"-i {row['device']} -d {row['public_ip']} -p {proto} --dport {row['public_port']} -m comment --comment {tag}-nat -j DNAT --to-destination {row['target_ip']}:{row['target_port']}" nat = f"-i {row['device']} -d {row['public_ip']} -p {proto} --dport {row['public_port']} -m comment --comment {tag}-nat -j DNAT --to-destination {row['target_ip']}:{row['target_port']}"
forward = f"-i {row['device']} -o {iface} -d {row['target_ip']} -p {proto} --dport {row['target_port']} -m comment --comment {tag}-in -j ACCEPT" forward_match = f"-i {row['device']} -o {iface} -d {row['target_ip']} -p {proto} --dport {row['target_port']} -m conntrack --ctorigdst {row['public_ip']} --ctorigdstport {row['public_port']}"
reply = f"-i {iface} -o {row['device']} -s {row['target_ip']} -p {proto} --sport {row['target_port']} -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment {tag}-out -j ACCEPT" reply = f"-i {iface} -o {row['device']} -s {row['target_ip']} -p {proto} --sport {row['target_port']} -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment {tag}-out -j ACCEPT"
for table, chain, rule in [(' -t nat', 'PREROUTING', nat), ('', 'FORWARD', forward), ('', 'FORWARD', reply)]: rules = [(' -t nat', 'PREROUTING', nat), ('', 'FORWARD', reply)]
sources = row.get('allowed_sources', [])
if sources:
# Match the original public tuple even for connections created
# before an edit changed the destination client.
deny_match = f"-i {row['device']} -o {iface} -p {proto} -m conntrack --ctorigdst {row['public_ip']} --ctorigdstport {row['public_port']}"
rules.append(('', 'FORWARD', f"{deny_match} -m comment --comment {tag}-deny -j DROP"))
for index, source in enumerate(sources or ['']):
source_match = f" -s {source}" if source else ''
rules.append(('', 'FORWARD', f"{forward_match}{source_match} -m comment --comment {tag}-in{index} -j ACCEPT"))
for table, chain, rule in rules:
up.append(f"iptables -w{table} -I {chain} 1 {rule}") up.append(f"iptables -w{table} -I {chain} 1 {rule}")
down.append(f"iptables -w{table} -D {chain} {rule} 2>/dev/null || true") down.append(f"iptables -w{table} -D {chain} {rule} 2>/dev/null || true")
if up: if up:
@@ -4521,7 +4539,7 @@ def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str
return raw_config_apply(iface, {"content": "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"}) return raw_config_apply(iface, {"content": "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"})
def extended_forward_add(iface: str, payload: dict[str, Any]) -> dict[str, Any]: def extended_forward_add(iface: str, payload: dict[str, Any], *, update_id: str = '') -> dict[str, Any]:
require_valid_iface(iface) require_valid_iface(iface)
try: try:
public_ip = str(ipaddress.IPv4Address(payload.get("public_ip"))) public_ip = str(ipaddress.IPv4Address(payload.get("public_ip")))
@@ -4530,6 +4548,15 @@ def extended_forward_add(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
except (ValueError, TypeError) as exc: except (ValueError, TypeError) as exc:
raise ValueError("Nieprawidłowy adres lub port") from exc raise ValueError("Nieprawidłowy adres lub port") from exc
protocol = str(payload.get("protocol") or "") protocol = str(payload.get("protocol") or "")
sources = payload.get('allowed_sources') or []
if not isinstance(sources, list) or len(sources) > 32:
raise ValueError("Można podać maksymalnie 32 adresy źródłowe")
try:
sources = sorted({str(ipaddress.IPv4Address(value)) for value in sources})
except (ValueError, TypeError) as exc:
raise ValueError("Podaj poprawne adresy źródłowe IPv4") from exc
if bool(payload.get('restrict_sources')) != bool(sources):
raise ValueError("Podaj co najmniej jeden adres IPv4 albo wyłącz ograniczenie")
if protocol not in {"tcp", "udp", "both"} or not (1 <= public_port <= 65535 and 1 <= target_port <= 65535): if protocol not in {"tcp", "udp", "both"} or not (1 <= public_port <= 65535 and 1 <= target_port <= 65535):
raise ValueError("Nieprawidłowy protokół lub port") raise ValueError("Nieprawidłowy protokół lub port")
if public_ip not in _extended_allowed(_extended_groups(), iface): if public_ip not in _extended_allowed(_extended_groups(), iface):
@@ -4549,14 +4576,18 @@ def extended_forward_add(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
if "udp" in protocols and (other_cfg.get("interface") or {}).get("listen_port") == public_port: if "udp" in protocols and (other_cfg.get("interface") or {}).get("listen_port") == public_port:
raise ValueError("Ten port UDP jest używany przez WireGuard") raise ValueError("Ten port UDP jest używany przez WireGuard")
for row in _extended_forwards(other): for row in _extended_forwards(other):
if other == iface and row['id'] == update_id:
continue
existing = {"tcp", "udp"} if row["protocol"] == "both" else {row["protocol"]} existing = {"tcp", "udp"} if row["protocol"] == "both" else {row["protocol"]}
if row["public_ip"] == public_ip and row["public_port"] == public_port and protocols & existing: if row["public_ip"] == public_ip and row["public_port"] == public_port and protocols & existing:
raise ValueError("Ten adres, port i protokół są już używane przez inne przekierowanie") raise ValueError("Ten adres, port i protokół są już używane przez inne przekierowanie")
rows = _extended_forwards(iface) rows = _extended_forwards(iface)
if len(rows) >= 20: if update_id and not any(row['id'] == update_id for row in rows):
raise ValueError("Nie znaleziono przekierowania")
if not update_id and len(rows) >= 20:
raise ValueError("Osiągnięto limit przekierowań w tej sieci") raise ValueError("Osiągnięto limit przekierowań w tej sieci")
row = {"id": secrets.token_hex(8), "public_ip": public_ip, "public_port": public_port, "target_ip": target_ip, "target_port": target_port, "protocol": protocol, "device": device} row = {"id": update_id or secrets.token_hex(8), "public_ip": public_ip, "public_port": public_port, "target_ip": target_ip, "target_port": target_port, "protocol": protocol, "device": device, "allowed_sources": sources}
result = _extended_write_forwards(iface, [*rows, row]) result = _extended_write_forwards(iface, [*(item for item in rows if item['id'] != update_id), row])
return {**result, "forward": row} return {**result, "forward": row}
@@ -6734,6 +6765,12 @@ def main() -> int:
elif action == "extended_forward_add": elif action == "extended_forward_add":
payload = read_json_stdin() payload = read_json_stdin()
result = locked_call(lambda: extended_forward_add(iface, payload)) result = locked_call(lambda: extended_forward_add(iface, payload))
elif action == "extended_forward_update":
payload = read_json_stdin()
identifier = str(payload.get('id') or '')
if not re.fullmatch(r'[0-9a-f]{16}', identifier):
raise ValueError("Nieprawidłowy identyfikator przekierowania")
result = locked_call(lambda: extended_forward_add(iface, payload, update_id=identifier))
elif action == "extended_forward_delete": elif action == "extended_forward_delete":
payload = read_json_stdin() payload = read_json_stdin()
result = locked_call(lambda: extended_forward_delete(iface, payload)) result = locked_call(lambda: extended_forward_delete(iface, payload))
+1
View File
@@ -51,6 +51,7 @@ def test_user_is_restricted_to_assigned_interface(tmp_path):
assert c.post('/api/clients/create', json={'name':'bad','type':'site_to_site','remote_networks':['10.1.0.0/16']}).status_code == 403 assert c.post('/api/clients/create', json={'name':'bad','type':'site_to_site','remote_networks':['10.1.0.0/16']}).status_code == 403
set_user_access(user['id'], 'user', ['wg1'], {'wg1':['add']}) 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/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/extended/forwardings/update', json={'id':'0123456789abcdef','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 assert c.post('/api/clients/update', json={'name':'peer','public_key':'x'*44}).status_code == 403
c.post('/api/auth/logout') c.post('/api/auth/logout')
assert c.post('/api/auth/login', json={'username':'admin','password':'password123'}).status_code == 200 assert c.post('/api/auth/login', json={'username':'admin','password':'password123'}).status_code == 200
+27
View File
@@ -55,6 +55,33 @@ def test_rejects_foreign_target_and_wireguard_port(network):
m['extended_forward_add']('wg1', {**forward,'target_ip':'10.0.1.2','public_port':51822,'protocol':'udp'}) m['extended_forward_add']('wg1', {**forward,'target_ip':'10.0.1.2','public_port':51822,'protocol':'udp'})
def test_forward_restricts_sources_and_can_be_edited(network):
m, configs = network
m['extended_ip_groups_set']({'name':'shared','addresses':['192.0.2.10'],'interfaces':['wg1']})
payload = {'public_ip':'192.0.2.10','public_port':25565,'target_ip':'10.0.1.2','target_port':25565,'protocol':'both',
'restrict_sources': True, 'allowed_sources':['89.144.32.110','89.144.32.172']}
row = m['extended_forward_add']('wg1', payload)['forward']
config = configs['wg1']
assert '--ctorigdst 192.0.2.10 --ctorigdstport 25565' in config
assert '-s 89.144.32.110' in config and '-s 89.144.32.172' in config
post_up = next(line for line in config.splitlines() if line.startswith('PostUp ='))
assert post_up.index('-tcp-deny -j DROP') < post_up.index('-tcp-in0 -j ACCEPT')
assert post_up.index('-udp-deny -j DROP') < post_up.index('-udp-in0 -j ACCEPT')
updated = m['extended_forward_add']('wg1', {**payload, 'restrict_sources':False, 'allowed_sources':[]}, update_id=row['id'])['forward']
assert updated['id'] == row['id']
assert len(m['extended_forward_get']('wg1')['forwards']) == 1
assert '-tcp-deny -j DROP' not in configs['wg1']
def test_forward_rejects_invalid_and_empty_source_lists(network):
m, _ = network
m['extended_ip_groups_set']({'name':'shared','addresses':['192.0.2.10'],'interfaces':['wg1']})
payload = {'public_ip':'192.0.2.10','public_port':1234,'target_ip':'10.0.1.2','target_port':1234,'protocol':'tcp','restrict_sources': True}
for sources in ([], ['192.0.2.1/24'], ['1.2.3.4;id']):
with pytest.raises(ValueError):
m['extended_forward_add']('wg1', {**payload, 'allowed_sources': sources})
def test_wireguard_dump_accepts_disabled_keepalive(network, monkeypatch): def test_wireguard_dump_accepts_disabled_keepalive(network, monkeypatch):
m, _ = network m, _ = network
gl = m['wg_dump'].__globals__ gl = m['wg_dump'].__globals__
+1 -1
View File
@@ -36,7 +36,7 @@ class HelpTranslationTests(unittest.TestCase):
def test_unknown_language_defaults_to_english(self): def test_unknown_language_defaults_to_english(self):
self.assertEqual(get_help_sections('non-existent-language'), HELP['en']) self.assertEqual(get_help_sections('non-existent-language'), HELP['en'])
def test_version(self): def test_version(self):
self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.2') self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.4')
if __name__ == '__main__': if __name__ == '__main__':
unittest.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): class CandidateTests(unittest.TestCase):
def test_versions_and_locale_fallback_contract(self): def test_versions_and_locale_fallback_contract(self):
self.assertEqual((ROOT / 'VERSION').read_text().strip(), '1.0.2') self.assertEqual((ROOT / 'VERSION').read_text().strip(), '1.0.4')
en = json.loads((ROOT/'app/locales/en.json').read_text()) en = json.loads((ROOT/'app/locales/en.json').read_text())
self.assertGreaterEqual(len(en), 1098) self.assertGreaterEqual(len(en), 1098)
for lang in LANGS: for lang in LANGS: