mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-08-25 12:27:13 +00:00
feat(amneziawg): add native AmneziaWG protocol support (#6105)
* feat(amneziawg): add native AmneziaWG protocol backend AmneziaWG (WireGuard plus DPI-resistant obfuscation) needs no Docker here — it runs as a genuine kernel interface via awg-quick/awg, managed the same way internal/mtproto manages mtg: one Inbound row is one desired Instance, and a Manager reconciles running interfaces toward the database every 10s (internal/web/job/amneziawg_job.go) plus immediately after a client edit (applyLocalAmneziaWG). Clients reuse model.Client verbatim (the same PrivateKey/PublicKey/ PreSharedKey/AllowedIPs fields WireGuard already uses), so bulk operations, the QR/share-link modal and subscriptions come from the shared inbound infrastructure instead of a parallel implementation. internal/amneziawg owns the obfuscation param generator/validator (ported from coinman-dev/3ax-ui, upgraded to AmneziaWG 2.0's S3/S4 padding and I1 signature packet) and the exec wrapper around awg-quick/awg, with fingerprint-based reconcile (noop / reload-via- syncconf / full restart) mirroring mtproto.Manager so a same-protocol edit doesn't force an unnecessary interface bounce that would drop every peer's connection. Frontend and install.sh's DKMS/awg-tools setup are tracked separately; this is backend-only. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(amneziawg): add frontend support and fix a Go->Zod generator gap Wires the amneziawg protocol through the panel UI the same way every other protocol is registered: a Zod settings schema (nested {server, clients}, matching the Go JSON exactly), the protocol enum, the inbound-form's per-protocol fields component and its tab-visibility allowlist, the default-settings factory, the client schema dispatcher, and the sniffing-capability exclusion (no Xray inbound exists for amneziawg, same as mtproto). Client key/allowedIPs fields are reused rather than duplicated: since AmneziaWG clients are wire-identical to WireGuard clients (same model.Client fields), ClientFormModal renders one shared field block for both, switching only the visible label by which protocol is active. The private-key input also gets a live public-key sync via a new useEffect, because unlike WireGuard's Xray-native inbound (which re-derives its public key at runtime and never stores one), AmneziaWG's server.publicKey is a real persisted field the Go backend reads directly — free-typing a new private key without this would silently save a mismatched keypair. Adds a downloadable per-client .conf (amneziawgConfig.ts, mirroring wireguardConfig.ts) with the obfuscation lines, and an InboundOption.AwgServer field on the Go side so the config builder gets the full server block in one round trip. Along the way, running tools/openapigen surfaced a real bug: it doesn't flatten anonymously-embedded Go structs the way encoding/json does, so ServerSettings embedding Obfuscation20 produced a Zod schema with a nested `obfuscation20` key that never matches the real wire JSON. Fixed by un-embedding (flat fields + an accessor method) and registering internal/amneziawg in the generator's own package list, which had been silently emitting a dangling schema reference. English and Russian translations are complete; the other 10 locale files still fall back to English for the new keys. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(amneziawg): complete frontend parity for the Inbounds list page The Clients page (form, CRUD, QR/config) already worked from the prior commit; this closes the remaining gap on the Inbounds side and in a couple of protocol allowlists that a plain search for existing wireguard/mtproto handling turned up. lib/xray/inbound-link.ts gets amneziawg-specific link/config builders (genAmneziaWGLink/genAmneziaWGConfig, plus the *s fan-out variants) mirroring the wireguard ones — AmneziaWG has no legacy peers-array to fall back to, so these read settings.clients directly and add the obfuscation lines every client must share with the server. Wired into genInboundLinks generically, and into three consumers that call the wireguard builders directly rather than through that dispatcher: QrCodeModal, InboundInfoModal, and InboundsPage's bulk export. ClientInfoModal, ClientBulkAddModal, and the bulk attach/detach modals each had their own protocol allowlist that needed amneziawg added alongside wireguard/mtproto. Two real gaps surfaced by grepping every remaining 'wireguard' / Protocols.WIREGUARD hit in frontend/src rather than trusting the checklist was exhaustive: - useInbounds.ts's TRACKED_PROTOCOLS gates the deactive/depleted/ expiring/online client counts shown per inbound on the list page; without amneziawg those counts would silently read zero. - inbound-tag.ts is an explicit client-side mirror of the Go backend's port_conflict.go (the file says so itself: "Keep in sync"). It still only special-cased wireguard for UDP, so an amneziawg inbound would have fallen through to the TCP default and disagreed with the backend's own port-conflict math. Also finishes translating the AmneziaWG UI strings into the 11 locale files that were still falling back to English (ar-EG, es-ES, fa-IR, id-ID, ja-JP, pt-BR, tr-TR, uk-UA, vi-VN, zh-CN, zh-TW), matching en-US/ru-RU key-for-key (26 new keys, verified by count in every file). Not run anywhere: npm run typecheck / build. This machine has neither Node nor npm, so nothing here has compiled — reviewed by hand plus brace/paren balance checks and cross-referencing the generated Zod/TS types. Treat this as needing a real typecheck before shipping. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * docs(install): note that AmneziaWG kernel module install is still manual Tracked separately (not yet ported into this script) — see coinman-dev/3ax-ui's install_amneziawg for the reference approach (ppa:amnezia/ppa). Also serves as a real, path-filter-matching change to get the previous empty commit's CI trigger to actually fire — release.yml's push trigger is paths-scoped and an empty commit changes no files, so it never matched. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(amneziawg): add a button to randomize obfuscation parameters Mirrors the existing key-regenerate button next to the private key field. Client-side randomization matches the ranges/constraints of GenerateObfuscation20's "default" preset (internal/amneziawg/params.go) closely enough for a form suggestion — the user can still hand-edit any field afterward. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(install): auto-install the AmneziaWG DKMS module + amneziawg-tools Ports install_amneziawg from coinman-dev/3ax-ui's install.sh, adapted to this script's broader distro coverage and NONINTERACTIVE convention: - Ubuntu/Debian/Armbian: ppa:amnezia/ppa (primary, tested path), with a reachability pre-check for the Launchpad PPA host — often blocked by hosting providers, especially Russian VPS — so a flaky network skips the feature instead of hanging apt through several retries. - Fedora/RHEL-family, Arch/Manjaro/Parch: best-effort fallback to plain wireguard-tools (+ AUR amneziawg-dkms via yay/paru when available), with a manual-install pointer. - Everything else: manual-install pointer only. Also installs ndppd and persists IPv4/IPv6 forwarding (for the future IPv6/NDP phase, not yet wired into the panel) and adds a Secure Boot warning at the end of the run, since a DKMS-built module is unsigned and won't load while it's enabled — a common trap on cloud VPS images. Never fatal: the panel installs and runs fine either way, an AmneziaWG inbound just won't bring up its tunnel until the module is present. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(amneziawg): resolve all 3 real CI failures (typecheck/lint/codegen) Found by checking the fork's Actions tab after the last two pushes — the release build passed (it doesn't run these checks) but the separate CI workflow caught three real issues: - golangci-lint (noctx): every internal/amneziawg/manager.go exec.Command call is now exec.CommandContext with a 30s timeout, so a hung awg-quick/awg invocation can't block the reconcile job indefinitely (mirrors internal/mtproto/process.go's own CommandContext usage). - tsc --noEmit: frontend/src/schemas/client.ts's hand-maintained InboundOptionSchema (used by the useClients hook, separate from the auto-generated one in generated/) never got an awgServer field added when the AmneziaWG frontend work was done — every read of inbound.awgServer.* in amneziawgConfig.ts was typing as {}. Added AwgServerOptionSchema, nested (not flattened like wg*) to match what amneziawgConfig.ts already expects. Also guarded server.publicKey in inbound-link.ts's genAmneziaWGLink against the schema's optional type. - codegen staleness: frontend/public/openapi.json is produced by a Node script (gen:api) this machine can't run; hand-applied the exact diff the CI failure log already showed (amneziawg protocol enum entry, ServerSettings schema, InboundOption.awgServer, one example payload), verified as valid JSON. Also confirmed independently by this run: install_amneziawg (previous commit) installed and loaded the DKMS module successfully on both amd64 and arm64 CI runners. The two "Deploy Smoke Tests" failures are unrelated to this change — this fork has only ever published the dev-latest pre-release, and GitHub's /releases/latest API deliberately excludes pre-releases, so the smoke test's no-argument install path (which resolves "latest") has nothing to find. Not a regression; needs an actual tagged release whenever that's wanted. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(amneziawg): Phase 2a — IPv6 support + NDP proxy Adds native dual-stack IPv6 to AmneziaWG inbounds, ported from coinman-dev/3ax-ui's approach: - ServerSettings gets ipv6Enabled/ipv6Subnet/ipv6ExternalInterface; Instance carries the server's own IPv6 address (first host of the subnet) alongside its IPv4 one. - defaultAmneziaWGClients allocates an IPv6 host address per client (second AllowedIPs entry) when the server has IPv6 enabled, reusing allocateWireguardAddress — which needed a real fix along the way: it always suffixed "/32" regardless of address family, which is wrong for an IPv6 host address (needs /128). Now family-aware. - generateServerConfig's PostUp/PostDown gains IPv6 forward-accept rules, proxy_ndp sysctl, and one `ip -6 neigh add/del proxy` entry per enabled peer with an IPv6 address — the lightweight per-client method, not the ndppd-daemon whole-subnet method (not worth the config-file-management complexity at this scale; ndppd itself is still installed by install.sh in case that changes later). - ValidateIPv6Subnet rejects a malformed subnet before save. - Frontend: ipv6Enabled/ipv6Subnet/ipv6ExternalInterface fields on the AmneziaWG inbound form, EN+RU translations, openapi.json/generated/* regenerated (the latter via `go run ./tools/openapigen`, pure Go). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(amneziawg): fill in IPv6 fields missed by the Phase 2a commit Two real gaps the CI caught (both new fields, both my miss): - inbound-defaults.ts's createDefaultAmneziawgInboundSettings() built a server object literal predating ipv6Enabled/ipv6Subnet/ ipv6ExternalInterface — AmneziawgServer's inferred type now requires them (zod .default() fields are non-optional post-parse), so this didn't typecheck at all. - openapi.json's ipv6Enabled property was missing the description the real generator attaches (the Go doc comment covering all three IPv6 fields is attached to the first one) — a one-line diff, but git diff --exit-code doesn't care how small. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(amneziawg): Phase 2b — per-client port-forwarding Admins can now set a per-client ForwardedPorts string (e.g. "80, 443, 8000-8100") that gets DNAT'd + FORWARD'd to that peer's tunnel address via iptables rules in PostUp/PostDown, ported and simplified from coinman-dev/3ax-ui's shared/portfwd. Two decisions worth flagging for future readers: - The iptables --comment tag on each rule is awg-fwd-<fnv32a(email)>, not the raw client email. Email is admin/API-supplied free text that ends up embedded in a shell-executed PostUp/PostDown line; a hash can never carry a shell metacharacter through where raw interpolation could. - The reconcile manager gained a third fingerprint (portFwdFP, next to the existing structural/peers ones). `awg syncconf` only touches the WireGuard peer table — it never re-applies PostUp/PostDown iptables rules — so a port-forward-only change has to force a full awg-quick down+up bounce, same as a structural change, rather than the lighter sync a plain peer add/remove can use. Also fixes a real pre-existing bug found while wiring up IPv6 client allocation in the previous commit's spirit: allocateWireguardAddress always suffixed "/32" regardless of address family, which produced invalid host bits for IPv6 (needs "/128"). ForwardedPorts flows through model.Client -> model.ClientRecord (gorm column wg_forwarded_ports, auto-migrated) -> ToRecord/ToClient/ MergeClientRecord, mirroring the awgServer field's earlier lesson that new fields need checking against a second, hand-maintained persistence-layer struct. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(amneziawg): route a client's traffic through Xray via the Routing page Every enabled AmneziaWG inbound gets its own Xray TPROXY bridge automatically, with no toggle to enable first: a loopback dokodemo-door inbound (sockopt.tproxy) tagged with the AmneziaWG inbound's own real tag, so it's already selectable in the existing Routing page's inbound-tag picker — the same trick the mtproto sidecar's own bridge already relies on (InboundService.GetInboundTags is a plain, protocol-blind SELECT over every inbound row's tag, no dedicated UI plumbing needed). internal/amneziawg's defaultPostUpDown TPROXYs every peer's traffic into that bridge unconditionally; the bridge's port is derived deterministically from the inbound's id (EgressPortForInbound) so the kernel-side reconcile loop and the Xray-config generator never need to negotiate a runtime value between them. injectAmneziawgEgress never generates a routing rule itself — whether a client's traffic goes anywhere beyond Xray's default routing is entirely up to whatever rules the admin adds through the existing Routing UI (pick the AmneziaWG inbound's tag as source, optionally a specific peer's IP via that page's own Source-IP field, and an outbound), exactly the same workflow as routing any other protocol. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(amneziawg): recover orphaned interfaces after an ungraceful exit Two gaps left an AmneziaWG interface stuck outside the manager's control after a crash (kill -9/OOM/panic skips StopAll): - ensureRestart's teardown was gated on the in-memory `exists` map, which is always empty on a fresh process, so a survived interface never got interfaceDown before interfaceUp tried `ip link add` against a name the kernel already had — failing forever and never populating m.ifaces, so traffic accounting silently stopped and the inbound could never be removed. Gate on isInterfaceUp instead, which checks real kernel state rather than this process's own bookkeeping. - An inbound deleted from the database entirely while the panel was down has no entry in `desired` ever again, so it never reaches the per-id cleanup loop in Reconcile (which only walks m.ifaces). Add a one-time sweepOrphansLocked scan of configDir, mirroring mtproto.Manager.sweepOrphansLocked, that tears down and removes any leftover interface/config not in the current desired set. Found by the automated review on MHSanaei/3x-ui#6105 (Finding 1). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * i18n(amneziawg): backfill IPv6/obfuscation/port-forwarding keys in 11 locales Only en-US/ru-RU ever got these 9 keys as each AmneziaWG feature landed (the regenerate-obfuscation button, then Phase 2a's IPv6 fields, then Phase 2b's per-client ForwardedPorts) — the other 11 locale files were never backfilled, so i18next has been silently falling back to English for all of them since Phase 1. Cosmetic-only (never broke anything), but now closed for every shipped locale. * fix(amneziawg): resolve 7 Medium findings from the automated PR review Each is independently reproducible; fixed together since one review pass found all of them. - manager.go: the shared "ip rule add fwmark" policy route had no existence check, so it duplicated in "ip rule show" on every interface bounce (which hostRulesFingerprint forces on any client add/remove/ re-IP). Now checked via "ip rule list | grep -q ..." first. (Finding 2) - params.go: ExternalInterface, IPv6ExternalInterface, and subnetIp/ subnetCidr are interpolated unescaped into a shell-executed PostUp/ PostDown line, but only obfuscation and the IPv6 subnet were validated before save. Added ValidateInterfaceName (a strict charset+length pattern) and ValidateSubnetIPv4 (netip.ParsePrefix), wired into normalizeAmneziaWGSettings. (Finding 3) - amneziawg_job.go: IsAwgInstalled() existed but nothing ever called it, so a host without awg/awg-quick (the Docker image, RHEL, Arch, a failed install.sh PPA step) logged a reconcile failure every 10s forever. Now checked once an inbound actually needs it, warning once instead of spamming. (Finding 4) - client_inbound_apply.go: the WireGuard/AmneziaWG credential carry-forward (added so a metadata-only client edit doesn't rotate keys) never covered ForwardedPorts, so a partial edit -- an API call or Telegram-bot toggle that omits the field -- silently wiped a client's port-forwarding spec. Carried forward and written back the same way the key fields already are. (Finding 5) - manager.go: hostRulesFingerprint keyed each peer on its IPv4 address only, and structuralFingerprint omitted IPv6Enabled/IPv6ExternalInterface entirely, so an IPv6-only change could pick the syncconf reload path (which never re-runs PostUp, leaving a stale NDP-proxy entry) or be a complete no-op. Both fingerprints now cover the IPv6 fields. (Finding 6) - port_conflict.go: the AmneziaWG egress bridge (injectAmneziawgEgress) binds 127.0.0.1:63100+id with no collision check anywhere, since it isn't a database row the ordinary port-conflict query can see -- same blind spot the reserved Xray API port already has its own check for. Added the equivalent check for the AmneziaWG bridge port. (Finding 7) - install.sh: install_amneziawg ran unconditionally for every install/ update, building a DKMS kernel module and enabling host-wide IPv4/IPv6 forwarding whether or not the feature is ever used. Gated behind a new should_install_amneziawg (XUI_INSTALL_AMNEZIAWG=true/false, or an interactive y/N prompt defaulting to no). Also replaced the deprecated apt-key adv with a dedicated keyring + signed-by= on the Debian branch, and guarded its sources.list appends against duplication on a retried install. (Finding 8) Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(amneziawg): make the Xray TPROXY bridge a per-inbound opt-in Addresses Finding 10 from the automated PR review: an always-on TPROXY bridge makes every AmneziaWG tunnel hard-depend on Xray being up (all traffic, including DNS, drops whenever Xray restarts), and forces a full awg-quick down+up bounce on any client add/remove/re-IP, permanently losing the syncconf fast path. Adds ServerSettings.RouteThroughXray (off by default): - defaultPostUpDown only emits the TPROXY/policy-route rules when it's on; a plain AmneziaWG tunnel now has zero Xray dependency out of the box. - structuralFingerprint covers it (toggling it changes whether PostUp/ PostDown contain any TPROXY rules at all -- structural, not a per-peer host-rule). hostRulesFingerprint's IPv4 tracking is now itself conditional on RouteThroughXray (and IPv6 tracking on IPv6Enabled), so an instance that never uses either keeps the syncconf fast path for a plain peer re-IP. - injectAmneziawgEgress only creates a bridge for inbounds that opted in; checkAmneziawgEgressConflict (the Finding-7 fix) now parses each candidate through InstanceFromInbound so a non-routed inbound's port is correctly never treated as reserved. - New inbound-level Switch in the AmneziaWG form; the actual outbound decision is still made entirely through the panel's stock Routing page, same as before -- only whether the bridge exists at all is now a choice. Translation keys added to all 13 locales in the same commit this time, not backfilled later (see Finding 9's lesson). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(amneziawg): resolve 4 Low findings from the automated PR review - manager.go: serverAddress assumed subnetIp always ends in ".0"; a base like "10.8.1.5" was used verbatim as the server's own address, eventually colliding with peer allocation (which starts at .2 upward). Now derives the first host of the actual subnetIp/subnetCidr network via netip, matching serverAddressV6's own approach. A /32 base (no host bits at all) is still used as-is. (Finding 12, partial -- the /16 pool-widening half of this finding only exists on the upstream-pr/amneziawg branch's merged client_wireguard.go, not here; handled separately on that branch.) - manager.go: ensureLocked carried the previous per-peer traffic counters (`last`) forward even through a full restart, but awg-quick down+up resets the kernel's own counters to zero -- the next CollectTraffic computed a large negative delta (clamped to 0), silently discarding real traffic. Extracted the decision into nextTrafficBaseline: only a reload (syncconf) preserves the baseline. (Finding 13) - portfwd.go: exported ForwardedPortsInclude; inbound_amneziawg.go's new checkForwardedPortsConflict uses it to reject, at save time, a client's forwardedPorts that would DNAT the panel's own port or another enabled inbound's port to the tunnel client -- portForwardLines has no destination restriction, so this collision was previously silent. Wired into both the single-client update path and the add-client path (client_inbound_apply.go), plus normalizeAmneziaWGSettings for the whole-inbound save path. (Finding 14) - inbound.go: InboundOption.AwgServer sent the whole ServerSettings struct including PrivateKey to GetInboundOptions callers -- a shared, admin-wide dropdown-filling endpoint the frontend's own AwgServerOptionSchema never reads that field from. Redacted it before assigning. (Finding 11) Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(amneziawg): don't widen the peer address pool past AmneziaWG's own subnet Completes Finding 12 from the automated PR review (the serverAddress half of this finding was already fixed on main and cherry-picked here). This half is specific to this branch: allocateWireguardAddress's /16 pool-widening fallback is an independent addition from upstream's own main that this branch inherited during the cherry-pick rebase -- it doesn't exist on the fork's own main at all, so this fix can't be cherry-picked the normal way and is committed directly here. Widening is safe for WireGuard's own Xray-native inbound (AllowedIPs isn't tied to a strict kernel interface subnet), but AmneziaWG's kernel interface Address is exactly the configured subnet -- an address allocated from the containing /16 once the /24 fills up would be silently unroutable. allocateWireguardAddress now takes an explicit allowWidening bool: WireGuard's own caller passes true (unchanged behavior), AmneziaWG's passes false (fails loudly on exhaustion instead). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * docs(docker): note that AmneziaWG doesn't work in this image Investigated: the image is Alpine-based, and AmneziaWG's own packaging (DKMS module + amneziawg-tools) doesn't target Alpine/musl at all -- unlike the Debian/Ubuntu/Fedora/Arch paths install.sh already handles, there's no package to apk add even with full host network/capabilities. The panel already degrades gracefully (IsAwgInstalled() logs one warning instead of retrying forever), so no code change is needed -- just made the reason explicit at the point where a user would reach for cap_add/ network_mode to try to work around it. * fix(sub): include amneziawg inbounds in subscription links getInboundsBySubId's SQL protocol allowlist never had 'amneziawg' added, so every AmneziaWG client was silently excluded from all three subscription formats (plain/individual links, JSON, Clash) and from the Telegram bot's QR/individual-link buttons, which fetch through the same path. genAmneziaWGLink itself was already fully implemented and already wired into GetLink's dispatch switch -- it just never got a chance to run. Same bug shape as the earlier TRACKED_PROTOCOLS frontend gap: a hardcoded protocol list one entry short. Found while investigating whether the Telegram bot needed AmneziaWG- specific client-management code -- it doesn't (the bot itself is fully protocol-agnostic), but this is the actual root cause of "can't share an AmneziaWG client's config via the bot." Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(inbound): enforce node-eligibility server-side, not just in the UI Investigated multi-node interaction with AmneziaWG: the master's own reconcile (DesiredAmneziaWGInstances) and Xray config generation (injectAmneziawgEgress, the GenXrayInboundConfig protocol skip) all correctly filter on NodeID IS NULL, so a node-assigned AmneziaWG (or MTProto) inbound would never be managed by the master. But nothing stopped one from being created that way: NODE_ELIGIBLE_PROTOCOLS (frontend/src/pages/inbounds/form/InboundFormModal.tsx) only hides the node picker client-side -- a direct API call could set nodeId on an AmneziaWG inbound, which every node then reconciles as an ordinary local inbound (nodes run the identical binary, full cron suite included), leaving it running unmanaged and untracked by the master's own AmneziaWG bookkeeping. Added isNodeEligibleProtocol (inbound_protocol.go), mirroring the frontend's allowlist, and enforced it in both AddInbound (the actually exploitable path -- nodeId comes straight from the request) and UpdateInbound (defense in depth; NodeID is already restored from the stored row there before this check, so it mainly guards against a protocol change on an existing node-hosted inbound). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(amneziawg): allow TPROXY-marked traffic through a default-deny INPUT chain TPROXY never rewrites a packet's own destination address, only the routing decision. A default-deny firewall whose INPUT chain sanity-checks "is this destination actually local" (UFW's ufw-not-local, via addrtype --dst-type LOCAL, is a concrete example) silently drops the redirected packet before Xray's socket ever sees it -- RouteThroughXray looked fully configured (TPROXY rule present and counting, Xray listening with IP_TRANSPARENT set) yet every peer's traffic vanished with no trace on either side. Adds an idempotent, never-torn-down "iptables -I INPUT 1 -m mark --mark <fwmark> -j ACCEPT" alongside the existing shared policy route, so this works regardless of which firewall manager owns the rest of the INPUT chain. * fix(frontend): give AmneziaWG the same UDP tag and its own tag color The Inbounds list only special-cased isWireguard/isHysteria for the "UDP" network badge, so an AmneziaWG row showed just the bare protocol tag with no transport badge next to it. Added the missing isAmneziawg flag (mirrors isWireguard exactly) and wired it into the same branch. Client-row protocol-color maps in ClientsPage/HostList had no amneziawg entry, silently falling back to grey -- ClientInfoModal already had amneziawg: 'yellow' from earlier work, these two just never got it. * feat(logs): show which AmneziaWG client an access-log line belongs to The dokodemo-door TPROXY bridge every AmneziaWG peer's traffic is routed through has no per-user identity, so Xray's own access log never carries an "email:" token for these lines -- the Access Logs modal showed a blank Email column for every in-*-udp row, even though every other protocol's rows show the client normally. The peer's decapsulated tunnel IP does survive as the log's "from" address, and that IP deterministically maps to exactly one configured peer. Builds a "<inbound tag>|<ip>" -> email index from the same AmneziaWG inbounds already parsed elsewhere (amneziawg.InstanceFromInbound), and fills in Email from it whenever the raw log line didn't have one. * fix(amneziawg): enable sniffing on the TPROXY bridge Domain-based Routing rules could never match RouteThroughXray traffic: an AmneziaWG peer resolves DNS itself, through the tunnel, before ever sending a packet, so the decapsulated traffic TPROXY hands to the bridge is already a bare destination IP with no domain name attached at the network layer. Every other inbound recovers this via sniffing (confirmed working for the stock wireguard inbound, which does have it configured); the bridge never got a sniffing block at all, so only tag/IP/network-based rules could ever match it -- any domain rule above it in the list was silently unreachable. * docs: add an AmneziaWG config page and list it as a supported protocol Closes the PR checklist gap: the feature shipped with zero mention on the docs site. Mirrors reality.mdx's structure (key settings, setup steps, config excerpt) and notes the Docker/multi-node/Telegram-bot caveats the PR itself is honest about not having confirmed. * fix: address the fresh review round on PR #6105 (8 findings) 1. hostRulesFingerprint didn't account for ForwardedPorts when RouteThroughXray was off, so re-IPing a peer with port-forwarding configured left stale DNAT rules pointing at an address the next peer could be handed. 2. Server/client config values (keys, email, I1) were never validated for control characters before being written into the generated .conf; a newline could smuggle a PostUp hook into awg-quick's parser. Added ValidateConfigValue at save time and a sanitizeConfigValue backstop at render time. 3. checkForwardedPortsConflict didn't scope to node_id IS NULL, so a port used only on a different node produced a false collision; also hoisted the panel-port/inbounds lookup out of the per-client loop (portConflictContext) so N clients cost one query, not N. 4. PostDown commands were ";"-joined and abort on the first failure; appendOrTrue makes teardown best-effort so an external firewall flush can't leave DNAT rules to accumulate across bounces. 5. The "ip rule list | grep -q" existence check could SIGPIPE under pipefail and re-add a duplicate rule; switched to grep -c >/dev/null. 6. Ported the vpn:// share-link format (base64url of the plain .conf text, matching the real AmneziaVPN app) onto this branch -- it had only ever landed on our own fork's main, so this PR branch was still on the old amneziawg://+query-params scheme our own docs no longer described. Also corrected the docs' install.sh claim (opt-in/ interactive, not automatic) and stale pre-opt-in comments in route_egress.go. 7. install.sh: Arch's ndppd install used pacman -Syu (full system upgrade) instead of -Sy like every other call in the script; and should_install_amneziawg re-prompted on every `x-ui update` even when awg was already installed. 8. CollectTraffic could clobber a concurrent restart's freshly-reset (empty) traffic baseline with stale pre-restart counters, since getPeerStats runs lock-free; now checks pointer identity before writing back. sweepOrphansLocked permanently disabled itself on a transient os.ReadDir failure instead of allowing a retry. go build/vet/test and frontend typecheck/lint/build/vitest all pass. * fix(install.sh): check the live sysctl value, not sysctl.conf text Reviewer feedback (cherts, PR #6105): grepping /etc/sysctl.conf for the setting name is unreliable -- many distros split sysctl config across /etc/sysctl.d/*.conf, and /etc/sysctl.conf can be a symlink into that directory, so the check can miss an already-active setting (harmless duplicate append) or match a disabled/commented line (forwarding silently stays off). Query the live value via `sysctl -n` instead, which is accurate regardless of which file set it. Applied the same fix to both the IPv6 and IPv4 checks for consistency. * fix: update inbound_amneziawg.go to the split buildInboundForLocalRuntime Same fork-only-file blind spot as the one caught on our own main after the 3.6.0 sync: upstream split buildRuntimeInboundForAPI into buildInboundForNodePush / buildInboundForLocalRuntime (part of the node-sync client-deletion fix,5bc81dfd), updating every call site it could see. This file doesn't exist upstream, so it kept calling the old name even after the branch merged in that commit. * fix(frontend): recognize AmneziaWG's vpn:// scheme in share-link labels The shared link-tag/label helper (used by the client info modal, QR modal, and subscription page) had no entry for the vpn:// scheme AmneziaWG links use, so it fell through to the generic fallback: a plain "Vpn" tag with no color, and an empty remark/port that made the row's title fall back to "Link N" instead of the inbound's actual name:port — unlike every other protocol, which shows its real tag and label. vpn:// links are base64url of a plain .conf text (matching the real AmneziaVPN app's own share-link format), not a structured URL, so there's no query string or #hash to read a remark/port from. Decode the payload and pull the remark/endpoint back out of the .conf text directly instead. * fix(xray): force a full restart for TPROXY inbounds, never hot-add them Real incident: an AmneziaWG inbound with RouteThroughXray enabled lost all internet on that connection after a migration. Root-caused on the live box -- iptables TPROXY counters were incrementing (packets correctly redirected to 127.0.0.1:63110), but nothing was actually listening there (ss showed nothing on that port) until a full `systemctl restart x-ui`, after which the bridge came up immediately. Xray-core's gRPC AddInbound reports success for a new sockopt.tproxy inbound (internal/amneziawg's own Xray egress bridge is the only kind this fork ever generates) but doesn't reliably bind a working listener for it outside of process startup -- the bridge silently never comes up, and RouteThroughXray traffic goes nowhere until the next full restart happens to occur for an unrelated reason. diffInbounds already has this exact defensive pattern for REALITY inbounds ("a gRPC remove+add does not reliably rebuild the REALITY authenticator"), just never extended to TPROXY, and only in the already-existing-then-changed branch -- the "brand new inbound" branch had no such guard at all, which is exactly the path a freshly-enabled RouteThroughXray bridge takes. Added inboundUsesTproxy and wired it into both branches. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(amneziawg): flag Xray for resync when a peer edit changes qualifying state Real production bug, root-caused on iiadmin-vps: updateAmneziaWGInbound/ AddInbound/DelInbound only ever updated the kernel interface via amneziawg.GetManager() -- they never called SetNeedRestart the way every other protocol's mutation path does (client_crud.go, inbound.go, etc. all do). injectAmneziawgEgress's TPROXY bridge inbound depends on InstanceFromInbound finding at least one qualifying peer plus RouteThroughXray, so an edit that flips that (first peer added, last one removed, RouteThroughXray toggled on) previously required a full panel restart before the bridge actually got created, with no error anywhere: the kernel interface would handshake fine, but traffic redirected into the bridge's TPROXY port went nowhere because nothing was listening there. diffInbounds/inboundUsesTproxy already correctly force a full restart for a brand new TPROXY inbound (bdee0a20) -- that part was never the bug. The gap was entirely upstream: nothing ever told Xray a resync was even needed. * fix(clients): reject AllowedIPs already used on another WireGuard/AmneziaWG inbound defaultWireguardClients/defaultAmneziaWGClients only ever checked uniqueness against their own inbound's client list, so two inbounds sharing a subnet (same protocol or not) could silently hand out or accept the same address -- the exact scenario behind a real duplicate-IP incident where a WireGuard and an AmneziaWG client both ended up on the same address. otherTunnelAllowedIPs now collects every address already claimed on every other tunnel inbound and folds it into both the auto-allocation pool and the manual-entry collision check, naming the other inbound in the error when it fires. * fix(frontend): add the missing AmneziaWG config download on the sub page The subscription page already gave WireGuard links their own "Config" block (copy/download/QR of the actual .conf, via wireguardConfigFromLink reversing the wireguard:// query params) but had no equivalent for AmneziaWG's vpn:// links -- its isWireguardLink gate never matched them, and no reverse-parse helper existed for this page specifically. Every other surface (InboundInfoModal, ClientInfoModal, ClientQrModal) already had this parity; this was the one page that didn't. Fixed by adding amneziawgConfigFromLink (inbound-link.ts), simpler than its WireGuard counterpart since a vpn:// payload already *is* the plain .conf text -- just base64url-decode it, no query-param reconstruction needed -- and wiring it into SubPage.tsx alongside the existing WireGuard block, reusing the same pages.clients.amneziaWgConfig label the other three surfaces already use. * fix(xray): force a full restart for password-auth SOCKS5 hot-apply Real production incident: editing a client under an AmneziaWG inbound left its embedded SOCKS5 relay's settings byte-different (a new account list), and Xray's gRPC remove+add hot swap silently dropped the account for a peer whose email contained non-ASCII characters -- its tunnel kept handshaking fine but all its traffic got rejected at the SOCKS5 layer, while every other peer on the same relay was unaffected. A full restart (reading the same JSON straight from disk) always produced the correct account list. socks isn't in userDiffableProtocols (that only covers vless/vmess/trojan's clients+email shape, not accounts+user), so any settings drift on this inbound fell through to the generic remove+add path. Forces a restart instead, the same defensive choice already made for REALITY and TPROXY -- scoped to auth:"password" specifically so the other, noauth SOCKS5 bridges (panel/node/mtproto egress) keep the cheaper hot path. * Fix Attach reusing one identity's address across wg/awg inbounds ClientService.Attach deliberately copies one identity's stored AllowedIPs into every WireGuard/AmneziaWG inbound it's attached to in the same call, so the same person gets the same tunnel address on every protocol they use. Its loop calls addInboundClient once per inbound, and each of those independently computes otherTunnelAllowedIPs -- so by the second inbound in the batch, the first inbound's just-written copy of this identity's own address looked like a cross-inbound collision against itself. Real production symptom this caused: detaching then re-attaching a client to both wg and awg failed with "wireguard: allowedIPs entry X is already used by a client on inbound 'awg' (#N)" -- the exact address the identity is supposed to keep, rejected as if it belonged to someone else. Add a selfEmails exclusion to otherTunnelAllowedIPs and populate it from the client(s) being processed at the one real call site. Safe unconditionally: ClientRecord.Email is globally unique, so a match can only ever be this same identity's own entry on a sibling inbound, never a genuine different client's address. Reproduced the underlying mechanism live (manual entry correctly rejected as a cross-inbound collision; fresh auto-allocation correctly avoided a used address) before writing the fix, to confirm the guard itself works and the bug is specifically in how Attach's per-inbound calls interact with it. * Attach: allocate fresh when re-attaching with no active tunnel The previous fix (82cc69f5) made Attach's own address-reuse correctly not collide with itself across inbounds -- but it still always reused an identity's stored AllowedIPs verbatim, even when that identity currently has zero WireGuard/AmneziaWG attachments at all. A real report from testing this live: an identity fully detached from both its wg and awg inbounds, then re-attached, got its old address back even though several lower addresses were free -- because nothing about being fully detached ever cleared the stored value Attach copies from. Add hasTunnelAttachment, checked once against the identity's CURRENT inbound set before Attach's loop runs: if none of its current inbounds is WireGuard/AmneziaWG, clear the stored AllowedIPs so this attach allocates fresh (matching what a brand-new client would get) instead of resurrecting an address nothing reserves anymore. Left alone when the identity already has an active tunnel elsewhere, so extending it to a second protocol still keeps a consistent address. * Fix TestOtherTunnelAllowedIPsExcludesSelfEmail's own test setup CI caught this: the "genuinely different client" (other@wg) was seeded onto the SAME inbound passed as excludeID, which otherTunnelAllowedIPs already excludes entirely regardless of the selfEmails fix -- so the assertion that its address is still reported could never have passed, proving nothing either way. Move it onto the sibling inbound alongside shared@id, which is what the test actually needs to exercise (two clients on one sibling, one excluded by email, one not). * Attach: never inherit an address that doesn't fit the target inbound hasTunnelAttachment (from the earlier fix, commit 51067f16) only asked "does this identity have ANY tunnel attachment", treating that as license to reuse its stored address verbatim on every inbound being attached. Real production case this missed: an identity's stored address came from WireGuard's own fallback subnet (10.0.0.0/24, used when that inbound has no other clients to infer a base from), then got attached to a second, AmneziaWG inbound configured for a completely different subnet (10.8.1.0/24). defaultAmneziaWGClients's already-set-AllowedIPs branch only checks for collisions, never subnet membership, so the mismatched address was accepted silently -- producing a peer that can never actually connect, since an AmneziaWG address must fall inside the kernel interface's own configured subnet to be routable at all. Add addressesFitAmneziaWGInbound, checked per inbound inside Attach's loop: if the inherited address doesn't fit the SPECIFIC inbound being attached, clear it just for that one so it gets a fresh, valid allocation instead, while other already-attached inbounds keep their existing values. WireGuard has no equivalent strict subnet requirement (allocateWireguardAddress can widen to a fallback pool for it), so this only ever constrains AmneziaWG targets. * Give WireGuard an explicit, admin-configurable subnet field WireGuard previously had no configurable subnet at all -- only an implicit one, either inferred from existing clients' own addresses (wireguardAllocationBase) or a hardcoded 10.0.0.0/24 fallback when none exist yet. AmneziaWG, by contrast, has always had a real server.subnetIp/subnetCidr field in its settings, editable in the UI. User request: give WireGuard the same treatment. Backend: explicitWireguardSubnetBase reads an optional subnetIp/ subnetCidr pair from the inbound's own settings JSON (mirroring AmneziaWG's defaultAmneziaWGSubnetBases). defaultWireguardClients checks it first; only when unset does it fall back to today's inference-from-existing-clients behavior, so an inbound saved before this field existed keeps working exactly as it always has. Frontend: subnetIp/subnetCidr added to WireguardInboundSettingsSchema and the inbound form (mirroring AmneziaWG's own field layout/labels), with a real default (10.0.0.0/24, the same value the backend already fell back to) seeded for newly created inbounds so the field starts populated and editable rather than blank. Translated across all 13 locales. This also structurally closes the class of bug fixed in 82cc69f5/291c47b3: with wg and awg subnets explicit and independently controllable, an admin who wants matching addresses across both protocols can configure them to actually agree, instead of one silently inheriting the other's incompatible range. * Split the client edit form's AllowedIPs into per-protocol fields A client attached to both WireGuard and AmneziaWG shared one AllowedIPs form field with a dynamically-switching label, so its two genuinely different addresses could never both be shown or edited correctly. Worse, Update/Create broadcast that one shared value to every attached wg/awg inbound with no subnet-fit check, so an ordinary edit save could silently overwrite one protocol's address with the other's -- the same bug class already fixed for Attach, but reachable from any client edit. model.Client gains an optional AllowedIPsByInbound map so a caller can send distinct values per inbound; Update/Create honor it and, when it's absent, clear a shared value that doesn't fit an AmneziaWG inbound's own subnet instead of writing it through. A new TunnelAllowedIPsByInbound read path feeds the real per-inbound address to the client edit form via GET, which now renders two separate, correctly-labeled fields whenever both protocols are attached (unchanged single dynamic field otherwise). * Regenerate openapi.json for the new allowedIPsByInbound field Follow-up to 878ee839: gen:zod (frontend/src/generated) was already regenerated and committed, but gen:api (frontend/public/openapi.json) wasn't, so CI's codegen drift check failed. * Fix build breakage from merging upstream main: Update() gained a limitHwid param Two of our own AllowedIPs tests (not present upstream, so the merge never flagged them as conflicting) still called the old 3-arg Update(inboundSvc, id, client) -- upstream's hardware-ID-limit feature added a required limitHwid parameter that every other caller in this package already passes. Also drop createDefaultInboundSettings from InboundsPage.tsx: the merge conflict resolution kept the import, but upstream's clone-payload refactor (buildClonePayload, inbound-clone.ts) already calls it internally now -- this file doesn't need it directly anymore. * Fix real bug: AmneziaWG clients rejected as "empty client ID" in 3 places Three switch statements on inbound.Protocol handle "wireguard" explicitly (checking client.PublicKey) but fall through to the default case for "amneziawg" (checking client.ID, which AmneziaWG clients never set -- they use PublicKey/Email like WireGuard, not the VMess/VLESS UUID field). This is what the 4 AllowedIPs tests were actually catching: UpdateInboundClient's newClientId derivation hit this same default branch, so every Update() on an AmneziaWG client returned "empty client ID" before ever reaching the AllowedIPs logic being tested. Fixed by adding "amneziawg" alongside "wireguard" in each switch: addInboundClient's per-client validation, UpdateInboundClient's newClientId derivation, and AddInbound's per-client validation (the third one wasn't hit by these tests, but has the identical bug -- creating a brand-new AmneziaWG inbound with a client attached would fail the same way). * refactor(amneziawg): rename Obfuscation20 to Obfuscation31, drop the dead mobile preset Mechanical rename ahead of the AmneziaWG 3.1 parameter work: the type, generator and prose all said 2.0, and the "mobile" generator preset was reachable only from its own test. No behavior change. * feat(amneziawg): AmneziaWG 3.1 obfuscation parameters (backend + generated schemas) Adds the 3.1 parameter surface to the inbound settings and both Go config emitters: I2-I5 signature packets, HeaderProtectionKey (base64 32-byte, shared server<->client), ContentPaddingAddition, the five handshake-timing randomization ranges (RekeyAfterTime/RekeyTimeout/RejectAfterTime/ KeepaliveTimeout/MaxHandshakeAttempts), and the RandomTrailers/ DisableCookies switches. Freshly generated sets fill everything except I2-I5 (matching Amnezia's own generator) with jittered ranges bracketing WireGuard's stock timing constants; every reject window starts >= 30s above the rekey window by construction. Empty fields stay off the wire, so blanking a field disables just that feature. Validation generalizes the H1-H4 range checker for the new uint32-range fields, requires min 1 on timers, cross-checks rekey-vs-reject, and demands a real 32-byte base64 header-protection key. The manager warns once per process when the installed awg tools predate 3.1 but an inbound uses 3.1 parameters (awg-quick rejects unknown keys with a generic error otherwise); apply still proceeds. Requires amneziawg-tools v3.1.20260812+ / module or amneziawg-go v3.1.20260814+ on the host. * feat(amneziawg): emit and randomize 3.1 parameters in the frontend Both client-config emitters (the vpn:// link builder and the clients-page .conf builder) now carry the 3.1 [Interface] lines in the same order as the Go emitters. The obfuscation randomizer moves out of InboundFormModal into a shared lib/xray/amneziawg-obfuscation.ts that also fills the new fields, and createDefaultAmneziawgInboundSettings switches from static values to that generator — a fresh inbound now really gets the unique fingerprint the docs promise instead of the same jc=5/jmin=10 set on every install. Schema parse-time defaults for the new fields stay ''/false on purpose: real values come only from the generator, so resaving an inbound never mutates its stored parameters. A new parity test pins the hand-written AmneziawgServerSchema to the generated ServerSettings key set, so a field added on one side can no longer silently vanish from configs. * feat(amneziawg): 3.1 form fields and translations Inbound form gains inputs for I2-I5, HeaderProtectionKey (filled by the existing obfuscation Regenerate button), ContentPaddingAddition, the five timing ranges, and the RandomTrailers/DisableCookies switches; the MTU input picks up the min=1 its schema already enforced. All 13 locales get the 19 new keys and drop the "2.0" branding from the s3/s4/i1 labels. * docs(amneziawg): document 3.1 parameters; install.sh kernel/version notes The AmneziaWG page's obfuscation section moves from the 2.0 to the 3.1 parameter set: table rows for I2-I5, HeaderProtectionKey, ContentPaddingAddition, the timing-randomization ranges and the RandomTrailers/DisableCookies switches, a requirements callout (tools v3.1.20260812+, module/awg-go v3.1.20260814+, Linux 6.7+ for the DKMS path), and a sample client .conf that matches what the panel actually emits (including the DNS defaults and PersistentKeepalive it always had). install.sh warns before a DKMS build on a pre-6.7 kernel and after any install that left pre-3.1 amneziawg-tools on PATH. Also updates the hosts API operation paths ({id} -> {groupId}) in the stale ru/zh/fa reference pages: syncing docs/public/openapi.json for the new AmneziaWG schema fields surfaced that rename, which had never been copied over, and the docs build fails on paths missing from the spec. * fix(amneziawg): reject control characters and canonicalize 3.1 range values Adversarial review of the 3.1 work surfaced a validation gap: base64.DecodeString silently ignores CR/LF, so a header-protection key that picked up a line wrap in transit decoded to a valid 32 bytes, passed validation, and was emitted verbatim into every client config — where the orphan second line breaks the import while the server (whose emitter strips control chars) keeps running with the correct key. The key and range validators now reject control characters outright. Also from the same review: range values are canonicalized on save ("110 - 140" -> "110-140", whitespace-only collapses to feature-off, closing a case where the server conf rendered an invalid blank-value line the client emitters omitted); the rekey/reject invariant is now enforced against WireGuard's 120s/180s defaults when only one side is set; and the structural fingerprint joins on "\n" instead of "|", which is a legal I1-I5 character and made adjacent free-text fields join-ambiguous. * fix(install): resolve latest release tag via web redirect to dodge API rate limits The non-interactive install smoke test resolved the release version through the unauthenticated GitHub API (api.github.com/.../releases/latest), which allows only 60 requests/hour per IP. The test installs twice in one run, and on shared CI runner IPs the second call gets rate-limited, returns no tag_name, and install.sh treats an empty version as fatal (exit 1) — the same "Failed to fetch x-ui version" real users hit behind CGNAT/shared addresses. resolve_latest_tag() now reads the tag from the github.com releases/latest web redirect (not subject to the API rate limit), falling back to the API only if the redirect yields nothing. Verified with the real deploy/test/smoke-noninteractive.sh (two installs, both green). * fix(amneziawg): three review findings on #6105, plus a comment trim 1. A peer's allowedIPs reached the generated .conf unvalidated and unsanitized, unlike email/publicKey/preSharedKey which normalizeAmneziaWGSettings already guards. A newline in an entry let a following "[Interface]" re-open the interface section, whose "PostUp = ..." awg-quick then runs as root on the next apply. Reproduced end to end against generateServerConfig. The save path now rejects and canonicalizes through normalizeWireguardAllowedIPs, and the render path sanitizes as a backstop for rows predating the validation (an upgrade, a restored backup, a direct DB edit). H1-H4 get the same render-time sanitize, and the two NIC name fields a plausibility check, since stripping control characters alone would still let a shell metacharacter into a root-executed PostUp line. 2. EgressPortForInbound is 63100 + inbound id, so an id past 2435 derives a port above 65535 -- and Xray rejects the whole generated config over one invalid port, taking every other protocol down with it. It now reports ok=false past the range, and both the Xray bridge and its TPROXY rules are skipped instead of emitting an impossible port. 3. The downloadable AmneziaWG .conf read ClientRecord.allowedIPs, a single shared column that holds the WireGuard address for an identity attached to both protocols -- the exact ambiguity tunnelAllowedIPs was added to resolve for the edit form. The info and QR modals already hydrate that field, so they now pass this inbound's own address to the builder. Also trims the comment blocks in the files touched here to the 2-line guidance in CLAUDE.md: internal/amneziawg alone carried 423 comment lines in over-long blocks against 118 for the comparable internal/mtproto, and is now at 110. Every non-obvious constraint is kept (the kernel S1/S2 rule, why PostDown is best-effort, why grep -c and not -q, why the fingerprints split three ways); the narration is gone. Two hot_diff.go comments pointed at an internal/amneziawgnet package and an injectAmneziawgnetSocks function that exist nowhere in the tree; the checks themselves are unchanged. * feat(logs): add an AmneziaWG log view to the overview The overview has an access-log view for Xray but nothing for AmneziaWG, so when a tunnel misbehaves there is no way to see it from the panel at all. A kernel tunnel logs no per-request lines, so the equivalent view is built from the two things it does expose: - Live per-peer activity from `awg show <iface> dump`, joined to the client email through the desired peer set: last handshake, endpoint, allowed IPs, cumulative transfer and online state, newest handshake first. - The panel's own AmneziaWG event lines (interface up/down, awg-quick failures, the pre-3.1 tools warning), which are what actually explain a peer being absent from the table. POST /panel/api/server/amneziawglogs/:count serves both, with the same count + filter contract GetXrayLogs uses, and the modal mirrors XrayLogModal's toolbar, auto-update, mobile cards and download. The action-bar button is gated on a new status.amneziawg.configured, which stays true while an inbound exists but its interface is down -- exactly when the event lines matter. Verified against a running panel: the endpoint returns the peer table and real event lines ("awg/awg-quick not found on PATH", "create config dir: permission denied"), and count and filter both narrow as documented. One of those lines surfaced a Debugf that had been rendering as "for inbound1:amneziawg:"; fixed here since it is now user-visible. * fix(amneziawg): stop double-counting a routed inbound's traffic injectAmneziawgEgress tags its Xray bridge with the AmneziaWG inbound's own tag, so the stock Routing page can target it. Xray therefore reports that bridge's bytes under the inbound's tag, and XrayTrafficJob feeds them to AddTraffic -- which accumulates -- on top of the same bytes AmneziaWGJob already reported from `awg show dump`. An inbound with routeThroughXray on counted roughly twice its real traffic, which also inflates the quota checks that read the same counters. The awg counters are the complete measure: every peer, whether or not TPROXY routed it, and the same wire bytes the per-client totals are built from, so they stay and the Xray rows are dropped. Per-client stats were never affected -- a dokodemo-door bridge has no per-user identity, so Xray emits no user>>>email rows for it. Filtering happens before every consumer, so the DB totals, the external traffic inform and the dashboard's live speed all read one source per inbound. The set of bridge tags now comes from a predicate shared with injectAmneziawgEgress itself, with a test that pins the two together -- naming one tag too few doubles the traffic again, one too many makes real traffic vanish. * fix(amneziawg): align the three .conf emitters on one peer field order The panel builds an AmneziaWG client .conf in three independent places, and they disagreed: buildAmneziaWGClientConfig put PresharedKey right after PublicKey (wg-quick(8)'s own order, and what both WireGuard emitters on the clients side already use), while genAmneziaWGConfig and the Go amneziaWGConfigText put it after Endpoint. A user comparing a subscription link against a downloaded .conf sees the difference immediately, and the generators are exactly the kind of parallel implementation CLAUDE.md warns about drifting. Moves the two outliers onto the wg-quick order. Also drops the stray trailing newline that only appeared when PersistentKeepalive was set, so a config now always ends on its last set field whichever that is -- the same shape all three emitters produce for the same client. Parsing is unaffected either way (the format is order-insensitive, and the AmneziaVPN app reads it as a flat key-value bag), so this changes only the rendered text. Adds a test on each side that pins the peer block's field order, since nothing previously asserted it. * refactor(amneziawg): switch to the embedded amneziawg-go/gVisor architecture Replaces the kernel-module (DKMS) + awg-quick + TPROXY backend with the fork's own embedded design: amneziawg-go runs in-process over a userspace gVisor netstack, and each peer's decapsulated traffic relays into its own loopback Xray SOCKS5 inbound, so Xray's native stats/sniffing/routing work for free instead of through hand-rolled bridges. No kernel module, no DKMS, no Secure Boot conflicts, works the same in a container as on bare metal. - internal/amneziawgnet: new package (Device/UAPI, gVisor netstack, TCP/UDP forwarding, SOCKS5 relay, peer identity, IPv6 host-alias egress identity, per-client port-forwarding) - amneziawg-go v3.1.20260814 + gvisor. - internal/amneziawg: keep the reusable protocol-shape types/validation (Instance/Peer/Obfuscation, InstanceFromInbound); drop the OS-shellout half (awg-quick, TPROXY policy routing, NDP proxy, peer-stats parsing). - internal/web/service: rewire the 5 integration points (job, runtime, client-apply, web shutdown, xray config) from the old manager to the new one; the AmneziaWG log view is rebuilt on the embedded Device's own UAPI dump (extended to carry endpoint/AllowedIPs) instead of `awg show dump`. - install.sh: drop DKMS/ndppd/TPROXY/Secure-Boot installer code (~250 lines) - an entire recurring class of installer fragility goes away. - frontend: drop the now-meaningless routeThroughXray toggle (the relay is always on); keep the field in the Zod schema, unexposed, so it isn't silently stripped from stored settings on next save - two regression tests deliberately depend on the Go struct still carrying it. - docs/i18n: rewrite amneziawg.mdx for the new architecture; drop the dead routeThroughXray translation keys across all 13 locales. Real production throughput (embedded core datapath, isolated bench, same box the kernel-module path was measured on): ~296 Mbit/s up, ~640 Mbit/s down, vs. 414.69 MB/s (~3.3 Gbit/s) for the kernel module on the same hardware - a real gap, tempered by this being single-stream/no-SOCKS5-hop and most VPN traffic being latency-bound rather than throughput-saturating. * fix(amneziawg): restore the branch's own Obfuscation31 shape + 2 CodeQL findings The previous push's wholesale-copy of types.go/params.go from the fork's main branch pulled in that branch's own independent (and incompatible) naming for the same AWG 3.1 feature set: Obfuscation20/GenerateObfuscation20 instead of this branch's already-shipped Obfuscation31/GenerateObfuscation31, and a missing CanonicalizeUintRange -- broke every Go CI job (the whole matrix fails to compile when any one package doesn't, which is why govulncheck/ golangci/postgres-durable-first/race all failed identically, not just go-test). Restores params.go/params_test.go verbatim from this branch's own last commit (a strict superset of validation: it already cross-checks rekey vs. reject timing windows, which the copied version never did) and folds the 3.0/3.1 fields (HeaderProtectionKey, ContentPaddingAddition, the 5 timing fields, RandomTrailers/DisableCookies) into Obfuscation31 itself, matching the original struct exactly instead of as separate top-level Instance fields. instance.go, the two amneziawgnet call sites, and 7 amneziawgnet test files updated to match. Also drops the one test (sanitizeConfigValue) that only ever served the retired kernel-module .conf writer -- correctly not ported, so the test testing it shouldn't have been copied either. Also fixes 2 CodeQL findings the same push surfaced: a clamped uint64->int64 conversion for the new log view's live byte counters (server.go), and an unneeded len+len sum feeding a slice pre-size in the v6-egress outbound merge (xray.go) -- append already grows correctly without it. * chore(amneziawg): regenerate frontend schemas for updated doc comments npm run gen was missed after the previous commit's types.go doc-comment edits (Obfuscation20 -> Obfuscation31, ValidateHeaderProtection -> ValidateObfuscation in the prose) -- openapigen bakes those comments into the generated schema's description field, so the committed frontend/src/generated/schemas.ts and openapi.json still had the old wording. codegen's git-diff-exit-code check caught it correctly. * fix(amneziawg): narrow 2 test fixtures that collided with MaxForwardedPorts TestCheckForwardedPortsConflict_CollidesWithEnabledInboundPort and ..._NoCollisionWhenPortsDontOverlap used "8000-8100"/"9000-9100" as their ForwardedPorts fixture -- 101 ports each, one over MaxForwardedPorts (100). The cap check (checkForwardedPortsConflict, added this session alongside the SOCKS-phantom-port check) fires first, so both tests got "more than 100 forwarded ports" instead of ever reaching the collision logic they're actually testing. The cap itself has its own dedicated boundary test already; these two just needed a narrower range that still covers/misses port 8080 as intended -- 8075-8085 and 9075-9085, 11 ports each. * fix(amneziawg): checkAmneziawgnetSocksConflict had no receiver in its new home My merge-conflict resolution kept this as a method call (s.checkAmneziawgnetSocksConflict) inside checkPortConflictTx, a plain function with no *InboundService receiver -- upstream's #6225 fix moved the port-conflict check out of the (s *InboundService) method and into this new tx-scoped free function, and I didn't notice the call site needed to change shape too. CI caught it immediately (undefined: s); nothing in this specific package can be locally verified past internal/database's own unrelated, pre-existing CGO build issue on this dev machine. Since the signature had to change either way, folded in the fix already flagged as a separate follow-up: checkAmneziawgnetSocksConflict now takes the caller's db handle instead of fetching its own via database.GetDB(), so it actually runs inside the same serialized transaction #6225 introduced -- previously it sat right next to that race fix without benefiting from it. * fix: address the review findings on the embedded AmneziaWG PR 5 blocking findings: - Floor S3/S4 at 12 in both obfuscation generators (Go and frontend) and reject a hand-edited value below that when HeaderProtectionKey is set -- IpcSet requires it, and ~39% of previously-generated sets violated it silently. - Guard PrivateKey/PrimaryDNS/SecondaryDNS/remark against newline injection in the AmneziaWG .conf builder (both the Go subscription-link path and the frontend downloadable-config path) -- unguarded, any of them could inject an arbitrary config line into a subscriber's client. - Bound the derived AmneziaWG SOCKS relay port to <= 65535 once an inbound's id is known, and check the reverse direction (does the relay port collide with an existing inbound's port) on both create and update -- previously only port -> relay collisions were checked, not relay -> port. - Gate injectAmneziawgV6Egress on the same V6AliasesActive predicate desiredV6Aliases already uses, so the two can't disagree about whether a peer's IPv6 identity is actually active at the OS level. 2 minor findings: - Fix the forwarded-ports cap check's off-by-one (a spec covering exactly the cap was rejected as if it were over it). - Correct docker-compose.yml's stale comment describing the retired DKMS/kernel-module architecture. * chore: retrigger CI build (armv5) failed on a transient Go module proxy network error (INTERNAL_ERROR stream reset on sagernet/sing), unrelated to this PR's changes. * docs: fix doc comments still describing the retired DKMS/awg-quick design A few doc comments (and one illustrative test log line) survived the embedded-architecture cutover unchanged and now contradict the code they sit next to: - internal/amneziawg/types.go's package comment claimed this package still owns a Manager that reconciles OS-level interfaces via awg-quick/DKMS -- that Manager was removed; the reconcile loop lives in internal/amneziawgnet now, and this package is protocol-shape-only. - internal/amneziawg/params.go's ValidateObfuscation/ValidateConfigValue comments cited "awg-quick up" / "awg-quick executes as root" as the reason to validate -- the server itself never calls awg-quick in this architecture; the same value still reaches a real rendered .conf that a client app or an admin's own awg-quick CLI applies downstream, so the validation is still warranted, just for a different consumer. Mirrored the same fix in inbound_amneziawg.go's matching comment and its test's comment. - internal/amneziawgnet/manager.go's Manager doc comments (x3) pointed readers at "internal/amneziawg.Manager" for comparison -- that type no longer exists in this diff at all. Repointed at internal/mtproto.Manager, the pattern this was actually modeled on and the one that's still real. - Swapped one test's illustrative "awg-quick up awg2 failed" log line for a message shaped like this architecture's actual amneziawgnet logging, so a reader skimming the test doesn't wonder whether the server still shells out to awg-quick. No behavior change. * fix(docs): re-run codegen for xray-settings.mdx after conflict merge The automated conflict-resolution hand-merge for this generated file was content-correct but didn't byte-match a real regen (different YAML long-string folding style). Re-ran npm run gen + docs' gen:api and kept that canonical output instead. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(amneziawg): drop the dead access-log email backfill amneziawgEmailIndex keyed peers by "<tag>|<tunnel IP>", a scheme built for the retired TPROXY bridge where the peer's decapsulated tunnel address survived as the access log's from-address. The embedded architecture relays through a loopback SOCKS5 dial, so every AmneziaWG log line's from-address is 127.0.0.1:<ephemeral> and the lookup could never match: the index was rebuilt on every log view just to miss. Remove the index, its GetXrayLogs wiring and its test. If per-line emails are wanted back, the relay would have to publish a local-port->email registry for the viewer to resolve loopback sources. * fix(api): generate AmneziaWGLogs/PeerActivity schemas instead of hand-writing them The amneziawglogs endpoint's response structs were missing from openapigen's StructAllow, so they were silently absent from every generated schema/example, the endpoints.ts entry carried a hand-written response, and AmneziaWGLogModal.tsx duplicated the shapes as local interfaces - the exact drift the allowlist rule exists to prevent. Allowlist both structs with example tags, point the endpoint at the generated schema, import the generated types in the modal, and sync docs/public/openapi.json. * chore(amneziawg): drop the unreferenced quiccapture package Nothing imports internal/amneziawg/quiccapture and no route exposes it; its package doc justifies the code as a port of frontend/src/lib/xray/i1Generators.ts, which does not exist in this repository, and promises an API round-trip that also does not exist. 1,110 lines of unreachable code with misleading provenance claims. Revert this commit to bring the package back when the live-capture I1 feature and its frontend counterpart actually land. * fix(clients): re-run cross-inbound conflict checks on the serialized writer The new client-level checks - cross-inbound AllowedIPs collisions and AmneziaWG forwardedPorts conflicts - read a fresh DB snapshot, decide, and only then enter runSerializedTx, while lockInbound only serializes writers on the SAME inbound. Two concurrent client creates on two different tunnel inbounds both passed the read and both committed, yielding two peers with one address: the exact check-then-claim race81cfd857(#6225) closed for AddInbound, which this PR's own checkAmneziawgnetSocksReverseConflict already cites. Keep the pre-tx pass for fail-fast UX and re-validate inside the transaction, where the single writer makes the answer authoritative. The race test drives two goroutines at two inbounds and demands exactly one winner; it fails with committed=2 when the in-tx re-check is removed. * fix(amneziawg): hot-apply depletion disables like mtproto does applyTrafficMutationBatch special-cases MTProto so a quota/expiry depletion cuts the sidecar immediately, but AmneziaWG fell through to runtime AddUser/RemoveUser - explicit no-ops for this protocol - so a depleted peer kept tunneling until the next 10s reconcile tick. Route it through applyLocalAmneziaWG, whose own contract (re-read committed settings, filter depleted clients, push to the interface) is exactly this case; the comment claiming it mirrors applyLocalMtproto is now true for the depletion path too. * fix(amneziawg): persist cleared DNS fields instead of resurrecting defaults PrimaryDNS/SecondaryDNS marshaled with omitempty, so clearing them persisted settings with no key at all - and the frontend re-parses stored settings through a Zod schema whose .default('8.8.8.8') / .default('8.8.4.4') fire on missing keys, silently repopulating the form on every load and re-persisting the defaults on the next save. Blank is a documented, meaningful state (no DNS line in client configs); drop omitempty so a cleared value survives the round-trip. The regression test normalizes a server block with cleared DNS and fails when the keys are dropped. * fix(amneziawg): accept cleared numeric obfuscation/subnet fields in the form AntD InputNumber emits null when cleared, Zod .default() only replaces undefined, and unlike wireguard.ts - whose optionalClearedInt comment documents exactly this failure mode - the AmneziaWG schema declared subnetCidr and jc/jmin/jmax/s1-s4 as bare z.number() defaults. Clearing any of the eight fields made safeParse reject the null and block the save until the user retyped a value. Absorb null into undefined while keeping each field's schema default, so a cleared field refills its documented default and legacy blobs with absent keys behave as before. * fix(amneziawg): guard the third .conf emitter against newline injection The review-round fix added the newline guard to amneziaWGConfigText (Go) and buildAmneziaWGClientConfig, but genAmneziaWGConfig in inbound-link.ts - the third of the three emitters its own comment says must not drift - still rendered privateKey/primaryDns/secondaryDns/remark unescaped, so a newline there injected a config line (e.g. a rogue PostUp) into the inbound form's downloaded .conf. Add the same guard, plus the regression tests the original fix shipped without: all four fields on the Go and both frontend emitters go red if any guard is removed. * test(amneziawg): pin the S3/S4 floors the TS drift guard claims to mirror The test's docstring says it mirrors internal/amneziawg/params_test.go, but it asserted S3>=8/S4>=4 while the Go test and both generators pin 12/12 - the floor ValidateObfuscation enforces whenever a header protection key is set, which this generator always sets. A regression narrowing the TS floors into 8-11/4-11 would have passed the drift guard and produced configs the backend rejects on save. * docs: restore the pia repo-map entry and document the AmneziaWG subsystem Merging main dropped CLAUDE.md's internal/pia/ bullet (added by #6272) while resolving the repo-map conflict - the package itself is untouched. Restore it, add the missing map entries for the two packages this branch introduces (internal/amneziawg/, internal/amneziawgnet/), bump the cron count, and give amneziawg_job its row in architecture.md's 5.4 table. * chore(amneziawg): correct comments stranded by the architecture pivot ae77c7e9's cutover to the embedded gVisor path deleted the kernel-module code but left several comments describing it in the present tense: hot_diff.go cited the removed service.amneziawgEgressStreamSettings and wrongly claimed AmneziaWG is the only sockopt.tproxy source (tunnel's TProxy mode is the live one the guard protects), socks_config.go pointed at the deleted EgressBasePort/EgressPortForInbound, manager.go referred to the deleted Manager and its fingerprinting as live code, web.go's cron registration claimed the job scrapes traffic (its own doc says it does not), and types.go capped ContentPaddingAddition at uint16 when validation and upstream both use uint32. * style(lint): satisfy gofumpt/goimports so make verify is green json_service.go's two 'Tag: "proxy"}' literals came in with main's owncc245a90formatting commit and fail the repo's gofumpt gate for everyone; the import grouping in inbound_amneziawg.go is from the serialized-writer fix on this branch. --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com> Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
This commit is contained in:
@@ -127,11 +127,16 @@ func (a *ClientController) buildClientPayload(rec *model.ClientRecord) (gin.H, e
|
||||
if t, tErr := a.inboundService.GetClientTrafficByEmail(rec.Email); tErr == nil && t != nil {
|
||||
usedTraffic = t.Up + t.Down
|
||||
}
|
||||
tunnelAllowedIPs, err := a.clientService.TunnelAllowedIPsByInbound(&a.inboundService, rec.Email, inboundIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return gin.H{
|
||||
"client": rec,
|
||||
"inboundIds": inboundIds,
|
||||
"externalLinks": externalLinks,
|
||||
"usedTraffic": usedTraffic,
|
||||
"client": rec,
|
||||
"inboundIds": inboundIds,
|
||||
"externalLinks": externalLinks,
|
||||
"usedTraffic": usedTraffic,
|
||||
"tunnelAllowedIPs": tunnelAllowedIPs,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -74,6 +74,7 @@ func (a *ServerController) initRouter(g *gin.RouterGroup) {
|
||||
g.POST("/updateGeofile/:fileName", a.updateGeofile)
|
||||
g.POST("/logs/:count", a.getLogs)
|
||||
g.POST("/xraylogs/:count", a.getXrayLogs)
|
||||
g.POST("/amneziawglogs/:count", a.getAmneziaWGLogs)
|
||||
g.POST("/importDB", a.importDB)
|
||||
g.POST("/getNewEchCert", a.getNewEchCert)
|
||||
g.POST("/getCertHash", a.getCertHash)
|
||||
@@ -320,6 +321,13 @@ func (a *ServerController) getXrayLogs(c *gin.Context) {
|
||||
jsonObj(c, logs, nil)
|
||||
}
|
||||
|
||||
// getAmneziaWGLogs retrieves the live AmneziaWG peer activity and the panel's
|
||||
// own AmneziaWG event lines, optionally narrowed by a free-text filter.
|
||||
func (a *ServerController) getAmneziaWGLogs(c *gin.Context) {
|
||||
logs := a.serverService.GetAmneziaWGLogs(c.Param("count"), c.PostForm("filter"))
|
||||
jsonObj(c, logs, nil)
|
||||
}
|
||||
|
||||
// getConfigJson retrieves the Xray configuration as JSON.
|
||||
func (a *ServerController) getConfigJson(c *gin.Context) {
|
||||
configJson, err := a.serverService.GetConfigJson()
|
||||
|
||||
Vendored
@@ -0,0 +1,55 @@
|
||||
package job
|
||||
|
||||
import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
)
|
||||
|
||||
// AmneziaWGJob reconciles the running embedded AmneziaWG interfaces
|
||||
// (internal/amneziawgnet -- amneziawg-go over a gVisor netstack, no kernel
|
||||
// module) against the enabled AmneziaWG inbounds in the database,
|
||||
// rebuilding/reconfiguring any that drifted. Unlike the retired
|
||||
// kernel-module Manager this job used to drive, there is no traffic/
|
||||
// online-status accounting here at all: once a peer's decapsulated traffic
|
||||
// is relayed into Xray's own SOCKS5 inbound (see
|
||||
// internal/web/service/xray.go's injectAmneziawgnetSocks, and
|
||||
// internal/amneziawgnet.Manager's automatic forwarder/relay wiring), it's
|
||||
// an ordinary Xray user, and XrayTrafficJob's existing, protocol-blind
|
||||
// stats/online-status polling already picks it up for free.
|
||||
type AmneziaWGJob struct {
|
||||
inboundService service.InboundService
|
||||
}
|
||||
|
||||
// NewAmneziaWGJob creates a new AmneziaWG reconcile job instance.
|
||||
func NewAmneziaWGJob() *AmneziaWGJob {
|
||||
return new(AmneziaWGJob)
|
||||
}
|
||||
|
||||
// Run reconciles desired AmneziaWG inbounds with running embedded interfaces.
|
||||
func (j *AmneziaWGJob) Run() {
|
||||
desired, err := j.inboundService.DesiredAmneziaWGInstances()
|
||||
if err != nil {
|
||||
logger.Warning("amneziawg job: get desired instances failed:", err)
|
||||
return
|
||||
}
|
||||
|
||||
wanted := make([]amneziawgnet.Desired, 0, len(desired))
|
||||
for _, inst := range desired {
|
||||
wanted = append(wanted, amneziawgnet.Desired{
|
||||
Instance: inst,
|
||||
Options: amneziawgnet.DeviceOptions{
|
||||
HeaderProtectionKey: inst.Obfuscation.HeaderProtectionKey,
|
||||
ContentPaddingAddition: inst.Obfuscation.ContentPaddingAddition,
|
||||
RekeyAfterTime: inst.Obfuscation.RekeyAfterTime,
|
||||
RekeyTimeout: inst.Obfuscation.RekeyTimeout,
|
||||
RejectAfterTime: inst.Obfuscation.RejectAfterTime,
|
||||
KeepaliveTimeout: inst.Obfuscation.KeepaliveTimeout,
|
||||
MaxHandshakeAttempts: inst.Obfuscation.MaxHandshakeAttempts,
|
||||
RandomTrailers: inst.Obfuscation.RandomTrailers,
|
||||
DisableCookies: inst.Obfuscation.DisableCookies,
|
||||
},
|
||||
})
|
||||
}
|
||||
amneziawgnet.GetManager().Reconcile(wanted)
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/mtproto"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
@@ -53,6 +55,35 @@ func (l *Local) AddInbound(_ context.Context, ib *model.Inbound) error {
|
||||
}
|
||||
return mtproto.GetManager().Ensure(inst)
|
||||
}
|
||||
if ib.Protocol == model.AmneziaWG {
|
||||
inst, ok := amneziawg.InstanceFromInbound(ib)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
err := amneziawgnet.GetManager().Ensure(amneziawgnet.Desired{
|
||||
Instance: inst,
|
||||
Options: amneziawgnet.DeviceOptions{
|
||||
HeaderProtectionKey: inst.Obfuscation.HeaderProtectionKey,
|
||||
ContentPaddingAddition: inst.Obfuscation.ContentPaddingAddition,
|
||||
RekeyAfterTime: inst.Obfuscation.RekeyAfterTime,
|
||||
RekeyTimeout: inst.Obfuscation.RekeyTimeout,
|
||||
RejectAfterTime: inst.Obfuscation.RejectAfterTime,
|
||||
KeepaliveTimeout: inst.Obfuscation.KeepaliveTimeout,
|
||||
MaxHandshakeAttempts: inst.Obfuscation.MaxHandshakeAttempts,
|
||||
RandomTrailers: inst.Obfuscation.RandomTrailers,
|
||||
DisableCookies: inst.Obfuscation.DisableCookies,
|
||||
},
|
||||
})
|
||||
// A brand new inbound can be the first one to qualify for
|
||||
// injectAmneziawgnetSocks's Xray-side relay inbound (e.g. its first
|
||||
// valid peer). Ensure only updates the embedded Device -- flag Xray
|
||||
// for a resync so the relay actually gets created within the next
|
||||
// ApplyPendingRestart tick instead of only at the next full restart.
|
||||
if l.deps.SetNeedRestart != nil {
|
||||
l.deps.SetNeedRestart()
|
||||
}
|
||||
return err
|
||||
}
|
||||
body, err := json.MarshalIndent(ib.GenXrayInboundConfig(), "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -67,6 +98,16 @@ func (l *Local) DelInbound(_ context.Context, ib *model.Inbound) error {
|
||||
mtproto.GetManager().Remove(ib.Id)
|
||||
return nil
|
||||
}
|
||||
if ib.Protocol == model.AmneziaWG {
|
||||
amneziawgnet.GetManager().Remove(ib.Id)
|
||||
// The removed inbound may have been the only one backing Xray's
|
||||
// injectAmneziawgnetSocks relay inbound for this tag -- flag a
|
||||
// resync so the now-stale relay gets torn down promptly.
|
||||
if l.deps.SetNeedRestart != nil {
|
||||
l.deps.SetNeedRestart()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return l.withAPI(func(api *xray.XrayAPI) error {
|
||||
return api.DelInbound(ib.Tag)
|
||||
})
|
||||
@@ -76,6 +117,9 @@ func (l *Local) UpdateInbound(ctx context.Context, oldIb, newIb *model.Inbound)
|
||||
if oldIb.Protocol == model.MTProto || newIb.Protocol == model.MTProto {
|
||||
return l.updateMtprotoInbound(ctx, oldIb, newIb)
|
||||
}
|
||||
if oldIb.Protocol == model.AmneziaWG || newIb.Protocol == model.AmneziaWG {
|
||||
return l.updateAmneziaWGInbound(ctx, oldIb, newIb)
|
||||
}
|
||||
_ = l.DelInbound(ctx, oldIb)
|
||||
if !newIb.Enable {
|
||||
return nil
|
||||
@@ -112,8 +156,61 @@ func (l *Local) updateMtprotoInbound(ctx context.Context, oldIb, newIb *model.In
|
||||
return mtproto.GetManager().Ensure(inst)
|
||||
}
|
||||
|
||||
// updateAmneziaWGInbound mirrors updateMtprotoInbound: it skips the
|
||||
// Remove+Ensure sequence a plain Del+Add would force so that, on an
|
||||
// AmneziaWG-to-AmneziaWG edit, Manager.Ensure's own fingerprint comparison
|
||||
// can reconfigure the running embedded Device in place via IpcSet instead
|
||||
// of always rebuilding it (see internal/amneziawgnet.Manager.ensureLocked --
|
||||
// only an address/MTU change forces a rebuild there, not a peer edit).
|
||||
//
|
||||
// Every exit path below only touches the embedded Device via
|
||||
// amneziawgnet.GetManager() -- none of it rebuilds Xray's own config, which
|
||||
// is what actually creates/removes injectAmneziawgnetSocks's relay inbound.
|
||||
// A peer edit that changes whether this inbound has a qualifying peer at
|
||||
// all (its first peer added, or its last one removed) must still get that
|
||||
// relay created or torn down, so flag Xray for a resync unconditionally
|
||||
// here rather than trying to enumerate which of the branches below need it.
|
||||
func (l *Local) updateAmneziaWGInbound(ctx context.Context, oldIb, newIb *model.Inbound) error {
|
||||
if l.deps.SetNeedRestart != nil {
|
||||
l.deps.SetNeedRestart()
|
||||
}
|
||||
if oldIb.Protocol == model.AmneziaWG && newIb.Protocol != model.AmneziaWG {
|
||||
amneziawgnet.GetManager().Remove(oldIb.Id)
|
||||
if !newIb.Enable {
|
||||
return nil
|
||||
}
|
||||
return l.AddInbound(ctx, newIb)
|
||||
}
|
||||
if oldIb.Protocol != model.AmneziaWG {
|
||||
_ = l.DelInbound(ctx, oldIb)
|
||||
}
|
||||
if !newIb.Enable {
|
||||
amneziawgnet.GetManager().Remove(newIb.Id)
|
||||
return nil
|
||||
}
|
||||
inst, ok := amneziawg.InstanceFromInbound(newIb)
|
||||
if !ok {
|
||||
amneziawgnet.GetManager().Remove(newIb.Id)
|
||||
return nil
|
||||
}
|
||||
return amneziawgnet.GetManager().Ensure(amneziawgnet.Desired{
|
||||
Instance: inst,
|
||||
Options: amneziawgnet.DeviceOptions{
|
||||
HeaderProtectionKey: inst.Obfuscation.HeaderProtectionKey,
|
||||
ContentPaddingAddition: inst.Obfuscation.ContentPaddingAddition,
|
||||
RekeyAfterTime: inst.Obfuscation.RekeyAfterTime,
|
||||
RekeyTimeout: inst.Obfuscation.RekeyTimeout,
|
||||
RejectAfterTime: inst.Obfuscation.RejectAfterTime,
|
||||
KeepaliveTimeout: inst.Obfuscation.KeepaliveTimeout,
|
||||
MaxHandshakeAttempts: inst.Obfuscation.MaxHandshakeAttempts,
|
||||
RandomTrailers: inst.Obfuscation.RandomTrailers,
|
||||
DisableCookies: inst.Obfuscation.DisableCookies,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (l *Local) AddUser(_ context.Context, ib *model.Inbound, userMap map[string]any) error {
|
||||
if ib.Protocol == model.MTProto {
|
||||
if ib.Protocol == model.MTProto || ib.Protocol == model.AmneziaWG {
|
||||
return nil
|
||||
}
|
||||
return l.withAPI(func(api *xray.XrayAPI) error {
|
||||
@@ -122,7 +219,7 @@ func (l *Local) AddUser(_ context.Context, ib *model.Inbound, userMap map[string
|
||||
}
|
||||
|
||||
func (l *Local) RemoveUser(_ context.Context, ib *model.Inbound, email string) error {
|
||||
if ib.Protocol == model.MTProto {
|
||||
if ib.Protocol == model.MTProto || ib.Protocol == model.AmneziaWG {
|
||||
return nil
|
||||
}
|
||||
return l.withAPI(func(api *xray.XrayAPI) error {
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
||||
wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
|
||||
)
|
||||
|
||||
// defaultAmneziaWGSubnetBases resolves the /CIDR bases new peer addresses are
|
||||
// allocated from, out of the inbound's own configured server subnet(s) —
|
||||
// unlike WireGuard, which always falls back to a fixed 10.0.0.0/24. v6Base is
|
||||
// "" when the server doesn't have IPv6 enabled.
|
||||
func defaultAmneziaWGSubnetBases(settingsJSON string) (v4Base, v6Base string, err error) {
|
||||
var parsed amneziawg.InboundSettings
|
||||
if err := json.Unmarshal([]byte(settingsJSON), &parsed); err != nil {
|
||||
return "", "", fmt.Errorf("amneziawg: invalid settings: %w", err)
|
||||
}
|
||||
if parsed.Server == nil {
|
||||
return "", "", fmt.Errorf("amneziawg: settings missing server block")
|
||||
}
|
||||
cidr := parsed.Server.SubnetCIDR
|
||||
if cidr <= 0 {
|
||||
cidr = 24
|
||||
}
|
||||
v4Base = fmt.Sprintf("%s/%d", parsed.Server.SubnetIP, cidr)
|
||||
if parsed.Server.IPv6Enabled && parsed.Server.IPv6Subnet != "" {
|
||||
v6Base = parsed.Server.IPv6Subnet
|
||||
}
|
||||
return v4Base, v6Base, nil
|
||||
}
|
||||
|
||||
// defaultAmneziaWGClients fills in blank credentials and a free tunnel address
|
||||
// for new clients, mutating both the typed clients and the parallel raw maps
|
||||
// persisted into the settings. Existing values are never overwritten, so an
|
||||
// edit never rotates keys. Mirrors defaultWireguardClients; crossInboundUsed
|
||||
// (see otherTunnelAllowedIPs) narrows which addresses are still free.
|
||||
func defaultAmneziaWGClients(settingsJSON string, existing, clients []model.Client, interfaceClients []any, crossInboundUsed map[string]string) error {
|
||||
v4Base, v6Base, err := defaultAmneziaWGSubnetBases(settingsJSON)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
used := make([]string, 0)
|
||||
for i := range existing {
|
||||
used = append(used, existing[i].AllowedIPs...)
|
||||
}
|
||||
for addr := range crossInboundUsed {
|
||||
used = append(used, addr)
|
||||
}
|
||||
for i := range clients {
|
||||
c := &clients[i]
|
||||
if c.PrivateKey == "" && c.PublicKey == "" {
|
||||
priv, pub, err := wgutil.GenerateWireguardKeypair()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.PrivateKey = priv
|
||||
c.PublicKey = pub
|
||||
} else if c.PublicKey == "" && c.PrivateKey != "" {
|
||||
pub, err := wgutil.PublicKeyFromPrivate(c.PrivateKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.PublicKey = pub
|
||||
}
|
||||
if len(c.AllowedIPs) == 0 {
|
||||
// allowWidening=false: unlike WireGuard's Xray-native inbound,
|
||||
// AmneziaWG's kernel interface Address is exactly the configured
|
||||
// subnet, so an address allocated outside it would be silently
|
||||
// unroutable. Exhaustion here must fail loudly instead.
|
||||
addr, err := allocateWireguardAddress(used, v4Base, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
allowed := []string{addr}
|
||||
if v6Base != "" {
|
||||
addr6, err := allocateWireguardAddress(used, v6Base, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
allowed = append(allowed, addr6)
|
||||
}
|
||||
c.AllowedIPs = allowed
|
||||
} else {
|
||||
normalized, err := normalizeWireguardAllowedIPs(c.AllowedIPs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(normalized) == 0 {
|
||||
return common.NewError("amneziawg: allowedIPs has no usable entry")
|
||||
}
|
||||
if hit := wireguardAllowedIPsCollision(normalized, used); hit != "" {
|
||||
if where := crossInboundUsed[hit]; where != "" {
|
||||
return common.NewError("amneziawg: allowedIPs entry", hit, "is already used by a client on", where)
|
||||
}
|
||||
return common.NewError("amneziawg: allowedIPs entry already used by another client:", hit)
|
||||
}
|
||||
c.AllowedIPs = normalized
|
||||
}
|
||||
used = append(used, c.AllowedIPs...)
|
||||
|
||||
if i < len(interfaceClients) {
|
||||
if m, ok := interfaceClients[i].(map[string]any); ok {
|
||||
m["privateKey"] = c.PrivateKey
|
||||
m["publicKey"] = c.PublicKey
|
||||
m["allowedIPs"] = c.AllowedIPs
|
||||
if c.PreSharedKey != "" {
|
||||
m["preSharedKey"] = c.PreSharedKey
|
||||
}
|
||||
interfaceClients[i] = m
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
// AmneziaWG's own kernel interface Address is exactly the configured
|
||||
// subnet (unlike WireGuard's Xray-native inbound), so allocation for it must
|
||||
// never widen past that subnet -- an address from outside it would be
|
||||
// silently unroutable. See PR #6105 Finding 12.
|
||||
func TestAllocateWireguardAddress_AmneziaWGNeverWidens(t *testing.T) {
|
||||
used := make([]string, 0, 254)
|
||||
for i := 2; i <= 255; i++ {
|
||||
used = append(used, fmt.Sprintf("10.8.1.%d/32", i))
|
||||
}
|
||||
if _, err := allocateWireguardAddress(used, "10.8.1.0/24", false); err == nil {
|
||||
t.Fatal("a full AmneziaWG /24 must fail loudly instead of allocating an address outside the interface's own subnet")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllocateWireguardAddress_AmneziaWGFillsItsOwnSubnetNormally(t *testing.T) {
|
||||
got, err := allocateWireguardAddress([]string{"10.8.1.2/32"}, "10.8.1.0/24", false)
|
||||
if err != nil {
|
||||
t.Fatalf("allocateWireguardAddress: %v", err)
|
||||
}
|
||||
if got != "10.8.1.3/32" {
|
||||
t.Fatalf("address = %q, want 10.8.1.3/32", got)
|
||||
}
|
||||
}
|
||||
|
||||
const amneziawgClientTestSettings = `{"server":{"subnetIp":"10.8.1.0","subnetCidr":24}}`
|
||||
|
||||
func TestDefaultAmneziaWGSubnetBases(t *testing.T) {
|
||||
v4, v6, err := defaultAmneziaWGSubnetBases(amneziawgClientTestSettings)
|
||||
if err != nil {
|
||||
t.Fatalf("defaultAmneziaWGSubnetBases: %v", err)
|
||||
}
|
||||
if v4 != "10.8.1.0/24" {
|
||||
t.Fatalf("v4Base = %q, want 10.8.1.0/24", v4)
|
||||
}
|
||||
if v6 != "" {
|
||||
t.Fatalf("v6Base = %q, want empty when IPv6 is not enabled", v6)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultAmneziaWGSubnetBasesIncludesIPv6WhenEnabled(t *testing.T) {
|
||||
settings := `{"server":{"subnetIp":"10.8.1.0","subnetCidr":24,"ipv6Enabled":true,"ipv6Subnet":"fd00::/64"}}`
|
||||
v4, v6, err := defaultAmneziaWGSubnetBases(settings)
|
||||
if err != nil {
|
||||
t.Fatalf("defaultAmneziaWGSubnetBases: %v", err)
|
||||
}
|
||||
if v4 != "10.8.1.0/24" || v6 != "fd00::/64" {
|
||||
t.Fatalf("got v4=%q v6=%q", v4, v6)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultAmneziaWGSubnetBasesRejectsMissingServer(t *testing.T) {
|
||||
if _, _, err := defaultAmneziaWGSubnetBases(`{}`); err == nil {
|
||||
t.Fatal("expected an error when the settings have no server block")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultAmneziaWGClientsGeneratesKeypairAndAllocatesFromOwnSubnet(t *testing.T) {
|
||||
clients := []model.Client{{Email: "a@awg"}}
|
||||
ifaces := []any{map[string]any{"email": "a@awg"}}
|
||||
if err := defaultAmneziaWGClients(amneziawgClientTestSettings, nil, clients, ifaces, nil); err != nil {
|
||||
t.Fatalf("defaultAmneziaWGClients: %v", err)
|
||||
}
|
||||
c := clients[0]
|
||||
if c.PrivateKey == "" || c.PublicKey == "" {
|
||||
t.Fatalf("keypair not generated: priv=%q pub=%q", c.PrivateKey, c.PublicKey)
|
||||
}
|
||||
if len(c.AllowedIPs) != 1 || c.AllowedIPs[0] != "10.8.1.2/32" {
|
||||
t.Fatalf("allowedIPs not allocated from the inbound's own subnet: %v", c.AllowedIPs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultAmneziaWGClientsPreservesProvided(t *testing.T) {
|
||||
clients := []model.Client{{
|
||||
Email: "b@awg",
|
||||
PrivateKey: "keep-priv",
|
||||
PublicKey: "keep-pub",
|
||||
AllowedIPs: []string{"10.8.1.50/32"},
|
||||
}}
|
||||
ifaces := []any{map[string]any{"email": "b@awg"}}
|
||||
if err := defaultAmneziaWGClients(amneziawgClientTestSettings, nil, clients, ifaces, nil); err != nil {
|
||||
t.Fatalf("defaultAmneziaWGClients: %v", err)
|
||||
}
|
||||
if clients[0].PrivateKey != "keep-priv" || clients[0].PublicKey != "keep-pub" {
|
||||
t.Fatalf("provided keys were rotated: %+v", clients[0])
|
||||
}
|
||||
if clients[0].AllowedIPs[0] != "10.8.1.50/32" {
|
||||
t.Fatalf("provided allowedIPs changed: %v", clients[0].AllowedIPs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultAmneziaWGClientsRejectsSameInboundDuplicate(t *testing.T) {
|
||||
existing := []model.Client{{Email: "old@awg", AllowedIPs: []string{"10.8.1.9/32"}}}
|
||||
dup := []model.Client{{Email: "new@awg", AllowedIPs: []string{"10.8.1.9/32"}}}
|
||||
err := defaultAmneziaWGClients(amneziawgClientTestSettings, existing, dup, []any{map[string]any{"email": "new@awg"}}, nil)
|
||||
if err == nil {
|
||||
t.Fatal("duplicate allowedIPs on the same inbound must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
// The exact real-world scenario that motivated crossInboundUsed: a WireGuard
|
||||
// client and an AmneziaWG peer given the same address by habit. The
|
||||
// collision must be caught even though the two live on different inbounds
|
||||
// and neither appears in the other's own "existing" client list, and the
|
||||
// error should name the other inbound so an admin isn't left guessing.
|
||||
func TestDefaultAmneziaWGClientsRejectsCrossInboundDuplicate(t *testing.T) {
|
||||
crossUsed := map[string]string{"10.8.1.21/32": "inbound 'wg' (#12)"}
|
||||
dup := []model.Client{{Email: "c@awg", AllowedIPs: []string{"10.8.1.21/32"}}}
|
||||
err := defaultAmneziaWGClients(amneziawgClientTestSettings, nil, dup, []any{map[string]any{"email": "c@awg"}}, crossUsed)
|
||||
if err == nil {
|
||||
t.Fatal("allowedIPs already used on another inbound must be rejected")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "inbound 'wg' (#12)") {
|
||||
t.Fatalf("error should name the other inbound holding the address, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultAmneziaWGClientsAutoAllocateSkipsCrossInboundUsed(t *testing.T) {
|
||||
crossUsed := map[string]string{"10.8.1.2/32": "inbound 'other-awg' (#3)"}
|
||||
clients := []model.Client{{Email: "d@awg"}}
|
||||
ifaces := []any{map[string]any{"email": "d@awg"}}
|
||||
if err := defaultAmneziaWGClients(amneziawgClientTestSettings, nil, clients, ifaces, crossUsed); err != nil {
|
||||
t.Fatalf("defaultAmneziaWGClients: %v", err)
|
||||
}
|
||||
if clients[0].AllowedIPs[0] != "10.8.1.3/32" {
|
||||
t.Fatalf("auto-allocation should skip the cross-inbound-used .2 and pick .3, got %v", clients[0].AllowedIPs)
|
||||
}
|
||||
}
|
||||
|
||||
// Unlike WireGuard's allocation base (inferred from existing peers with a
|
||||
// fallback), AmneziaWG's base always comes from the inbound's own configured
|
||||
// subnet -- so this is really confirming crossInboundUsed can never change
|
||||
// which subnet is used, only which addresses within it are free.
|
||||
func TestDefaultAmneziaWGClientsCrossInboundUsedDoesNotChangeBase(t *testing.T) {
|
||||
crossUsed := map[string]string{"192.168.99.5/32": "inbound 'unrelated' (#99)"}
|
||||
clients := []model.Client{{Email: "e@awg"}}
|
||||
ifaces := []any{map[string]any{"email": "e@awg"}}
|
||||
if err := defaultAmneziaWGClients(amneziawgClientTestSettings, nil, clients, ifaces, crossUsed); err != nil {
|
||||
t.Fatalf("defaultAmneziaWGClients: %v", err)
|
||||
}
|
||||
if got := clients[0].AllowedIPs[0]; got != "10.8.1.2/32" {
|
||||
t.Fatalf("base subnet must stay the inbound's own 10.8.1.0/24; got %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
// TestHasTunnelAttachmentDetectsWireguardOrAmneziaWG backs the fix for a
|
||||
// real production bug: Attach copies an identity's stored AllowedIPs into
|
||||
// every inbound it processes (so the same person keeps the same tunnel
|
||||
// address across protocols), but when an identity has been fully detached
|
||||
// from every WireGuard/AmneziaWG inbound, that stored address is a leftover
|
||||
// nothing reserves anymore -- reusing it can skip past address space that's
|
||||
// genuinely free (a real user's own case: address .21 resurrected instead
|
||||
// of the actually-free .3). hasTunnelAttachment is what Attach checks to
|
||||
// decide whether to clear the stored address before its loop, so it needs
|
||||
// to correctly tell "still has an active tunnel elsewhere" (preserve) apart
|
||||
// from "no tunnel attachment at all" (clear, allocate fresh).
|
||||
func TestHasTunnelAttachmentDetectsWireguardOrAmneziaWG(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 443, model.AmneziaWG, ``, `{"server":{"subnetIp":"10.8.1.0","subnetCidr":24},"clients":[]}`)
|
||||
seedInboundConflict(t, "wg-1", "0.0.0.0", 51820, model.WireGuard, ``, `{"clients":[]}`)
|
||||
seedInboundConflict(t, "vless-1", "0.0.0.0", 8443, model.VLESS, `{"network":"tcp"}`, `{"clients":[]}`)
|
||||
|
||||
var awgInbound, wgInbound, vlessInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded awg row: %v", err)
|
||||
}
|
||||
if err := database.GetDB().Where("tag = ?", "wg-1").First(&wgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded wg row: %v", err)
|
||||
}
|
||||
if err := database.GetDB().Where("tag = ?", "vless-1").First(&vlessInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded vless row: %v", err)
|
||||
}
|
||||
|
||||
s := &ClientService{}
|
||||
inboundSvc := &InboundService{}
|
||||
|
||||
if s.hasTunnelAttachment(inboundSvc, nil) {
|
||||
t.Error("empty inboundIds must report no tunnel attachment")
|
||||
}
|
||||
if s.hasTunnelAttachment(inboundSvc, []int{vlessInbound.Id}) {
|
||||
t.Error("a VLESS-only attachment must not count as a tunnel attachment")
|
||||
}
|
||||
if s.hasTunnelAttachment(inboundSvc, []int{99999}) {
|
||||
t.Error("a nonexistent inbound id must not count as a tunnel attachment")
|
||||
}
|
||||
if !s.hasTunnelAttachment(inboundSvc, []int{vlessInbound.Id, wgInbound.Id}) {
|
||||
t.Error("a WireGuard inbound among others must count as a tunnel attachment")
|
||||
}
|
||||
if !s.hasTunnelAttachment(inboundSvc, []int{awgInbound.Id}) {
|
||||
t.Error("an AmneziaWG inbound must count as a tunnel attachment")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAddressesFitAmneziaWGInbound is a regression test for a real
|
||||
// production bug: hasTunnelAttachment only asked "does this identity have
|
||||
// ANY tunnel attachment", not "is the address it would inherit actually
|
||||
// valid for THIS inbound" -- so an identity whose stored address came from
|
||||
// WireGuard's own fallback subnet (10.0.0.0/24, used when that inbound has
|
||||
// no other clients to infer a base from) got that exact address silently
|
||||
// carried over onto a second, AmneziaWG inbound configured for a completely
|
||||
// different subnet (10.8.1.0/24). defaultAmneziaWGClients's already-set
|
||||
// branch only checks for collisions, not subnet membership, so the mismatch
|
||||
// was accepted with no error -- producing a peer that can never actually
|
||||
// connect (an AmneziaWG address must fall inside the kernel interface's own
|
||||
// configured subnet to be routable at all). addressesFitAmneziaWGInbound is
|
||||
// the check Attach now runs per inbound before deciding whether to keep an
|
||||
// inherited address or force a fresh allocation.
|
||||
func TestAddressesFitAmneziaWGInbound(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 443, model.AmneziaWG, ``, `{"server":{"subnetIp":"10.8.1.0","subnetCidr":24},"clients":[]}`)
|
||||
seedInboundConflict(t, "wg-1", "0.0.0.0", 51820, model.WireGuard, ``, `{"clients":[]}`)
|
||||
|
||||
var awgInbound, wgInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded awg row: %v", err)
|
||||
}
|
||||
if err := database.GetDB().Where("tag = ?", "wg-1").First(&wgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded wg row: %v", err)
|
||||
}
|
||||
|
||||
if !addressesFitAmneziaWGInbound(nil, &awgInbound) {
|
||||
t.Error("no addresses at all must trivially fit (Attach's own fresh-allocate path)")
|
||||
}
|
||||
if !addressesFitAmneziaWGInbound([]string{"10.0.0.2/32"}, &wgInbound) {
|
||||
t.Error("WireGuard has no strict subnet requirement -- must never be rejected here")
|
||||
}
|
||||
if addressesFitAmneziaWGInbound([]string{"10.0.0.2/32"}, &awgInbound) {
|
||||
t.Fatal("the real bug: a WireGuard-fallback-subnet address must NOT be accepted as fitting an AmneziaWG inbound configured for a different subnet")
|
||||
}
|
||||
if !addressesFitAmneziaWGInbound([]string{"10.8.1.21/32"}, &awgInbound) {
|
||||
t.Error("an address genuinely inside the awg inbound's own configured subnet must fit")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
// Concurrent creates on two inbounds hold two different lockInbound mutexes,
|
||||
// so only the serialized writer's in-tx re-check can reject the second claim.
|
||||
func TestAddInboundClientConcurrentCrossInboundAddressSingleWinner(t *testing.T) {
|
||||
setupBulkDB(t)
|
||||
svc := &ClientService{}
|
||||
inboundSvc := &InboundService{}
|
||||
|
||||
ib1 := mkInbound(t, 52210, model.WireGuard, wgServerSettings())
|
||||
ib2 := mkInbound(t, 52211, model.WireGuard, wgServerSettings())
|
||||
|
||||
const rounds = 25
|
||||
for round := range rounds {
|
||||
addr := fmt.Sprintf("10.77.%d.7/32", round)
|
||||
claims := []*model.Inbound{
|
||||
{Id: ib1.Id, Protocol: model.WireGuard, Settings: clientsSettings(t, []model.Client{
|
||||
{Email: fmt.Sprintf("race-%d-a@wg", round), Enable: true, AllowedIPs: []string{addr}},
|
||||
})},
|
||||
{Id: ib2.Id, Protocol: model.WireGuard, Settings: clientsSettings(t, []model.Client{
|
||||
{Email: fmt.Sprintf("race-%d-b@wg", round), Enable: true, AllowedIPs: []string{addr}},
|
||||
})},
|
||||
}
|
||||
|
||||
start := make(chan struct{})
|
||||
errs := make(chan error, len(claims))
|
||||
var wg sync.WaitGroup
|
||||
for _, claim := range claims {
|
||||
wg.Add(1)
|
||||
go func(data *model.Inbound) {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
_, err := svc.AddInboundClient(inboundSvc, data)
|
||||
errs <- err
|
||||
}(claim)
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
|
||||
committed := 0
|
||||
rejections := make([]string, 0, len(claims))
|
||||
for err := range errs {
|
||||
if err == nil {
|
||||
committed++
|
||||
continue
|
||||
}
|
||||
rejections = append(rejections, err.Error())
|
||||
}
|
||||
if committed != 1 {
|
||||
t.Fatalf("round %d addr %s: concurrent AddInboundClient committed=%d, want exactly 1 (rejections: %v)",
|
||||
round, addr, committed, rejections)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
@@ -202,7 +203,19 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate
|
||||
if err := s.fillProtocolDefaults(&client, inbound); err != nil {
|
||||
return needRestart, err
|
||||
}
|
||||
settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(client, inbound)}})
|
||||
clientForInbound := client
|
||||
if ips, ok := client.AllowedIPsByInbound[ibId]; ok {
|
||||
clientForInbound.AllowedIPs = ips
|
||||
} else if !addressesFitAmneziaWGInbound(clientForInbound.AllowedIPs, inbound) {
|
||||
// The shared AllowedIPs value (e.g. from a single-field legacy
|
||||
// caller) came from a different subnet than this inbound's own --
|
||||
// clear it so defaultAmneziaWGClients allocates a fresh, correct
|
||||
// address for THIS inbound instead of persisting an unroutable
|
||||
// peer. Same reasoning as addressesFitAmneziaWGInbound's own doc
|
||||
// comment on the Attach path.
|
||||
clientForInbound.AllowedIPs = nil
|
||||
}
|
||||
settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}})
|
||||
if mErr != nil {
|
||||
return needRestart, mErr
|
||||
}
|
||||
@@ -503,7 +516,22 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model
|
||||
if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
|
||||
return needRestart, err
|
||||
}
|
||||
settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(updated, inbound)}})
|
||||
clientForInbound := updated
|
||||
if ips, ok := updated.AllowedIPsByInbound[ibId]; ok {
|
||||
clientForInbound.AllowedIPs = ips
|
||||
} else if !addressesFitAmneziaWGInbound(clientForInbound.AllowedIPs, inbound) {
|
||||
// A single shared AllowedIPs field (the common case for a caller
|
||||
// that never sends AllowedIPsByInbound) must never overwrite an
|
||||
// inbound it doesn't belong to -- e.g. a client attached to both
|
||||
// wg and awg saving its wg-labeled address would otherwise get
|
||||
// that same address silently written into the awg peer config
|
||||
// too. Clearing it here makes UpdateInboundClient's own
|
||||
// empty-AllowedIPs carry-forward (see its WireGuard/AmneziaWG
|
||||
// branch) preserve THIS inbound's existing, correct value
|
||||
// instead.
|
||||
clientForInbound.AllowedIPs = nil
|
||||
}
|
||||
settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {clientWithInboundFlow(clientForInbound, inbound)}})
|
||||
if mErr != nil {
|
||||
return needRestart, mErr
|
||||
}
|
||||
@@ -704,6 +732,66 @@ func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic b
|
||||
return needRestart, nil
|
||||
}
|
||||
|
||||
// hasTunnelAttachment reports whether any of inboundIds is a currently
|
||||
// existing WireGuard or AmneziaWG inbound. Inbounds that fail to load are
|
||||
// skipped rather than treated as an error -- Attach's own loop already
|
||||
// surfaces a real error for any inbound it can't load when it gets there.
|
||||
func (s *ClientService) hasTunnelAttachment(inboundSvc *InboundService, inboundIds []int) bool {
|
||||
for _, ibId := range inboundIds {
|
||||
inbound, err := inboundSvc.GetInbound(ibId)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// addressesFitAmneziaWGInbound reports whether every entry in addrs falls
|
||||
// inside ib's own configured subnet(s). AmneziaWG only: its kernel interface
|
||||
// Address is exactly that subnet, so an address inherited from elsewhere (an
|
||||
// identity attached to a WireGuard inbound first, say) produces a peer that
|
||||
// can never connect -- Attach allocates fresh instead.
|
||||
func addressesFitAmneziaWGInbound(addrs []string, ib *model.Inbound) bool {
|
||||
if ib.Protocol != model.AmneziaWG || len(addrs) == 0 {
|
||||
return true
|
||||
}
|
||||
v4Base, v6Base, err := defaultAmneziaWGSubnetBases(ib.Settings)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
bases := make([]netip.Prefix, 0, 2)
|
||||
for _, base := range []string{v4Base, v6Base} {
|
||||
if base == "" {
|
||||
continue
|
||||
}
|
||||
prefix, pErr := netip.ParsePrefix(base)
|
||||
if pErr != nil {
|
||||
return false
|
||||
}
|
||||
bases = append(bases, prefix)
|
||||
}
|
||||
for _, a := range addrs {
|
||||
host := wireguardHostAddr(a)
|
||||
if !host.IsValid() {
|
||||
return false
|
||||
}
|
||||
fits := false
|
||||
for _, prefix := range bases {
|
||||
if prefix.Contains(host) {
|
||||
fits = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !fits {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
|
||||
existing, err := s.GetByID(id)
|
||||
if err != nil {
|
||||
@@ -726,6 +814,18 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []
|
||||
clientWire.Flow = flow
|
||||
clientWire.UpdatedAt = time.Now().UnixMilli()
|
||||
|
||||
// If this identity has no CURRENT WireGuard/AmneziaWG attachment,
|
||||
// clientWire.AllowedIPs (from the ClientRecord) is a leftover from
|
||||
// whenever it last had one -- nothing reserves it anymore. Clear it so
|
||||
// attaching to a tunnel inbound now allocates a fresh address instead
|
||||
// of resurrecting the old one, which may no longer even be the lowest
|
||||
// free slot. Left untouched when the identity already has an active
|
||||
// tunnel elsewhere, so extending it to a second protocol still keeps
|
||||
// the same address on both.
|
||||
if !s.hasTunnelAttachment(inboundSvc, currentIds) {
|
||||
clientWire.AllowedIPs = nil
|
||||
}
|
||||
|
||||
needRestart := false
|
||||
for _, ibId := range inboundIds {
|
||||
if _, attached := have[ibId]; attached {
|
||||
@@ -736,6 +836,9 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []
|
||||
return needRestart, getErr
|
||||
}
|
||||
copyClient := *clientWire
|
||||
if !addressesFitAmneziaWGInbound(copyClient.AllowedIPs, inbound) {
|
||||
copyClient.AllowedIPs = nil
|
||||
}
|
||||
if err := s.fillProtocolDefaults(©Client, inbound); err != nil {
|
||||
return needRestart, err
|
||||
}
|
||||
|
||||
@@ -241,6 +241,46 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId
|
||||
return needRestart, nil
|
||||
}
|
||||
|
||||
// otherTunnelAllowedIPs maps every AllowedIPs entry claimed on another
|
||||
// WireGuard/AmneziaWG inbound to a description of which one holds it: the
|
||||
// per-inbound defaulters only check their own client list, so two inbounds
|
||||
// sharing a subnet could otherwise hand out the same address. Disabled
|
||||
// siblings count too, keeping their addresses reserved for a later re-enable.
|
||||
//
|
||||
// selfEmails skips this identity's own entries. Email is globally unique, so a
|
||||
// match there is never a real collision -- and Attach deliberately reuses one
|
||||
// address across every inbound it attaches the identity to.
|
||||
func (s *ClientService) otherTunnelAllowedIPs(db *gorm.DB, inboundSvc *InboundService, excludeID int, selfEmails map[string]struct{}) (map[string]string, error) {
|
||||
var inbounds []*model.Inbound
|
||||
err := db.Model(model.Inbound{}).
|
||||
Where("protocol IN ? AND id != ?", []model.Protocol{model.WireGuard, model.AmneziaWG}, excludeID).
|
||||
Find(&inbounds).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
used := make(map[string]string)
|
||||
for _, ib := range inbounds {
|
||||
clients, cErr := inboundSvc.GetClients(ib)
|
||||
if cErr != nil {
|
||||
continue
|
||||
}
|
||||
name := ib.Remark
|
||||
if name == "" {
|
||||
name = ib.Tag
|
||||
}
|
||||
label := fmt.Sprintf("inbound '%s' (#%d)", name, ib.Id)
|
||||
for _, c := range clients {
|
||||
if _, self := selfEmails[strings.ToLower(c.Email)]; self {
|
||||
continue
|
||||
}
|
||||
for _, addr := range c.AllowedIPs {
|
||||
used[addr] = label
|
||||
}
|
||||
}
|
||||
}
|
||||
return used, nil
|
||||
}
|
||||
|
||||
func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client) (string, error) {
|
||||
emailSubIDs, err := inboundSvc.emailSubIDsForClients(clients)
|
||||
if err != nil {
|
||||
@@ -348,12 +388,37 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
|
||||
interfaceClients = keptWire
|
||||
}
|
||||
|
||||
if oldInbound.Protocol == model.WireGuard {
|
||||
if dErr := defaultWireguardClients(existingClients, clients, interfaceClients); dErr != nil {
|
||||
return false, dErr
|
||||
var selfEmails map[string]struct{}
|
||||
if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG {
|
||||
selfEmails = make(map[string]struct{}, len(clients))
|
||||
for _, c := range clients {
|
||||
if c.Email != "" {
|
||||
selfEmails[strings.ToLower(c.Email)] = struct{}{}
|
||||
}
|
||||
}
|
||||
crossUsed, cErr := s.otherTunnelAllowedIPs(database.GetDB(), inboundSvc, oldInbound.Id, selfEmails)
|
||||
if cErr != nil {
|
||||
return false, cErr
|
||||
}
|
||||
if oldInbound.Protocol == model.WireGuard {
|
||||
if dErr := defaultWireguardClients(oldInbound.Settings, existingClients, clients, interfaceClients, crossUsed); dErr != nil {
|
||||
return false, dErr
|
||||
}
|
||||
}
|
||||
if oldInbound.Protocol == model.AmneziaWG {
|
||||
if dErr := defaultAmneziaWGClients(oldInbound.Settings, existingClients, clients, interfaceClients, crossUsed); dErr != nil {
|
||||
return false, dErr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var portCtx portConflictContext
|
||||
if oldInbound.Protocol == model.AmneziaWG {
|
||||
portCtx, err = inboundSvc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
for _, client := range clients {
|
||||
if strings.TrimSpace(client.Email) == "" {
|
||||
return false, common.NewError("client email is required")
|
||||
@@ -371,7 +436,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
|
||||
if client.Auth == "" {
|
||||
return false, common.NewError("empty client ID")
|
||||
}
|
||||
case "wireguard":
|
||||
case "wireguard", "amneziawg":
|
||||
if client.PublicKey == "" {
|
||||
return false, common.NewError("wireguard client requires a key")
|
||||
}
|
||||
@@ -387,6 +452,11 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
|
||||
return false, common.NewError("empty client ID")
|
||||
}
|
||||
}
|
||||
if oldInbound.Protocol == model.AmneziaWG {
|
||||
if hit := inboundSvc.checkForwardedPortsConflict(portCtx, client.ForwardedPorts); hit != "" {
|
||||
return false, common.NewError("amneziawg: forwardedPorts collides with", hit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var oldSettings map[string]any
|
||||
@@ -430,6 +500,34 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
|
||||
// Persist client stats + inbound atomically, serialized against the traffic
|
||||
// poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
|
||||
if txErr := runSerializedTx(func(tx *gorm.DB) error {
|
||||
// lockInbound is per-inbound, so the pre-tx cross-inbound checks race
|
||||
// concurrent writers on other inbounds — re-run them in here (#6225).
|
||||
if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG {
|
||||
crossUsed, cErr := s.otherTunnelAllowedIPs(tx, inboundSvc, oldInbound.Id, selfEmails)
|
||||
if cErr != nil {
|
||||
return cErr
|
||||
}
|
||||
crossAddrs := make([]string, 0, len(crossUsed))
|
||||
for addr := range crossUsed {
|
||||
crossAddrs = append(crossAddrs, addr)
|
||||
}
|
||||
for i := range clients {
|
||||
if hit := wireguardAllowedIPsCollision(clients[i].AllowedIPs, crossAddrs); hit != "" {
|
||||
return common.NewError("allowedIPs entry", hit, "is already used by a client on", crossUsed[hit])
|
||||
}
|
||||
}
|
||||
}
|
||||
if oldInbound.Protocol == model.AmneziaWG {
|
||||
txPortCtx, pErr := inboundSvc.loadPortConflictContext(tx)
|
||||
if pErr != nil {
|
||||
return pErr
|
||||
}
|
||||
for i := range clients {
|
||||
if hit := inboundSvc.checkForwardedPortsConflict(txPortCtx, clients[i].ForwardedPorts); hit != "" {
|
||||
return common.NewError("amneziawg: forwardedPorts collides with", hit)
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range clients {
|
||||
if len(clients[i].Email) == 0 {
|
||||
continue
|
||||
@@ -459,6 +557,8 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
|
||||
needRestart = true
|
||||
} else if oldInbound.Protocol == model.MTProto {
|
||||
inboundSvc.applyLocalMtproto(oldInbound.Id)
|
||||
} else if oldInbound.Protocol == model.AmneziaWG {
|
||||
inboundSvc.applyLocalAmneziaWG(oldInbound.Id)
|
||||
} else {
|
||||
for _, client := range clients {
|
||||
if len(client.Email) == 0 {
|
||||
@@ -550,7 +650,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
|
||||
newClientId = clients[0].Email
|
||||
case "hysteria":
|
||||
newClientId = clients[0].Auth
|
||||
case "wireguard":
|
||||
case "wireguard", "amneziawg":
|
||||
newClientId = clients[0].Email
|
||||
case "mtproto":
|
||||
newClientId = clients[0].Email
|
||||
@@ -590,10 +690,10 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
|
||||
}
|
||||
}
|
||||
|
||||
// WireGuard keys are never rotated by an edit: when the incoming payload omits
|
||||
// them (a metadata-only change), carry the stored credentials forward so the
|
||||
// settings JSON and the running peer keep the client's identity.
|
||||
if oldInbound.Protocol == model.WireGuard && clientIndex >= 0 && clientIndex < len(oldClients) {
|
||||
// WireGuard/AmneziaWG keys are never rotated by an edit: when the incoming
|
||||
// payload omits them (a metadata-only change), carry the stored credentials
|
||||
// forward so the settings JSON and the running peer keep the client's identity.
|
||||
if (oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG) && clientIndex >= 0 && clientIndex < len(oldClients) {
|
||||
old := oldClients[clientIndex]
|
||||
if clients[0].PrivateKey == "" {
|
||||
clients[0].PrivateKey = old.PrivateKey
|
||||
@@ -630,6 +730,23 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
|
||||
if clients[0].KeepAlive == 0 {
|
||||
clients[0].KeepAlive = old.KeepAlive
|
||||
}
|
||||
// ForwardedPorts is AmneziaWG-only (WireGuard's own inbound never
|
||||
// reads it), same carry-forward reasoning as the fields above: a
|
||||
// partial edit (e.g. a Telegram-bot enable/expiry toggle, or an API
|
||||
// call that omits the field) must not silently drop a client's
|
||||
// existing port-forwarding spec.
|
||||
if oldInbound.Protocol == model.AmneziaWG && clients[0].ForwardedPorts == "" {
|
||||
clients[0].ForwardedPorts = old.ForwardedPorts
|
||||
}
|
||||
}
|
||||
if oldInbound.Protocol == model.AmneziaWG {
|
||||
portCtx, err := inboundSvc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if hit := inboundSvc.checkForwardedPortsConflict(portCtx, clients[0].ForwardedPorts); hit != "" {
|
||||
return false, common.NewError("amneziawg: forwardedPorts collides with", hit)
|
||||
}
|
||||
}
|
||||
|
||||
var oldSettings map[string]any
|
||||
@@ -670,7 +787,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
|
||||
if v, ok2 := newMap["subId"].(string); ok2 {
|
||||
clients[0].SubID = v
|
||||
}
|
||||
if oldInbound.Protocol == model.WireGuard {
|
||||
if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG {
|
||||
newMap["privateKey"] = clients[0].PrivateKey
|
||||
newMap["publicKey"] = clients[0].PublicKey
|
||||
newMap["allowedIPs"] = clients[0].AllowedIPs
|
||||
@@ -680,6 +797,9 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
|
||||
if clients[0].KeepAlive > 0 {
|
||||
newMap["keepAlive"] = clients[0].KeepAlive
|
||||
}
|
||||
if oldInbound.Protocol == model.AmneziaWG && clients[0].ForwardedPorts != "" {
|
||||
newMap["forwardedPorts"] = clients[0].ForwardedPorts
|
||||
}
|
||||
}
|
||||
if oldClientMap != nil && sameClientConfigExceptUpdatedAt(oldClientMap, newMap) {
|
||||
if v, ok2 := oldClientMap["updated_at"]; ok2 {
|
||||
@@ -754,6 +874,17 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
|
||||
// Persist client stats + inbound atomically, serialized against the traffic
|
||||
// poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
|
||||
if txErr := runSerializedTx(func(tx *gorm.DB) error {
|
||||
// Same re-check-inside-the-writer rule as AddInboundClient (#6225):
|
||||
// the pre-tx pass can race a concurrent writer on another inbound.
|
||||
if oldInbound.Protocol == model.AmneziaWG {
|
||||
txPortCtx, pErr := inboundSvc.loadPortConflictContext(tx)
|
||||
if pErr != nil {
|
||||
return pErr
|
||||
}
|
||||
if hit := inboundSvc.checkForwardedPortsConflict(txPortCtx, clients[0].ForwardedPorts); hit != "" {
|
||||
return common.NewError("amneziawg: forwardedPorts collides with", hit)
|
||||
}
|
||||
}
|
||||
if len(clients[0].Email) > 0 {
|
||||
if len(oldEmail) > 0 {
|
||||
emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
|
||||
@@ -846,6 +977,8 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
|
||||
needRestart = true
|
||||
} else if oldInbound.Protocol == model.MTProto {
|
||||
inboundSvc.applyLocalMtproto(oldInbound.Id)
|
||||
} else if oldInbound.Protocol == model.AmneziaWG {
|
||||
inboundSvc.applyLocalAmneziaWG(oldInbound.Id)
|
||||
} else {
|
||||
if oldClients[clientIndex].Enable {
|
||||
err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
|
||||
@@ -1023,6 +1156,10 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo
|
||||
// it (removing the last client stops the sidecar) regardless of the
|
||||
// client's enable state.
|
||||
inboundSvc.applyLocalMtproto(oldInbound.Id)
|
||||
} else if oldInbound.Protocol == model.AmneziaWG {
|
||||
// Same reasoning as MTProto above: the interface config is
|
||||
// regenerated from the full peer set, so any delete re-applies it.
|
||||
inboundSvc.applyLocalAmneziaWG(oldInbound.Id)
|
||||
} else if needApiDel {
|
||||
// Local inbound: a disabled client isn't in the running Xray, so only
|
||||
// a live one (needApiDel) needs an API removal.
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
// otherTunnelAllowedIPs must see across protocols (a WireGuard inbound's
|
||||
// client address collides with an AmneziaWG one just as easily as two
|
||||
// AmneziaWG inbounds would), must exclude the inbound doing the asking, and
|
||||
// must ignore inbounds that aren't WireGuard/AmneziaWG entirely.
|
||||
func TestOtherTunnelAllowedIPs(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "wg-1", "0.0.0.0", 51820, model.WireGuard, ``, `{"clients":[{"email":"a@wg","allowedIPs":["10.0.0.5/32"]}]}`)
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 443, model.AmneziaWG, ``, `{"server":{"subnetIp":"10.8.1.0","subnetCidr":24},"clients":[{"email":"b@awg","allowedIPs":["10.8.1.21/32"]}]}`)
|
||||
seedInboundConflict(t, "vless-1", "0.0.0.0", 8443, model.VLESS, `{"network":"tcp"}`, `{"clients":[{"email":"c@vless"}]}`)
|
||||
|
||||
var wgInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "wg-1").First(&wgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded wg row: %v", err)
|
||||
}
|
||||
|
||||
svc := &ClientService{}
|
||||
inboundSvc := &InboundService{}
|
||||
used, err := svc.otherTunnelAllowedIPs(database.GetDB(), inboundSvc, wgInbound.Id, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("otherTunnelAllowedIPs: %v", err)
|
||||
}
|
||||
if len(used) != 1 {
|
||||
t.Fatalf("expected exactly one cross-inbound address (self excluded, vless ignored), got %v", used)
|
||||
}
|
||||
label, ok := used["10.8.1.21/32"]
|
||||
if !ok {
|
||||
t.Fatalf("expected the awg inbound's address to be reported as used, got %v", used)
|
||||
}
|
||||
if label == "" {
|
||||
t.Fatal("expected a non-empty description of which inbound holds the address")
|
||||
}
|
||||
}
|
||||
|
||||
// TestOtherTunnelAllowedIPsExcludesSelfEmail is a regression test for a real
|
||||
// bug in ClientService.Attach: attaching one identity to multiple
|
||||
// WireGuard/AmneziaWG inbounds in the same call copies that identity's own
|
||||
// stored AllowedIPs into every inbound it processes (by design -- the same
|
||||
// person should get the same tunnel address on every protocol they use).
|
||||
// Attach's loop calls addInboundClient once per inbound, and each of those
|
||||
// calls independently computes otherTunnelAllowedIPs -- so by the second
|
||||
// inbound in the loop, the first inbound's now-successful copy of the
|
||||
// identity's own address looked like a cross-inbound collision against
|
||||
// itself, and the attach failed with exactly the error a real user hit:
|
||||
// "wireguard: allowedIPs entry 10.8.1.21/32 is already used by a client on
|
||||
// inbound 'awg' (#10)". selfEmails must exclude this identity's own entries
|
||||
// on sibling inbounds -- safe to do unconditionally because ClientRecord.Email
|
||||
// is globally unique, so a same-email match can only ever be this identity,
|
||||
// never a genuine different client.
|
||||
func TestOtherTunnelAllowedIPsExcludesSelfEmail(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
// Both shared@id (to be excluded) and other@awg (a genuinely different
|
||||
// client, must still be reported) live on the SAME sibling inbound --
|
||||
// otherTunnelAllowedIPs already excludes the asking inbound entirely via
|
||||
// excludeID, so putting other@awg there instead would make it invisible
|
||||
// to the scan regardless of the selfEmails fix, proving nothing.
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 443, model.AmneziaWG, ``, `{"server":{"subnetIp":"10.8.1.0","subnetCidr":24},"clients":[{"email":"shared@id","allowedIPs":["10.8.1.21/32"]},{"email":"other@awg","allowedIPs":["10.8.1.5/32"]}]}`)
|
||||
seedInboundConflict(t, "wg-1", "0.0.0.0", 51820, model.WireGuard, ``, `{"clients":[]}`)
|
||||
|
||||
var wgInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "wg-1").First(&wgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded wg row: %v", err)
|
||||
}
|
||||
|
||||
svc := &ClientService{}
|
||||
inboundSvc := &InboundService{}
|
||||
used, err := svc.otherTunnelAllowedIPs(database.GetDB(), inboundSvc, wgInbound.Id, map[string]struct{}{"shared@id": {}})
|
||||
if err != nil {
|
||||
t.Fatalf("otherTunnelAllowedIPs: %v", err)
|
||||
}
|
||||
if _, stillThere := used["10.8.1.21/32"]; stillThere {
|
||||
t.Fatalf("shared@id's own address on the awg inbound must be excluded from used, got %v", used)
|
||||
}
|
||||
if _, ok := used["10.8.1.5/32"]; !ok {
|
||||
t.Fatalf("a genuinely different client's address must still be reported as used, got %v", used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOtherTunnelAllowedIPsEmptyWhenNoSiblings(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "wg-1", "0.0.0.0", 51820, model.WireGuard, ``, `{"clients":[{"email":"a@wg","allowedIPs":["10.0.0.5/32"]}]}`)
|
||||
|
||||
var wgInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "wg-1").First(&wgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded wg row: %v", err)
|
||||
}
|
||||
|
||||
svc := &ClientService{}
|
||||
inboundSvc := &InboundService{}
|
||||
used, err := svc.otherTunnelAllowedIPs(database.GetDB(), inboundSvc, wgInbound.Id, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("otherTunnelAllowedIPs: %v", err)
|
||||
}
|
||||
if len(used) != 0 {
|
||||
t.Fatalf("expected no cross-inbound addresses with only one tunnel inbound present, got %v", used)
|
||||
}
|
||||
}
|
||||
@@ -133,6 +133,41 @@ func (s *ClientService) GetInboundIdsForRecord(id int) ([]int, error) {
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// TunnelAllowedIPsByInbound returns, for each given WireGuard/AmneziaWG
|
||||
// inbound id, the real AllowedIPs this email currently has on that specific
|
||||
// inbound's own settings JSON -- joined comma-separated, matching the form
|
||||
// value shape a single AllowedIPs field already uses. Non-tunnel inbounds
|
||||
// and ids the email isn't actually attached to are simply absent from the
|
||||
// result (not an error): callers use this to seed a per-protocol display
|
||||
// field, and ClientRecord's own single AllowedIPs column can't tell two
|
||||
// different protocol addresses apart, which is exactly the gap this closes.
|
||||
func (s *ClientService) TunnelAllowedIPsByInbound(inboundSvc *InboundService, email string, inboundIds []int) (map[int]string, error) {
|
||||
result := make(map[int]string, len(inboundIds))
|
||||
for _, ibId := range inboundIds {
|
||||
inbound, err := inboundSvc.GetInbound(ibId)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
continue
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if inbound.Protocol != model.WireGuard && inbound.Protocol != model.AmneziaWG {
|
||||
continue
|
||||
}
|
||||
clients, err := inboundSvc.GetClients(inbound)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range clients {
|
||||
if strings.EqualFold(clients[i].Email, email) {
|
||||
result[ibId] = strings.Join(clients[i].AllowedIPs, ",")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *ClientService) List() ([]ClientWithAttachments, error) {
|
||||
db := database.GetDB()
|
||||
var rows []model.ClientRecord
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
// seedDualProtocolClient creates a WireGuard inbound and an AmneziaWG inbound
|
||||
// (real, distinct subnets: 10.0.0.0/24 and 10.8.1.0/24), attaches the same
|
||||
// email to both with its own correct, protocol-appropriate address, and
|
||||
// returns the two inbounds plus the shared client record id.
|
||||
func seedDualProtocolClient(t *testing.T, email, wgAddr, awgAddr string) (wgIb, awgIb *model.Inbound, recordId int) {
|
||||
t.Helper()
|
||||
svc := &ClientService{}
|
||||
|
||||
wgClient := model.Client{Email: email, SubID: "sub-" + email, Enable: true, AllowedIPs: []string{wgAddr}}
|
||||
wgIb = mkInbound(t, 51820, model.WireGuard, clientsSettings(t, []model.Client{wgClient}))
|
||||
if err := svc.SyncInbound(nil, wgIb.Id, []model.Client{wgClient}); err != nil {
|
||||
t.Fatalf("seed wg linkage: %v", err)
|
||||
}
|
||||
|
||||
awgClient := model.Client{Email: email, SubID: "sub-" + email, Enable: true, AllowedIPs: []string{awgAddr}}
|
||||
awgIb = mkInbound(t, 443, model.AmneziaWG, clientsSettings(t, []model.Client{awgClient}))
|
||||
if err := svc.SyncInbound(nil, awgIb.Id, []model.Client{awgClient}); err != nil {
|
||||
t.Fatalf("seed awg linkage: %v", err)
|
||||
}
|
||||
|
||||
recordId = lookupClientRecord(t, email).Id
|
||||
return wgIb, awgIb, recordId
|
||||
}
|
||||
|
||||
func inboundAllowedIPs(t *testing.T, inboundSvc *InboundService, ibId int, email string) []string {
|
||||
t.Helper()
|
||||
ib, err := inboundSvc.GetInbound(ibId)
|
||||
if err != nil {
|
||||
t.Fatalf("GetInbound %d: %v", ibId, err)
|
||||
}
|
||||
clients, err := inboundSvc.GetClients(ib)
|
||||
if err != nil {
|
||||
t.Fatalf("GetClients %d: %v", ibId, err)
|
||||
}
|
||||
for i := range clients {
|
||||
if clients[i].Email == email {
|
||||
return clients[i].AllowedIPs
|
||||
}
|
||||
}
|
||||
t.Fatalf("email %q not found on inbound %d", email, ibId)
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestUpdateBroadcastAllowedIPsDoesNotOverwriteOtherInboundWhenMismatched is a
|
||||
// regression test for the same bug class already fixed for Attach
|
||||
// (addressesFitAmneziaWGInbound), but on the far more common Update path: the
|
||||
// edit-client form sends one shared AllowedIPs value, and Update's per-inbound
|
||||
// loop used to broadcast it verbatim to every attached inbound, including one
|
||||
// it doesn't belong to. A client attached to both wg (10.0.0.5/32) and awg
|
||||
// (10.8.1.5/32) saving with the wg-labeled value as the single shared field
|
||||
// must not silently overwrite the awg inbound's own, unrelated address.
|
||||
func TestUpdateBroadcastAllowedIPsDoesNotOverwriteOtherInboundWhenMismatched(t *testing.T) {
|
||||
setupBulkDB(t)
|
||||
inboundSvc := &InboundService{}
|
||||
svc := &ClientService{}
|
||||
|
||||
wgIb, awgIb, recId := seedDualProtocolClient(t, "dual@x", "10.0.0.5/32", "10.8.1.5/32")
|
||||
|
||||
updated := model.Client{Email: "dual@x", Enable: true, AllowedIPs: []string{"10.0.0.5/32"}}
|
||||
if _, err := svc.Update(inboundSvc, recId, updated, 0); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
|
||||
if got := inboundAllowedIPs(t, inboundSvc, wgIb.Id, "dual@x"); len(got) != 1 || got[0] != "10.0.0.5/32" {
|
||||
t.Fatalf("wg AllowedIPs = %v, want [10.0.0.5/32]", got)
|
||||
}
|
||||
if got := inboundAllowedIPs(t, inboundSvc, awgIb.Id, "dual@x"); len(got) != 1 || got[0] != "10.8.1.5/32" {
|
||||
t.Fatalf("the real bug: awg AllowedIPs = %v, want unchanged [10.8.1.5/32] (must not inherit the wg-labeled shared value)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUpdateAllowedIPsByInboundAppliesDistinctValuesPerInbound covers the new
|
||||
// mechanism the two-field client-edit form uses to intentionally change both
|
||||
// addresses in one save: distinct, valid, per-inbound override values must
|
||||
// each land on their own inbound.
|
||||
func TestUpdateAllowedIPsByInboundAppliesDistinctValuesPerInbound(t *testing.T) {
|
||||
setupBulkDB(t)
|
||||
inboundSvc := &InboundService{}
|
||||
svc := &ClientService{}
|
||||
|
||||
wgIb, awgIb, recId := seedDualProtocolClient(t, "dual@x", "10.0.0.5/32", "10.8.1.5/32")
|
||||
|
||||
updated := model.Client{
|
||||
Email: "dual@x",
|
||||
Enable: true,
|
||||
AllowedIPsByInbound: map[int][]string{
|
||||
wgIb.Id: {"10.0.0.9/32"},
|
||||
awgIb.Id: {"10.8.1.9/32"},
|
||||
},
|
||||
}
|
||||
if _, err := svc.Update(inboundSvc, recId, updated, 0); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
|
||||
if got := inboundAllowedIPs(t, inboundSvc, wgIb.Id, "dual@x"); len(got) != 1 || got[0] != "10.0.0.9/32" {
|
||||
t.Fatalf("wg AllowedIPs = %v, want [10.0.0.9/32]", got)
|
||||
}
|
||||
if got := inboundAllowedIPs(t, inboundSvc, awgIb.Id, "dual@x"); len(got) != 1 || got[0] != "10.8.1.9/32" {
|
||||
t.Fatalf("awg AllowedIPs = %v, want [10.8.1.9/32]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateSharedAllowedIPsThatDontFitAmneziaWGGetsFreshAllocation is
|
||||
// Create's counterpart to the Update regression above: adding a brand-new
|
||||
// client to both wg and awg inbounds at once with a single manually-typed
|
||||
// address must not hand the awg inbound an address from the wrong subnet --
|
||||
// it must fall back to auto-allocating a real, correctly-scoped address
|
||||
// instead, exactly as if AllowedIPs had been left empty for that inbound.
|
||||
func TestCreateSharedAllowedIPsThatDontFitAmneziaWGGetsFreshAllocation(t *testing.T) {
|
||||
setupBulkDB(t)
|
||||
inboundSvc := &InboundService{}
|
||||
svc := &ClientService{}
|
||||
|
||||
wgIb := mkInbound(t, 51820, model.WireGuard, wgServerSettings())
|
||||
awgIb := mkInbound(t, 443, model.AmneziaWG, amneziawgClientTestSettings)
|
||||
|
||||
payload := &ClientCreatePayload{
|
||||
Client: model.Client{Email: "new@x", Enable: true, AllowedIPs: []string{"10.0.0.7/32"}},
|
||||
InboundIds: []int{wgIb.Id, awgIb.Id},
|
||||
}
|
||||
if _, err := svc.Create(inboundSvc, payload); err != nil {
|
||||
t.Fatalf("Create: %v", err)
|
||||
}
|
||||
|
||||
if got := inboundAllowedIPs(t, inboundSvc, wgIb.Id, "new@x"); len(got) != 1 || got[0] != "10.0.0.7/32" {
|
||||
t.Fatalf("wg AllowedIPs = %v, want [10.0.0.7/32]", got)
|
||||
}
|
||||
got := inboundAllowedIPs(t, inboundSvc, awgIb.Id, "new@x")
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("awg AllowedIPs = %v, want exactly one freshly allocated address", got)
|
||||
}
|
||||
if got[0] == "10.0.0.7/32" {
|
||||
t.Fatal("the real bug: awg inbound inherited the wg-shaped shared address instead of allocating its own")
|
||||
}
|
||||
if !addressesFitAmneziaWGInbound(got, awgIb) {
|
||||
t.Fatalf("freshly allocated awg address %v does not actually fit the awg inbound's own subnet", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateAllowedIPsByInboundAppliesDistinctValuesPerInbound is Create's
|
||||
// counterpart to the Update explicit-override test: the add-client form,
|
||||
// when attaching to both wg and awg at once with the two-field UI, must be
|
||||
// able to give each inbound its own manually chosen address in one call.
|
||||
func TestCreateAllowedIPsByInboundAppliesDistinctValuesPerInbound(t *testing.T) {
|
||||
setupBulkDB(t)
|
||||
inboundSvc := &InboundService{}
|
||||
svc := &ClientService{}
|
||||
|
||||
wgIb := mkInbound(t, 51820, model.WireGuard, wgServerSettings())
|
||||
awgIb := mkInbound(t, 443, model.AmneziaWG, amneziawgClientTestSettings)
|
||||
|
||||
payload := &ClientCreatePayload{
|
||||
Client: model.Client{
|
||||
Email: "new@x",
|
||||
Enable: true,
|
||||
AllowedIPsByInbound: map[int][]string{
|
||||
wgIb.Id: {"10.0.0.9/32"},
|
||||
awgIb.Id: {"10.8.1.9/32"},
|
||||
},
|
||||
},
|
||||
InboundIds: []int{wgIb.Id, awgIb.Id},
|
||||
}
|
||||
if _, err := svc.Create(inboundSvc, payload); err != nil {
|
||||
t.Fatalf("Create: %v", err)
|
||||
}
|
||||
|
||||
if got := inboundAllowedIPs(t, inboundSvc, wgIb.Id, "new@x"); len(got) != 1 || got[0] != "10.0.0.9/32" {
|
||||
t.Fatalf("wg AllowedIPs = %v, want [10.0.0.9/32]", got)
|
||||
}
|
||||
if got := inboundAllowedIPs(t, inboundSvc, awgIb.Id, "new@x"); len(got) != 1 || got[0] != "10.8.1.9/32" {
|
||||
t.Fatalf("awg AllowedIPs = %v, want [10.8.1.9/32]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTunnelAllowedIPsByInbound covers the GET-client read side: a two-field
|
||||
// display needs the real, distinct per-inbound address for each protocol,
|
||||
// which ClientRecord's own single AllowedIPs column cannot represent.
|
||||
func TestTunnelAllowedIPsByInbound(t *testing.T) {
|
||||
setupBulkDB(t)
|
||||
inboundSvc := &InboundService{}
|
||||
svc := &ClientService{}
|
||||
|
||||
wgIb, awgIb, _ := seedDualProtocolClient(t, "dual@x", "10.0.0.5/32", "10.8.1.5/32")
|
||||
vlessIb := mkInbound(t, 8443, model.VLESS, clientsSettings(t, nil))
|
||||
|
||||
got, err := svc.TunnelAllowedIPsByInbound(inboundSvc, "dual@x", []int{wgIb.Id, awgIb.Id, vlessIb.Id, 999999})
|
||||
if err != nil {
|
||||
t.Fatalf("TunnelAllowedIPsByInbound: %v", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("result = %v, want exactly 2 entries (vless and the nonexistent id must be skipped)", got)
|
||||
}
|
||||
if got[wgIb.Id] != "10.0.0.5/32" {
|
||||
t.Fatalf("wg entry = %q, want 10.0.0.5/32", got[wgIb.Id])
|
||||
}
|
||||
if got[awgIb.Id] != "10.8.1.5/32" {
|
||||
t.Fatalf("awg entry = %q, want 10.8.1.5/32", got[awgIb.Id])
|
||||
}
|
||||
if _, ok := got[vlessIb.Id]; ok {
|
||||
t.Fatalf("a non-tunnel (VLESS) inbound must not appear in the result")
|
||||
}
|
||||
if _, ok := got[999999]; ok {
|
||||
t.Fatalf("a nonexistent inbound id must not appear in the result")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -12,6 +14,41 @@ import (
|
||||
|
||||
const defaultWireguardBase = "10.0.0.0/24"
|
||||
|
||||
// wireguardSubnetSettings is the subset of a WireGuard inbound's top-level
|
||||
// settings JSON this package cares about for subnet resolution. Unlike
|
||||
// AmneziaWG (whose whole settings shape is a typed struct in
|
||||
// internal/amneziawg), plain WireGuard has no dedicated Go struct on this
|
||||
// fork's side at all -- everything else is handled as untyped
|
||||
// map[string]any -- so this stays a narrow, local decode rather than
|
||||
// introducing a full struct just for two fields.
|
||||
type wireguardSubnetSettings struct {
|
||||
SubnetIP string `json:"subnetIp"`
|
||||
SubnetCIDR int `json:"subnetCidr"`
|
||||
}
|
||||
|
||||
// explicitWireguardSubnetBase resolves an admin-configured subnet base out
|
||||
// of settingsJSON's own subnetIp/subnetCidr fields, mirroring AmneziaWG's
|
||||
// defaultAmneziaWGSubnetBases. Returns "" when either field is unset/empty
|
||||
// or doesn't parse as a valid prefix -- callers fall back to
|
||||
// wireguardAllocationBase's existing infer-from-clients behavior in that
|
||||
// case, so an inbound saved before this field existed (or one that simply
|
||||
// never set it) keeps behaving exactly as it always has.
|
||||
func explicitWireguardSubnetBase(settingsJSON string) string {
|
||||
var parsed wireguardSubnetSettings
|
||||
if err := json.Unmarshal([]byte(settingsJSON), &parsed); err != nil {
|
||||
return ""
|
||||
}
|
||||
ip := strings.TrimSpace(parsed.SubnetIP)
|
||||
if ip == "" || parsed.SubnetCIDR <= 0 {
|
||||
return ""
|
||||
}
|
||||
base := fmt.Sprintf("%s/%d", ip, parsed.SubnetCIDR)
|
||||
if _, err := netip.ParsePrefix(base); err != nil {
|
||||
return ""
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func keepAliveStr(seconds int) string {
|
||||
if seconds <= 0 {
|
||||
return ""
|
||||
@@ -48,7 +85,14 @@ func wireguardAllocationBase(used []string, fallback string) string {
|
||||
|
||||
const wireguardPoolFloorBits = 16
|
||||
|
||||
func allocateWireguardAddress(used []string, base string) (string, error) {
|
||||
// allocateWireguardAddress returns the first free single-host address in base
|
||||
// not already in used, starting at the second host (the server holds the first).
|
||||
//
|
||||
// allowWidening retries in the containing /16 once base's pool is exhausted.
|
||||
// True for Xray-native WireGuard, whose AllowedIPs aren't tied to a kernel
|
||||
// interface subnet; AmneziaWG must pass false and fail loudly instead, since an
|
||||
// address outside its interface's own Address would be silently unroutable.
|
||||
func allocateWireguardAddress(used []string, base string, allowWidening bool) (string, error) {
|
||||
if base == "" {
|
||||
base = defaultWireguardBase
|
||||
}
|
||||
@@ -56,6 +100,10 @@ func allocateWireguardAddress(used []string, base string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
hostBits := "32"
|
||||
if prefix.Addr().Is6() {
|
||||
hostBits = "128"
|
||||
}
|
||||
taken := make(map[netip.Addr]struct{}, len(used))
|
||||
for _, u := range used {
|
||||
if a := wireguardHostAddr(u); a.IsValid() {
|
||||
@@ -63,7 +111,7 @@ func allocateWireguardAddress(used []string, base string) (string, error) {
|
||||
}
|
||||
}
|
||||
scopes := []netip.Prefix{prefix}
|
||||
if prefix.Addr().Is4() && prefix.Bits() > wireguardPoolFloorBits {
|
||||
if allowWidening && prefix.Addr().Is4() && prefix.Bits() > wireguardPoolFloorBits {
|
||||
if wider, wErr := prefix.Addr().Prefix(wireguardPoolFloorBits); wErr == nil {
|
||||
scopes = append(scopes, wider)
|
||||
}
|
||||
@@ -72,7 +120,7 @@ func allocateWireguardAddress(used []string, base string) (string, error) {
|
||||
addr := scope.Masked().Addr().Next().Next()
|
||||
for scope.Contains(addr) {
|
||||
if _, ok := taken[addr]; !ok {
|
||||
return addr.String() + "/32", nil
|
||||
return addr.String() + "/" + hostBits, nil
|
||||
}
|
||||
addr = addr.Next()
|
||||
}
|
||||
@@ -127,12 +175,32 @@ func wireguardAllowedIPsCollision(entries, used []string) string {
|
||||
// inbound's subnet. It mutates both the typed clients and the parallel raw client
|
||||
// maps that get persisted into the inbound settings. Existing values are never
|
||||
// overwritten, so editing a client never rotates its keys.
|
||||
func defaultWireguardClients(existing, clients []model.Client, interfaceClients []any) error {
|
||||
//
|
||||
// crossInboundUsed maps AllowedIPs already claimed by clients on every OTHER
|
||||
// WireGuard/AmneziaWG inbound on this panel to a human-readable description
|
||||
// of which inbound holds it (see otherTunnelAllowedIPs). It is folded into
|
||||
// used only AFTER the base subnet is resolved, so an unrelated inbound's
|
||||
// subnet can never skew this inbound's own base-subnet resolution — it only
|
||||
// ever narrows which addresses are free to hand out or accept, and lets a
|
||||
// manual-entry collision name the other inbound instead of just the address.
|
||||
//
|
||||
// settingsJSON is checked first for an admin-configured subnetIp/subnetCidr
|
||||
// (see explicitWireguardSubnetBase) — set explicitly, that always wins.
|
||||
// Only when it's unset does base fall back to inferring from existing
|
||||
// clients' own addresses, and finally to defaultWireguardBase, exactly as
|
||||
// before this field existed.
|
||||
func defaultWireguardClients(settingsJSON string, existing, clients []model.Client, interfaceClients []any, crossInboundUsed map[string]string) error {
|
||||
used := make([]string, 0)
|
||||
for i := range existing {
|
||||
used = append(used, existing[i].AllowedIPs...)
|
||||
}
|
||||
base := wireguardAllocationBase(used, defaultWireguardBase)
|
||||
base := explicitWireguardSubnetBase(settingsJSON)
|
||||
if base == "" {
|
||||
base = wireguardAllocationBase(used, defaultWireguardBase)
|
||||
}
|
||||
for addr := range crossInboundUsed {
|
||||
used = append(used, addr)
|
||||
}
|
||||
for i := range clients {
|
||||
c := &clients[i]
|
||||
if c.PrivateKey == "" && c.PublicKey == "" {
|
||||
@@ -150,7 +218,7 @@ func defaultWireguardClients(existing, clients []model.Client, interfaceClients
|
||||
c.PublicKey = pub
|
||||
}
|
||||
if len(c.AllowedIPs) == 0 {
|
||||
addr, err := allocateWireguardAddress(used, base)
|
||||
addr, err := allocateWireguardAddress(used, base, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -164,6 +232,9 @@ func defaultWireguardClients(existing, clients []model.Client, interfaceClients
|
||||
return common.NewError("wireguard: allowedIPs has no usable entry")
|
||||
}
|
||||
if hit := wireguardAllowedIPsCollision(normalized, used); hit != "" {
|
||||
if where := crossInboundUsed[hit]; where != "" {
|
||||
return common.NewError("wireguard: allowedIPs entry", hit, "is already used by a client on", where)
|
||||
}
|
||||
return common.NewError("wireguard: allowedIPs entry already used by another client:", hit)
|
||||
}
|
||||
c.AllowedIPs = normalized
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
@@ -26,7 +27,7 @@ func TestAllocateWireguardAddress(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := allocateWireguardAddress(tt.used, tt.base)
|
||||
got, err := allocateWireguardAddress(tt.used, tt.base, true)
|
||||
if tt.err {
|
||||
if err == nil {
|
||||
t.Fatalf("expected error, got %q", got)
|
||||
@@ -46,7 +47,7 @@ func TestAllocateWireguardAddress(t *testing.T) {
|
||||
func TestDefaultWireguardClientsGeneratesKeypair(t *testing.T) {
|
||||
clients := []model.Client{{Email: "a@wg"}}
|
||||
ifaces := []any{map[string]any{"email": "a@wg"}}
|
||||
if err := defaultWireguardClients(nil, clients, ifaces); err != nil {
|
||||
if err := defaultWireguardClients("", nil, clients, ifaces, nil); err != nil {
|
||||
t.Fatalf("defaultWireguardClients: %v", err)
|
||||
}
|
||||
c := clients[0]
|
||||
@@ -73,7 +74,7 @@ func TestDefaultWireguardClientsDerivesPublicKey(t *testing.T) {
|
||||
}
|
||||
clients := []model.Client{{Email: "b@wg", PrivateKey: priv}}
|
||||
ifaces := []any{map[string]any{"email": "b@wg"}}
|
||||
if err := defaultWireguardClients(nil, clients, ifaces); err != nil {
|
||||
if err := defaultWireguardClients("", nil, clients, ifaces, nil); err != nil {
|
||||
t.Fatalf("defaultWireguardClients: %v", err)
|
||||
}
|
||||
if clients[0].PublicKey != wantPub {
|
||||
@@ -89,7 +90,7 @@ func TestDefaultWireguardClientsPreservesProvided(t *testing.T) {
|
||||
AllowedIPs: []string{"10.0.0.50/32"},
|
||||
}}
|
||||
ifaces := []any{map[string]any{"email": "c@wg"}}
|
||||
if err := defaultWireguardClients(nil, clients, ifaces); err != nil {
|
||||
if err := defaultWireguardClients("", nil, clients, ifaces, nil); err != nil {
|
||||
t.Fatalf("defaultWireguardClients: %v", err)
|
||||
}
|
||||
if clients[0].PrivateKey != "keep-priv" || clients[0].PublicKey != "keep-pub" {
|
||||
@@ -124,7 +125,7 @@ func TestDefaultWireguardClientsHonorsExistingSubnet(t *testing.T) {
|
||||
existing := []model.Client{{Email: "old@wg", AllowedIPs: []string{"172.16.0.2/32"}}}
|
||||
clients := []model.Client{{Email: "new@wg"}}
|
||||
ifaces := []any{map[string]any{"email": "new@wg"}}
|
||||
if err := defaultWireguardClients(existing, clients, ifaces); err != nil {
|
||||
if err := defaultWireguardClients("", existing, clients, ifaces, nil); err != nil {
|
||||
t.Fatalf("defaultWireguardClients: %v", err)
|
||||
}
|
||||
if got := clients[0].AllowedIPs[0]; got != "172.16.0.3/32" {
|
||||
@@ -138,7 +139,7 @@ func TestAllocateWireguardAddressWidensPastFullSlash24(t *testing.T) {
|
||||
used = append(used, fmt.Sprintf("10.0.0.%d/32", i))
|
||||
}
|
||||
|
||||
got, err := allocateWireguardAddress(used, "10.0.0.0/24")
|
||||
got, err := allocateWireguardAddress(used, "10.0.0.0/24", true)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate with a full /24: %v", err)
|
||||
}
|
||||
@@ -147,7 +148,7 @@ func TestAllocateWireguardAddressWidensPastFullSlash24(t *testing.T) {
|
||||
}
|
||||
|
||||
used = append(used, got)
|
||||
next, err := allocateWireguardAddress(used, "10.0.0.0/24")
|
||||
next, err := allocateWireguardAddress(used, "10.0.0.0/24", true)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate after widening: %v", err)
|
||||
}
|
||||
@@ -157,7 +158,7 @@ func TestAllocateWireguardAddressWidensPastFullSlash24(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAllocateWireguardAddressFillsItsOwnSlash24First(t *testing.T) {
|
||||
got, err := allocateWireguardAddress([]string{"172.16.0.2/32"}, "172.16.0.0/24")
|
||||
got, err := allocateWireguardAddress([]string{"172.16.0.2/32"}, "172.16.0.0/24", true)
|
||||
if err != nil {
|
||||
t.Fatalf("allocateWireguardAddress: %v", err)
|
||||
}
|
||||
@@ -166,10 +167,23 @@ func TestAllocateWireguardAddressFillsItsOwnSlash24First(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllocateWireguardAddressNoWideningFailsWhenPoolExhausted(t *testing.T) {
|
||||
used := make([]string, 0, 254)
|
||||
for i := 2; i <= 255; i++ {
|
||||
used = append(used, fmt.Sprintf("10.0.0.%d/32", i))
|
||||
}
|
||||
// allowWidening=false: AmneziaWG's own call. A full /24 must fail loudly
|
||||
// instead of handing out an address from the containing /16 that the
|
||||
// kernel interface's own Address never routes (PR #6105 Finding 12).
|
||||
if _, err := allocateWireguardAddress(used, "10.0.0.0/24", false); err == nil {
|
||||
t.Fatal("a full /24 with widening disabled must fail, not widen")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultWireguardClientsAllocatesDistinctIPs(t *testing.T) {
|
||||
clients := []model.Client{{Email: "x@wg"}, {Email: "y@wg"}}
|
||||
ifaces := []any{map[string]any{"email": "x@wg"}, map[string]any{"email": "y@wg"}}
|
||||
if err := defaultWireguardClients(nil, clients, ifaces); err != nil {
|
||||
if err := defaultWireguardClients("", nil, clients, ifaces, nil); err != nil {
|
||||
t.Fatalf("defaultWireguardClients: %v", err)
|
||||
}
|
||||
if clients[0].AllowedIPs[0] == clients[1].AllowedIPs[0] {
|
||||
@@ -222,7 +236,7 @@ func TestDefaultWireguardClientsHonorsAndValidatesSuppliedAllowedIPs(t *testing.
|
||||
|
||||
clients := []model.Client{{Email: "c@wg", AllowedIPs: []string{"10.0.0.9"}}}
|
||||
ifaces := []any{map[string]any{"email": "c@wg"}}
|
||||
if err := defaultWireguardClients(existing, clients, ifaces); err != nil {
|
||||
if err := defaultWireguardClients("", existing, clients, ifaces, nil); err != nil {
|
||||
t.Fatalf("defaultWireguardClients: %v", err)
|
||||
}
|
||||
if len(clients[0].AllowedIPs) != 1 || clients[0].AllowedIPs[0] != "10.0.0.9/32" {
|
||||
@@ -230,13 +244,121 @@ func TestDefaultWireguardClientsHonorsAndValidatesSuppliedAllowedIPs(t *testing.
|
||||
}
|
||||
|
||||
dup := []model.Client{{Email: "d@wg", AllowedIPs: []string{"10.0.0.2/32"}}}
|
||||
err := defaultWireguardClients(existing, dup, []any{map[string]any{"email": "d@wg"}})
|
||||
err := defaultWireguardClients("", existing, dup, []any{map[string]any{"email": "d@wg"}}, nil)
|
||||
if err == nil {
|
||||
t.Fatal("duplicate allowedIPs across clients must be rejected")
|
||||
}
|
||||
|
||||
bad := []model.Client{{Email: "e@wg", AllowedIPs: []string{"not-an-ip"}}}
|
||||
if err := defaultWireguardClients(existing, bad, []any{map[string]any{"email": "e@wg"}}); err == nil {
|
||||
if err := defaultWireguardClients("", existing, bad, []any{map[string]any{"email": "e@wg"}}, nil); err == nil {
|
||||
t.Fatal("invalid allowedIPs entry must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
// A duplicate manually-typed address is rejected even when the OTHER holder
|
||||
// lives on a completely different inbound (e.g. a WireGuard client and an
|
||||
// AmneziaWG peer given the same address by habit) -- this is the exact
|
||||
// real-world scenario that motivated crossInboundUsed: two inbounds sharing
|
||||
// a subnet must not be able to silently hand out or accept the same address.
|
||||
func TestDefaultWireguardClientsRejectsCrossInboundDuplicate(t *testing.T) {
|
||||
crossUsed := map[string]string{"10.8.1.21/32": "inbound 'awg' (#10)"}
|
||||
dup := []model.Client{{Email: "d@wg", AllowedIPs: []string{"10.8.1.21/32"}}}
|
||||
err := defaultWireguardClients("", nil, dup, []any{map[string]any{"email": "d@wg"}}, crossUsed)
|
||||
if err == nil {
|
||||
t.Fatal("allowedIPs already used on another inbound must be rejected")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "inbound 'awg' (#10)") {
|
||||
t.Fatalf("error should name the other inbound holding the address, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-allocation (no AllowedIPs supplied) must also skip addresses already
|
||||
// claimed on another inbound, not just ones used on this one.
|
||||
func TestDefaultWireguardClientsAutoAllocateSkipsCrossInboundUsed(t *testing.T) {
|
||||
crossUsed := map[string]string{"10.0.0.2/32": "inbound 'other-wg' (#7)"}
|
||||
clients := []model.Client{{Email: "f@wg"}}
|
||||
ifaces := []any{map[string]any{"email": "f@wg"}}
|
||||
if err := defaultWireguardClients("", nil, clients, ifaces, crossUsed); err != nil {
|
||||
t.Fatalf("defaultWireguardClients: %v", err)
|
||||
}
|
||||
if clients[0].AllowedIPs[0] != "10.0.0.3/32" {
|
||||
t.Fatalf("auto-allocation should skip the cross-inbound-used .2 and pick .3, got %v", clients[0].AllowedIPs)
|
||||
}
|
||||
}
|
||||
|
||||
// crossInboundUsed must never influence which subnet THIS inbound's own new
|
||||
// clients get allocated from -- only existing (this inbound's own clients)
|
||||
// may do that. Otherwise a brand-new WireGuard inbound on a panel that
|
||||
// already has an unrelated AmneziaWG inbound would infer the wrong base
|
||||
// subnet purely from the other inbound's addresses.
|
||||
func TestDefaultWireguardClientsCrossInboundUsedDoesNotSkewSubnetInference(t *testing.T) {
|
||||
crossUsed := map[string]string{"10.8.1.21/32": "inbound 'awg' (#10)"}
|
||||
clients := []model.Client{{Email: "g@wg"}}
|
||||
ifaces := []any{map[string]any{"email": "g@wg"}}
|
||||
if err := defaultWireguardClients("", nil, clients, ifaces, crossUsed); err != nil {
|
||||
t.Fatalf("defaultWireguardClients: %v", err)
|
||||
}
|
||||
if got := clients[0].AllowedIPs[0]; got != "10.0.0.2/32" {
|
||||
t.Fatalf("base subnet must stay the default 10.0.0.0/24, not be skewed by a cross-inbound address; got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplicitWireguardSubnetBase(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
settingsJSON string
|
||||
want string
|
||||
}{
|
||||
{name: "unset settings", settingsJSON: `{"secretKey":"x"}`, want: ""},
|
||||
{name: "empty subnetIp", settingsJSON: `{"subnetIp":"","subnetCidr":24}`, want: ""},
|
||||
{name: "zero cidr", settingsJSON: `{"subnetIp":"10.8.1.0","subnetCidr":0}`, want: ""},
|
||||
{name: "invalid ip", settingsJSON: `{"subnetIp":"not-an-ip","subnetCidr":24}`, want: ""},
|
||||
{name: "invalid json", settingsJSON: `not json`, want: ""},
|
||||
{name: "configured subnet", settingsJSON: `{"subnetIp":"10.8.1.0","subnetCidr":24}`, want: "10.8.1.0/24"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := explicitWireguardSubnetBase(tt.settingsJSON); got != tt.want {
|
||||
t.Fatalf("got %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultWireguardClientsPrefersExplicitSubnetOverInference is the
|
||||
// backend half of a user-requested feature: WireGuard previously had no
|
||||
// admin-configurable subnet at all, only an implicit one (inferred from
|
||||
// existing clients' own addresses, or a hardcoded 10.0.0.0/24 fallback when
|
||||
// none exist yet) -- unlike AmneziaWG, which has always had a real
|
||||
// server.subnetIp/subnetCidr field. An explicit subnetIp/subnetCidr in the
|
||||
// inbound's own settings must now win outright, even when existing clients
|
||||
// would otherwise suggest a different base via wireguardAllocationBase.
|
||||
func TestDefaultWireguardClientsPrefersExplicitSubnetOverInference(t *testing.T) {
|
||||
existing := []model.Client{{Email: "old@wg", AllowedIPs: []string{"172.16.0.2/32"}}}
|
||||
clients := []model.Client{{Email: "new@wg"}}
|
||||
ifaces := []any{map[string]any{"email": "new@wg"}}
|
||||
settingsJSON := `{"subnetIp":"10.8.1.0","subnetCidr":24}`
|
||||
if err := defaultWireguardClients(settingsJSON, existing, clients, ifaces, nil); err != nil {
|
||||
t.Fatalf("defaultWireguardClients: %v", err)
|
||||
}
|
||||
if got := clients[0].AllowedIPs[0]; got != "10.8.1.2/32" {
|
||||
t.Fatalf("explicit subnet must win over inference from existing clients (172.16.0.0/24); got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDefaultWireguardClientsFallsBackWhenNoExplicitSubnet locks in the
|
||||
// backward-compat half of the same feature: an inbound saved before this
|
||||
// field existed (settingsJSON carries no subnetIp/subnetCidr at all) must
|
||||
// keep allocating exactly as it always has.
|
||||
func TestDefaultWireguardClientsFallsBackWhenNoExplicitSubnet(t *testing.T) {
|
||||
existing := []model.Client{{Email: "old@wg", AllowedIPs: []string{"172.16.0.2/32"}}}
|
||||
clients := []model.Client{{Email: "new@wg"}}
|
||||
ifaces := []any{map[string]any{"email": "new@wg"}}
|
||||
settingsJSON := `{"secretKey":"x","peers":[],"clients":[]}`
|
||||
if err := defaultWireguardClients(settingsJSON, existing, clients, ifaces, nil); err != nil {
|
||||
t.Fatalf("defaultWireguardClients: %v", err)
|
||||
}
|
||||
if got := clients[0].AllowedIPs[0]; got != "172.16.0.3/32" {
|
||||
t.Fatalf("with no explicit subnet, inference from existing clients must still apply; got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
@@ -314,6 +316,10 @@ type InboundOption struct {
|
||||
WgMtu int `json:"wgMtu,omitempty"`
|
||||
WgDns string `json:"wgDns,omitempty"`
|
||||
MtprotoDomain string `json:"mtprotoDomain,omitempty"`
|
||||
// AwgServer carries the full AmneziaWG server block (keys, subnet,
|
||||
// obfuscation params) so the clients page can render a downloadable
|
||||
// per-client .conf without a second round trip.
|
||||
AwgServer *amneziawg.ServerSettings `json:"awgServer,omitempty"`
|
||||
// Hosting node; nil for this panel's own inbounds. Lets the clients
|
||||
// page map a node filter onto inbound IDs (#4997).
|
||||
NodeId *int `json:"nodeId,omitempty"`
|
||||
@@ -376,6 +382,7 @@ func (s *InboundService) GetInboundOptions(userId int) ([]InboundOption, error)
|
||||
WgMtu: wgMtu,
|
||||
WgDns: wgDns,
|
||||
MtprotoDomain: inboundMtprotoDomain(r.Protocol, r.Settings),
|
||||
AwgServer: inboundAmneziaWGServer(r.Protocol, r.Settings),
|
||||
NodeId: r.NodeId,
|
||||
NodeAddress: r.NodeAddress,
|
||||
Listen: r.Listen,
|
||||
@@ -412,6 +419,26 @@ func inboundWireguardHints(protocol string, settings string) (string, int, strin
|
||||
return publicKey, parsed.MTU, parsed.DNS
|
||||
}
|
||||
|
||||
// inboundAmneziaWGServer returns the AmneziaWG server block for the clients
|
||||
// page's config-download builder, or nil when the inbound isn't AmneziaWG or
|
||||
// its settings don't parse. PrivateKey is redacted: GetInboundOptions is a
|
||||
// shared, admin-wide list used to fill dropdowns, not a place a live tunnel
|
||||
// secret needs to travel — the frontend's own AwgServerOptionSchema never
|
||||
// reads it, so nothing is lost by not sending it, and it shouldn't widen the
|
||||
// blast radius of a log capture, proxy cache, or browser devtools screenshot.
|
||||
func inboundAmneziaWGServer(protocol string, settings string) *amneziawg.ServerSettings {
|
||||
if protocol != string(model.AmneziaWG) || strings.TrimSpace(settings) == "" {
|
||||
return nil
|
||||
}
|
||||
var parsed amneziawg.InboundSettings
|
||||
if err := json.Unmarshal([]byte(settings), &parsed); err != nil || parsed.Server == nil {
|
||||
return nil
|
||||
}
|
||||
redacted := *parsed.Server
|
||||
redacted.PrivateKey = ""
|
||||
return &redacted
|
||||
}
|
||||
|
||||
// inboundMtprotoDomain returns the inbound-level FakeTLS default domain, used by
|
||||
// the clients UI to seed a new mtproto client's secret with the right fronting
|
||||
// hostname.
|
||||
@@ -929,6 +956,12 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
|
||||
if err := s.normalizeMtprotoXrayPort(inbound, ""); err != nil {
|
||||
return inbound, false, err
|
||||
}
|
||||
if err := s.normalizeAmneziaWGSettings(inbound); err != nil {
|
||||
return inbound, false, err
|
||||
}
|
||||
if inbound.NodeID != nil && !isNodeEligibleProtocol(inbound.Protocol) {
|
||||
return inbound, false, common.NewErrorf("%s inbounds cannot be assigned to a node", inbound.Protocol)
|
||||
}
|
||||
inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
|
||||
if err := normalizeInboundShareAddressStrict(inbound); err != nil {
|
||||
return inbound, false, err
|
||||
@@ -1006,7 +1039,7 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
|
||||
if client.Auth == "" {
|
||||
return inbound, false, common.NewError("empty client ID")
|
||||
}
|
||||
case "wireguard":
|
||||
case "wireguard", "amneziawg":
|
||||
if client.PublicKey == "" {
|
||||
return inbound, false, common.NewError("wireguard client requires a key")
|
||||
}
|
||||
@@ -1038,6 +1071,21 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
|
||||
if err := tx.Omit("ClientStats").Save(inbound).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// The relay port is derived from the id, only known after Save; checkPortConflictTx
|
||||
// ran the reverse-direction check above with ignoreId==0, so it couldn't yet.
|
||||
if inbound.Protocol == model.AmneziaWG {
|
||||
if amneziawgnet.SOCKSPortForInbound(inbound.Id) > 65535 {
|
||||
return common.NewErrorf("amneziawg: inbound id %d exceeds the relay port window (ids above %d are not supported)",
|
||||
inbound.Id, 65535-amneziawgnet.SOCKSBasePort)
|
||||
}
|
||||
conflict, cErr := checkAmneziawgnetSocksReverseConflict(tx, inbound.Id)
|
||||
if cErr != nil {
|
||||
return cErr
|
||||
}
|
||||
if conflict != nil {
|
||||
return common.NewError(conflict.String())
|
||||
}
|
||||
}
|
||||
// Emails seeded here (import's ClientStats, e.g. the controller's forced
|
||||
// Enable=true on every imported stat row) are authoritative for this call
|
||||
// and must not be clobbered by the AddClientStat loop below, which derives
|
||||
@@ -1425,6 +1473,9 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound,
|
||||
return inbound, false, err
|
||||
}
|
||||
s.normalizeMtprotoSecret(inbound)
|
||||
if err := s.normalizeAmneziaWGSettings(inbound); err != nil {
|
||||
return inbound, false, err
|
||||
}
|
||||
inbound.SubSortIndex = normalizeSubSortIndex(inbound.SubSortIndex)
|
||||
|
||||
clients, err := s.GetClients(inbound)
|
||||
@@ -1446,6 +1497,9 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound,
|
||||
// Restore the stored NodeID before the port-conflict check so a node inbound
|
||||
// stays scoped to its own node (the payload's nodeId is unreliable, often absent).
|
||||
inbound.NodeID = oldInbound.NodeID
|
||||
if inbound.NodeID != nil && !isNodeEligibleProtocol(inbound.Protocol) {
|
||||
return inbound, false, common.NewErrorf("%s inbounds cannot be assigned to a node", inbound.Protocol)
|
||||
}
|
||||
|
||||
// Capture the pre-edit protocol and routing state before oldInbound is
|
||||
// overwritten with the new values further down, then ensure a routed
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
// DesiredAmneziaWGInstances derives the AmneziaWG interfaces this panel
|
||||
// should be running: one instance per enabled local AmneziaWG inbound,
|
||||
// serving only the peers of clients that are both enabled in the inbound
|
||||
// settings and not depletion-disabled in client_traffics. That is the same
|
||||
// effective peer set buildInboundForLocalRuntime pushes on interactive edits,
|
||||
// so the reconcile job and the push path agree on one fingerprint — see
|
||||
// DesiredMtprotoInstances, which this mirrors exactly.
|
||||
func (s *InboundService) DesiredAmneziaWGInstances() ([]amneziawg.Instance, error) {
|
||||
db := database.GetDB()
|
||||
var inbounds []*model.Inbound
|
||||
err := db.Model(model.Inbound{}).
|
||||
Where("protocol = ? AND enable = ? AND node_id IS NULL", model.AmneziaWG, true).
|
||||
Find(&inbounds).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(inbounds) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
ids := make([]int, 0, len(inbounds))
|
||||
for _, ib := range inbounds {
|
||||
ids = append(ids, ib.Id)
|
||||
}
|
||||
var disabledRows []xray.ClientTraffic
|
||||
err = db.Model(xray.ClientTraffic{}).
|
||||
Where("inbound_id IN ? AND enable = ?", ids, false).
|
||||
Select("inbound_id", "email").
|
||||
Find(&disabledRows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
disabled := make(map[int]map[string]struct{}, len(disabledRows))
|
||||
for _, row := range disabledRows {
|
||||
if disabled[row.InboundId] == nil {
|
||||
disabled[row.InboundId] = map[string]struct{}{}
|
||||
}
|
||||
disabled[row.InboundId][row.Email] = struct{}{}
|
||||
}
|
||||
|
||||
instances := make([]amneziawg.Instance, 0, len(inbounds))
|
||||
for _, ib := range inbounds {
|
||||
inst, ok := amneziawg.InstanceFromInbound(ib)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if off := disabled[ib.Id]; len(off) > 0 {
|
||||
kept := make([]amneziawg.Peer, 0, len(inst.Peers))
|
||||
for _, p := range inst.Peers {
|
||||
if _, skip := off[p.Email]; !skip {
|
||||
kept = append(kept, p)
|
||||
}
|
||||
}
|
||||
inst.Peers = kept
|
||||
}
|
||||
if len(inst.Peers) == 0 {
|
||||
continue
|
||||
}
|
||||
instances = append(instances, inst)
|
||||
}
|
||||
return instances, nil
|
||||
}
|
||||
|
||||
// applyLocalAmneziaWG pushes a single local AmneziaWG inbound's current peer
|
||||
// set to its interface right after a client edit commits, so an add,
|
||||
// removal, re-key or enable-toggle takes effect immediately instead of
|
||||
// waiting up to 10s for the reconcile job. It re-reads the inbound so it sees
|
||||
// the committed settings, filters depleted clients exactly like the
|
||||
// reconcile job, and is a no-op for node-owned or non-AmneziaWG inbounds.
|
||||
// Failures are logged and swallowed: the reconcile job is the backstop.
|
||||
// Mirrors applyLocalMtproto.
|
||||
func (s *InboundService) applyLocalAmneziaWG(inboundId int) {
|
||||
inbound, err := s.GetInbound(inboundId)
|
||||
if err != nil || inbound == nil || inbound.Protocol != model.AmneziaWG || inbound.NodeID != nil {
|
||||
return
|
||||
}
|
||||
rt, err := s.runtimeFor(inbound)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
payload := inbound
|
||||
if inbound.Enable {
|
||||
if built, bErr := s.buildInboundForLocalRuntime(database.GetDB(), inbound); bErr == nil {
|
||||
payload = built
|
||||
}
|
||||
}
|
||||
if err := rt.UpdateInbound(context.Background(), inbound, payload); err != nil {
|
||||
logger.Debugf("amneziawg: immediate apply failed for inbound %d: %v", inboundId, err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaultAmneziaWGServer builds a fresh server block: a random AmneziaWG 3.1
|
||||
// obfuscation set, the default tunnel subnet/DNS, and a freshly generated
|
||||
// keypair.
|
||||
func defaultAmneziaWGServer() (*amneziawg.ServerSettings, error) {
|
||||
obf := amneziawg.GenerateObfuscation31()
|
||||
server := &amneziawg.ServerSettings{
|
||||
SubnetIP: "10.8.1.0",
|
||||
SubnetCIDR: 24,
|
||||
PrimaryDNS: "8.8.8.8",
|
||||
SecondaryDNS: "8.8.4.4",
|
||||
Jc: obf.Jc,
|
||||
Jmin: obf.Jmin,
|
||||
Jmax: obf.Jmax,
|
||||
S1: obf.S1,
|
||||
S2: obf.S2,
|
||||
S3: obf.S3,
|
||||
S4: obf.S4,
|
||||
H1: obf.H1,
|
||||
H2: obf.H2,
|
||||
H3: obf.H3,
|
||||
H4: obf.H4,
|
||||
I1: obf.I1,
|
||||
|
||||
HeaderProtectionKey: obf.HeaderProtectionKey,
|
||||
ContentPaddingAddition: obf.ContentPaddingAddition,
|
||||
RekeyAfterTime: obf.RekeyAfterTime,
|
||||
RekeyTimeout: obf.RekeyTimeout,
|
||||
RejectAfterTime: obf.RejectAfterTime,
|
||||
KeepaliveTimeout: obf.KeepaliveTimeout,
|
||||
MaxHandshakeAttempts: obf.MaxHandshakeAttempts,
|
||||
RandomTrailers: obf.RandomTrailers,
|
||||
DisableCookies: obf.DisableCookies,
|
||||
}
|
||||
if err := fillAmneziaWGServerKeys(server); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return server, nil
|
||||
}
|
||||
|
||||
// fillAmneziaWGServerKeys generates a real WireGuard-compatible keypair for
|
||||
// the server block when one is missing.
|
||||
func fillAmneziaWGServerKeys(server *amneziawg.ServerSettings) error {
|
||||
priv, pub, err := wgutil.GenerateWireguardKeypair()
|
||||
if err != nil {
|
||||
return fmt.Errorf("amneziawg: generate server keypair: %w", err)
|
||||
}
|
||||
server.PrivateKey = priv
|
||||
server.PublicKey = pub
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeAmneziaWGSettings ensures an AmneziaWG inbound's settings have a
|
||||
// valid server block, generating one (fresh obfuscation params + keypair) on
|
||||
// first save and validating a manually-edited one so a bad entry can't bring
|
||||
// the interface down on the next apply. A no-op for every other protocol.
|
||||
func (s *InboundService) normalizeAmneziaWGSettings(inbound *model.Inbound) error {
|
||||
if inbound.Protocol != model.AmneziaWG {
|
||||
return nil
|
||||
}
|
||||
|
||||
trimmed := strings.TrimSpace(inbound.Settings)
|
||||
if trimmed == "" || trimmed == "null" || trimmed == "{}" {
|
||||
server, err := defaultAmneziaWGServer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
settings := amneziawg.InboundSettings{Server: server, Clients: []model.Client{}}
|
||||
bs, err := json.MarshalIndent(settings, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
inbound.Settings = string(bs)
|
||||
return nil
|
||||
}
|
||||
|
||||
var parsed amneziawg.InboundSettings
|
||||
if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
|
||||
return fmt.Errorf("amneziawg: invalid settings: %w", err)
|
||||
}
|
||||
if parsed.Server == nil {
|
||||
server, err := defaultAmneziaWGServer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parsed.Server = server
|
||||
} else if parsed.Server.PrivateKey == "" {
|
||||
if err := fillAmneziaWGServerKeys(parsed.Server); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
parsed.Server.HeaderProtectionKey = strings.TrimSpace(parsed.Server.HeaderProtectionKey)
|
||||
for _, f := range []*string{
|
||||
&parsed.Server.ContentPaddingAddition, &parsed.Server.RekeyAfterTime,
|
||||
&parsed.Server.RekeyTimeout, &parsed.Server.RejectAfterTime,
|
||||
&parsed.Server.KeepaliveTimeout, &parsed.Server.MaxHandshakeAttempts,
|
||||
} {
|
||||
*f = amneziawg.CanonicalizeUintRange(*f)
|
||||
}
|
||||
if err := amneziawg.ValidateObfuscation(parsed.Server.Obfuscation()); err != nil {
|
||||
return fmt.Errorf("amneziawg: %w", err)
|
||||
}
|
||||
if err := amneziawg.ValidateIPv6Subnet(parsed.Server.IPv6Enabled, parsed.Server.IPv6Subnet); err != nil {
|
||||
return fmt.Errorf("amneziawg: %w", err)
|
||||
}
|
||||
if err := amneziawg.ValidateSubnetIPv4(parsed.Server.SubnetIP, parsed.Server.SubnetCIDR); err != nil {
|
||||
return fmt.Errorf("amneziawg: %w", err)
|
||||
}
|
||||
if err := amneziawg.ValidateInterfaceName(parsed.Server.ExternalInterface); err != nil {
|
||||
return fmt.Errorf("amneziawg: externalInterface: %w", err)
|
||||
}
|
||||
if err := amneziawg.ValidateInterfaceName(parsed.Server.IPv6ExternalInterface); err != nil {
|
||||
return fmt.Errorf("amneziawg: ipv6ExternalInterface: %w", err)
|
||||
}
|
||||
if err := amneziawg.ValidateConfigValue("privateKey", parsed.Server.PrivateKey); err != nil {
|
||||
return fmt.Errorf("amneziawg: %w", err)
|
||||
}
|
||||
if err := amneziawg.ValidateConfigValue("publicKey", parsed.Server.PublicKey); err != nil {
|
||||
return fmt.Errorf("amneziawg: %w", err)
|
||||
}
|
||||
signaturePackets := []struct{ field, v string }{
|
||||
{"i1", parsed.Server.I1},
|
||||
{"i2", parsed.Server.I2},
|
||||
{"i3", parsed.Server.I3},
|
||||
{"i4", parsed.Server.I4},
|
||||
{"i5", parsed.Server.I5},
|
||||
}
|
||||
for _, sp := range signaturePackets {
|
||||
if err := amneziawg.ValidateConfigValue(sp.field, sp.v); err != nil {
|
||||
return fmt.Errorf("amneziawg: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
portCtx, err := s.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range parsed.Clients {
|
||||
c := &parsed.Clients[i]
|
||||
if hit := s.checkForwardedPortsConflict(portCtx, c.ForwardedPorts); hit != "" {
|
||||
return fmt.Errorf("amneziawg: client %q forwardedPorts collides with %s", c.Email, hit)
|
||||
}
|
||||
if err := amneziawg.ValidateConfigValue("email", c.Email); err != nil {
|
||||
return fmt.Errorf("amneziawg: %w", err)
|
||||
}
|
||||
if err := amneziawg.ValidateConfigValue("publicKey", c.PublicKey); err != nil {
|
||||
return fmt.Errorf("amneziawg: client %q: %w", c.Email, err)
|
||||
}
|
||||
if err := amneziawg.ValidateConfigValue("preSharedKey", c.PreSharedKey); err != nil {
|
||||
return fmt.Errorf("amneziawg: client %q: %w", c.Email, err)
|
||||
}
|
||||
// AllowedIPs lands verbatim in a rendered [Peer] block, so a newline here
|
||||
// re-opens an [Interface] section whose PostUp runs as root once the
|
||||
// downloaded config is applied (client app, or awg-quick directly).
|
||||
normalized, err := normalizeWireguardAllowedIPs(c.AllowedIPs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("amneziawg: client %q: %w", c.Email, err)
|
||||
}
|
||||
c.AllowedIPs = normalized
|
||||
}
|
||||
|
||||
bs, err := json.MarshalIndent(parsed, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
inbound.Settings = string(bs)
|
||||
return nil
|
||||
}
|
||||
|
||||
// portConflictContext caches the state checkForwardedPortsConflict needs —
|
||||
// the panel's own port and this host's enabled inbound ports — so validating
|
||||
// N clients in one save (normalizeAmneziaWGSettings, or a bulk client add)
|
||||
// costs one query total instead of N. Load it once with
|
||||
// loadPortConflictContext and pass it to every checkForwardedPortsConflict
|
||||
// call in that batch.
|
||||
type portConflictContext struct {
|
||||
webPort int
|
||||
inbounds []*model.Inbound
|
||||
}
|
||||
|
||||
// loadPortConflictContext loads the panel's own port and every enabled
|
||||
// inbound hosted on THIS panel (node_id IS NULL) — an inbound hosted on a
|
||||
// different node listens on that node's own host, never this one, so it can
|
||||
// never collide with a DNAT rule this process installs.
|
||||
func (s *InboundService) loadPortConflictContext(db *gorm.DB) (portConflictContext, error) {
|
||||
var ctx portConflictContext
|
||||
if webPort, err := (&SettingService{}).GetPort(); err == nil {
|
||||
ctx.webPort = webPort
|
||||
}
|
||||
err := db.Model(model.Inbound{}).
|
||||
Where("enable = ? AND node_id IS NULL", true).
|
||||
Find(&ctx.inbounds).Error
|
||||
return ctx, err
|
||||
}
|
||||
|
||||
// checkForwardedPortsConflict reports whether a client's ForwardedPorts spec
|
||||
// exceeds the cap, covers the panel's own web port, one of this host's own
|
||||
// enabled inbound listen ports, or an AmneziaWG inbound's own phantom SOCKS5
|
||||
// relay port (SOCKSPortForInbound -- never a real inbounds row, so the loop
|
||||
// below can't see it any other way). A collision on the SOCKS5 port would
|
||||
// let a port-forward listener race Xray's own relay for the bind and, if it
|
||||
// wins, take down that inbound's entire relay rather than just one forward.
|
||||
// Returns a human-readable description of the first collision found, or ""
|
||||
// when there is none.
|
||||
func (s *InboundService) checkForwardedPortsConflict(ctx portConflictContext, forwardedPorts string) string {
|
||||
if forwardedPorts == "" {
|
||||
return ""
|
||||
}
|
||||
if amneziawg.ExceedsForwardedPortsCap(forwardedPorts) {
|
||||
return fmt.Sprintf("more than %d forwarded ports", amneziawg.MaxForwardedPorts)
|
||||
}
|
||||
if ctx.webPort > 0 && amneziawg.ForwardedPortsInclude(forwardedPorts, ctx.webPort) {
|
||||
return fmt.Sprintf("the panel's own port (%d)", ctx.webPort)
|
||||
}
|
||||
for _, ib := range ctx.inbounds {
|
||||
if amneziawg.ForwardedPortsInclude(forwardedPorts, ib.Port) {
|
||||
name := ib.Remark
|
||||
if name == "" {
|
||||
name = ib.Tag
|
||||
}
|
||||
return fmt.Sprintf("inbound '%s' (#%d, port %d)", name, ib.Id, ib.Port)
|
||||
}
|
||||
if ib.Protocol != model.AmneziaWG {
|
||||
continue
|
||||
}
|
||||
socksPort := amneziawgnet.SOCKSPortForInbound(ib.Id)
|
||||
if amneziawg.ForwardedPortsInclude(forwardedPorts, socksPort) {
|
||||
name := ib.Remark
|
||||
if name == "" {
|
||||
name = ib.Tag
|
||||
}
|
||||
return fmt.Sprintf("inbound '%s' (#%d)'s own SOCKS5 relay port (%d)", name, ib.Id, socksPort)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetAmneziaWGDiagnostics returns a live diagnostics snapshot for inbound
|
||||
// id: interface up/down, listen port, and per-client handshake/traffic
|
||||
// state, read entirely from data amneziawgnet.Manager already tracks --
|
||||
// gathering it can never itself change anything. Returns an error only
|
||||
// when id doesn't name an AmneziaWG inbound at all; an inbound that simply
|
||||
// isn't running right now (disabled, no enabled clients, or reconcile
|
||||
// hasn't caught up yet) comes back as amneziawgnet.Diagnostics{}
|
||||
// (Running=false), not an error, since that's a normal state an admin
|
||||
// might specifically be checking for.
|
||||
func (s *InboundService) GetAmneziaWGDiagnostics(id int) (amneziawgnet.Diagnostics, error) {
|
||||
inbound, err := s.GetInbound(id)
|
||||
if err != nil {
|
||||
return amneziawgnet.Diagnostics{}, err
|
||||
}
|
||||
if inbound.Protocol != model.AmneziaWG {
|
||||
return amneziawgnet.Diagnostics{}, fmt.Errorf("inbound %d is not an AmneziaWG inbound", id)
|
||||
}
|
||||
inst, ok := amneziawg.InstanceFromInbound(inbound)
|
||||
if !ok {
|
||||
return amneziawgnet.Diagnostics{}, nil
|
||||
}
|
||||
return amneziawgnet.Diagnose(inst.Id, inst.Peers), nil
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/op/go-logging"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
)
|
||||
|
||||
func TestCheckForwardedPortsConflict_EmptySpecNoConflict(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
svc := &InboundService{}
|
||||
ctx, err := svc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
t.Fatalf("loadPortConflictContext: %v", err)
|
||||
}
|
||||
if hit := svc.checkForwardedPortsConflict(ctx, ""); hit != "" {
|
||||
t.Fatalf("an empty spec must never conflict; got hit=%q", hit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckForwardedPortsConflict_CollidesWithPanelPort(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
svc := &InboundService{}
|
||||
ctx, err := svc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
t.Fatalf("loadPortConflictContext: %v", err)
|
||||
}
|
||||
// getString falls back to defaultValueMap's "webPort": "2053" on a fresh
|
||||
// DB with no explicit setting row.
|
||||
hit := svc.checkForwardedPortsConflict(ctx, "2053")
|
||||
if !strings.Contains(hit, "panel") {
|
||||
t.Fatalf("expected a collision naming the panel's own port, got %q", hit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckForwardedPortsConflict_CollidesWithEnabledInboundPort(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "vless-8080", "0.0.0.0", 8080, model.VLESS, `{"network":"tcp"}`, `{}`)
|
||||
|
||||
svc := &InboundService{}
|
||||
ctx, err := svc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
t.Fatalf("loadPortConflictContext: %v", err)
|
||||
}
|
||||
hit := svc.checkForwardedPortsConflict(ctx, "8075-8085")
|
||||
if !strings.Contains(hit, "vless-8080") {
|
||||
t.Fatalf("expected a collision naming the colliding inbound, got %q", hit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckForwardedPortsConflict_IgnoresDisabledInboundPort(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
disabled := &model.Inbound{Tag: "vless-8080-off", Enable: false, Listen: "0.0.0.0", Port: 8080, Protocol: model.VLESS, StreamSettings: `{"network":"tcp"}`}
|
||||
if err := database.GetDB().Create(disabled).Error; err != nil {
|
||||
t.Fatalf("seed disabled inbound: %v", err)
|
||||
}
|
||||
|
||||
svc := &InboundService{}
|
||||
ctx, err := svc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
t.Fatalf("loadPortConflictContext: %v", err)
|
||||
}
|
||||
if hit := svc.checkForwardedPortsConflict(ctx, "8080"); hit != "" {
|
||||
t.Fatalf("a disabled inbound's port must not be reserved; got hit=%q", hit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckForwardedPortsConflict_NoCollisionWhenPortsDontOverlap(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "vless-8080", "0.0.0.0", 8080, model.VLESS, `{"network":"tcp"}`, `{}`)
|
||||
|
||||
svc := &InboundService{}
|
||||
ctx, err := svc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
t.Fatalf("loadPortConflictContext: %v", err)
|
||||
}
|
||||
if hit := svc.checkForwardedPortsConflict(ctx, "9075-9085"); hit != "" {
|
||||
t.Fatalf("unrelated ports must not conflict; got hit=%q", hit)
|
||||
}
|
||||
}
|
||||
|
||||
// A port-forward spec matching a port used only by an inbound hosted on a
|
||||
// DIFFERENT node must not conflict: that inbound's DNAT/listen socket lives
|
||||
// on the node's own host, never on this panel's, so there is nothing here
|
||||
// for the forwarded port to actually collide with. Mirrors
|
||||
// TestCheckPortConflict_NodeScope's own reasoning for the general port-
|
||||
// conflict check.
|
||||
func TestCheckForwardedPortsConflict_IgnoresPortOnDifferentNode(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflictNode(t, "node1-8080", "0.0.0.0", 8080, model.VLESS, `{"network":"tcp"}`, `{}`, new(1))
|
||||
|
||||
svc := &InboundService{}
|
||||
ctx, err := svc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
t.Fatalf("loadPortConflictContext: %v", err)
|
||||
}
|
||||
if hit := svc.checkForwardedPortsConflict(ctx, "8080"); hit != "" {
|
||||
t.Fatalf("a port used only on a different node must not conflict; got hit=%q", hit)
|
||||
}
|
||||
}
|
||||
|
||||
// inboundAmneziaWGServer is pure (no DB), so it needs neither setupConflictDB
|
||||
// nor CGO/sqlite -- it can run in any Go environment.
|
||||
func TestInboundAmneziaWGServer_RedactsPrivateKey(t *testing.T) {
|
||||
settings := `{"server":{"privateKey":"super-secret","publicKey":"pub","mtu":1420,"headerProtectionKey":"MCPfRGcDGotJ6TcnIdDqsemj2cMIiGHnPUHM5ivXN18="},"clients":[]}`
|
||||
got := inboundAmneziaWGServer(string(model.AmneziaWG), settings)
|
||||
if got == nil {
|
||||
t.Fatal("expected a non-nil server block")
|
||||
}
|
||||
if got.PrivateKey != "" {
|
||||
t.Fatalf("PrivateKey must be redacted, got %q", got.PrivateKey)
|
||||
}
|
||||
if got.PublicKey != "pub" || got.MTU != 1420 {
|
||||
t.Fatalf("non-secret fields must still come through unchanged, got %+v", got)
|
||||
}
|
||||
// Unlike the private key, the header-protection key is shared with every
|
||||
// client config, so the clients page must receive it.
|
||||
if got.HeaderProtectionKey != "MCPfRGcDGotJ6TcnIdDqsemj2cMIiGHnPUHM5ivXN18=" {
|
||||
t.Fatalf("HeaderProtectionKey must NOT be redacted, got %q", got.HeaderProtectionKey)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAmneziaWGSettings_GeneratesFull31Set(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
svc := &InboundService{}
|
||||
inbound := &model.Inbound{Protocol: model.AmneziaWG, Port: 51820, Settings: ""}
|
||||
if err := svc.normalizeAmneziaWGSettings(inbound); err != nil {
|
||||
t.Fatalf("normalize empty settings: %v", err)
|
||||
}
|
||||
|
||||
var parsed amneziawg.InboundSettings
|
||||
if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed.Server == nil {
|
||||
t.Fatalf("normalized settings must carry a server block (err=%v): %s", err, inbound.Settings)
|
||||
}
|
||||
srv := parsed.Server
|
||||
|
||||
key, err := base64.StdEncoding.DecodeString(srv.HeaderProtectionKey)
|
||||
if err != nil || len(key) != 32 {
|
||||
t.Fatalf("headerProtectionKey = %q, must be base64 of 32 bytes (err=%v)", srv.HeaderProtectionKey, err)
|
||||
}
|
||||
for field, v := range map[string]string{
|
||||
"contentPaddingAddition": srv.ContentPaddingAddition,
|
||||
"rekeyAfterTime": srv.RekeyAfterTime,
|
||||
"rekeyTimeout": srv.RekeyTimeout,
|
||||
"rejectAfterTime": srv.RejectAfterTime,
|
||||
"keepaliveTimeout": srv.KeepaliveTimeout,
|
||||
"maxHandshakeAttempts": srv.MaxHandshakeAttempts,
|
||||
"i1": srv.I1,
|
||||
} {
|
||||
if v == "" {
|
||||
t.Errorf("fresh server block must fill %s", field)
|
||||
}
|
||||
}
|
||||
if !srv.RandomTrailers || !srv.DisableCookies {
|
||||
t.Errorf("fresh server block defaults RandomTrailers/DisableCookies on, got %v/%v", srv.RandomTrailers, srv.DisableCookies)
|
||||
}
|
||||
if srv.I2 != "" || srv.I3 != "" || srv.I4 != "" || srv.I5 != "" {
|
||||
t.Errorf("generated sets must leave I2-I5 empty, got %q/%q/%q/%q", srv.I2, srv.I3, srv.I4, srv.I5)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAmneziaWGSettings_RejectsBad31Values(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
svc := &InboundService{}
|
||||
cases := []struct {
|
||||
name string
|
||||
snippet string
|
||||
}{
|
||||
{"bad headerProtectionKey", `"headerProtectionKey":"short"`},
|
||||
{"zero rekeyTimeout", `"rekeyTimeout":"0"`},
|
||||
{"rekey overlapping reject", `"rekeyAfterTime":"100-200","rejectAfterTime":"150-300"`},
|
||||
{"control chars in i2", `"i2":"<r 64>\nPostUp = evil"`},
|
||||
{"line-wrapped headerProtectionKey", `"headerProtectionKey":"MCPfRGcDGotJ6Tcn\r\nIdDqsemj2cMIiGHnPUHM5ivXN18="`},
|
||||
}
|
||||
for _, c := range cases {
|
||||
inbound := &model.Inbound{
|
||||
Protocol: model.AmneziaWG,
|
||||
Port: 51820,
|
||||
Settings: `{"server":{"privateKey":"x","publicKey":"y","subnetIp":"10.8.1.0","subnetCidr":24,` + c.snippet + `},"clients":[]}`,
|
||||
}
|
||||
if err := svc.normalizeAmneziaWGSettings(inbound); err == nil {
|
||||
t.Errorf("%s must be rejected", c.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAmneziaWGSettings_CanonicalizesRangeValues(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
svc := &InboundService{}
|
||||
inbound := &model.Inbound{
|
||||
Protocol: model.AmneziaWG,
|
||||
Port: 51820,
|
||||
Settings: `{"server":{"privateKey":"x","publicKey":"y","subnetIp":"10.8.1.0","subnetCidr":24,` +
|
||||
`"rekeyAfterTime":"110 - 140","rejectAfterTime":"190-250","keepaliveTimeout":" "},"clients":[]}`,
|
||||
}
|
||||
if err := svc.normalizeAmneziaWGSettings(inbound); err != nil {
|
||||
t.Fatalf("normalize: %v", err)
|
||||
}
|
||||
var parsed amneziawg.InboundSettings
|
||||
if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil || parsed.Server == nil {
|
||||
t.Fatalf("re-parse normalized settings (err=%v): %s", err, inbound.Settings)
|
||||
}
|
||||
if parsed.Server.RekeyAfterTime != "110-140" {
|
||||
t.Errorf("rekeyAfterTime = %q, want canonical \"110-140\"", parsed.Server.RekeyAfterTime)
|
||||
}
|
||||
// A whitespace-only value must collapse to "feature off", not be stored
|
||||
// as a value the server emitter renders into an invalid blank line.
|
||||
if parsed.Server.KeepaliveTimeout != "" {
|
||||
t.Errorf("keepaliveTimeout = %q, want collapsed to empty", parsed.Server.KeepaliveTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundAmneziaWGServer_NonAmneziaWGReturnsNil(t *testing.T) {
|
||||
if got := inboundAmneziaWGServer(string(model.VLESS), `{"server":{"privateKey":"x"}}`); got != nil {
|
||||
t.Fatalf("a non-AmneziaWG protocol must return nil, got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundAmneziaWGServer_MissingServerBlockReturnsNil(t *testing.T) {
|
||||
if got := inboundAmneziaWGServer(string(model.AmneziaWG), `{"clients":[]}`); got != nil {
|
||||
t.Fatalf("settings with no server block must return nil, got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A newline inside a client's allowedIPs used to reach the rendered .conf,
|
||||
// where a following "[Interface]\nPostUp = ..." runs as root the moment
|
||||
// whoever applies that config (client app, or awg-quick directly) does so.
|
||||
func TestNormalizeAmneziaWGSettings_RejectsInjectedClientAllowedIPs(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
svc := &InboundService{}
|
||||
inbound := &model.Inbound{
|
||||
Protocol: model.AmneziaWG,
|
||||
Port: 51820,
|
||||
Settings: `{"server":{"privateKey":"x","publicKey":"y","subnetIp":"10.8.1.0","subnetCidr":24},` +
|
||||
`"clients":[{"email":"a@x","enable":true,"publicKey":"pk",` +
|
||||
`"allowedIPs":["10.8.1.2/32\n[Interface]\nPostUp = touch /tmp/pwned"]}]}`,
|
||||
}
|
||||
err := svc.normalizeAmneziaWGSettings(inbound)
|
||||
if err == nil {
|
||||
t.Fatalf("an allowedIPs entry carrying a config-injection payload must be rejected; settings became:\n%s", inbound.Settings)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "allowedIPs") {
|
||||
t.Errorf("error should name the offending field, got %q", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAmneziaWGSettings_CanonicalizesClientAllowedIPs(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
svc := &InboundService{}
|
||||
inbound := &model.Inbound{
|
||||
Protocol: model.AmneziaWG,
|
||||
Port: 51820,
|
||||
Settings: `{"server":{"privateKey":"x","publicKey":"y","subnetIp":"10.8.1.0","subnetCidr":24},` +
|
||||
`"clients":[{"email":"a@x","enable":true,"publicKey":"pk","allowedIPs":[" 10.8.1.2 "]}]}`,
|
||||
}
|
||||
if err := svc.normalizeAmneziaWGSettings(inbound); err != nil {
|
||||
t.Fatalf("normalize: %v", err)
|
||||
}
|
||||
var parsed amneziawg.InboundSettings
|
||||
if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
|
||||
t.Fatalf("re-parse normalized settings: %v", err)
|
||||
}
|
||||
if len(parsed.Clients) != 1 || len(parsed.Clients[0].AllowedIPs) != 1 || parsed.Clients[0].AllowedIPs[0] != "10.8.1.2/32" {
|
||||
t.Fatalf("allowedIPs = %v, want [\"10.8.1.2/32\"]", parsed.Clients)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAmneziaWGLogs_ClampsCountAndFiltersEvents(t *testing.T) {
|
||||
logger.InitLogger(logging.DEBUG)
|
||||
logger.Info("amneziawg: started interface awg1 for inbound 1")
|
||||
logger.Info("xray: unrelated line that must never show up here")
|
||||
logger.Warning("amneziawgnet: reconcile failed for inbound 2: handshake timeout")
|
||||
|
||||
svc := &ServerService{}
|
||||
logs := svc.GetAmneziaWGLogs("not-a-number", "")
|
||||
if logs == nil {
|
||||
t.Fatal("GetAmneziaWGLogs must never return nil")
|
||||
}
|
||||
for _, line := range logs.Events {
|
||||
if !strings.Contains(strings.ToLower(line), "amneziawg") {
|
||||
t.Fatalf("non-AmneziaWG line leaked into the event list: %q", line)
|
||||
}
|
||||
}
|
||||
if len(logs.Events) < 2 {
|
||||
t.Fatalf("both AmneziaWG lines should be present, got %v", logs.Events)
|
||||
}
|
||||
|
||||
// count caps the event list, so an operator asking for 1 gets 1.
|
||||
if one := svc.GetAmneziaWGLogs("1", ""); len(one.Events) != 1 {
|
||||
t.Fatalf("count=1 must cap the event list, got %d", len(one.Events))
|
||||
}
|
||||
// filter narrows further, case-insensitively.
|
||||
filtered := svc.GetAmneziaWGLogs("100", "RECONCILE")
|
||||
if len(filtered.Events) != 1 || !strings.Contains(filtered.Events[0], "reconcile") {
|
||||
t.Fatalf("filter must narrow to the matching line, got %v", filtered.Events)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckForwardedPortsConflict_RejectsSpecOverCap(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
svc := &InboundService{}
|
||||
ctx, err := svc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
t.Fatalf("loadPortConflictContext: %v", err)
|
||||
}
|
||||
spec := fmt.Sprintf("20000-%d", 20000+amneziawg.MaxForwardedPorts)
|
||||
hit := svc.checkForwardedPortsConflict(ctx, spec)
|
||||
if !strings.Contains(hit, fmt.Sprintf("%d", amneziawg.MaxForwardedPorts)) {
|
||||
t.Fatalf("expected a collision naming the %d-port cap, got %q", amneziawg.MaxForwardedPorts, hit)
|
||||
}
|
||||
}
|
||||
|
||||
// A spec covering exactly MaxForwardedPorts ports is AT the cap, not over
|
||||
// it, and must be accepted -- ExpandForwardedPorts truncates there by
|
||||
// design, so a naive len(...) >= cap comparison can't tell the two apart.
|
||||
func TestCheckForwardedPortsConflict_AcceptsSpecExactlyAtCap(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
svc := &InboundService{}
|
||||
ctx, err := svc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
t.Fatalf("loadPortConflictContext: %v", err)
|
||||
}
|
||||
spec := fmt.Sprintf("20000-%d", 20000+amneziawg.MaxForwardedPorts-1)
|
||||
if hit := svc.checkForwardedPortsConflict(ctx, spec); hit != "" {
|
||||
t.Fatalf("a spec covering exactly %d ports must be accepted, got collision %q", amneziawg.MaxForwardedPorts, hit)
|
||||
}
|
||||
}
|
||||
|
||||
// The SOCKS5 relay port an enabled AmneziaWG inbound gets (SOCKSPortForInbound)
|
||||
// is a phantom, non-DB-row port -- ctx.inbounds alone can't see it, so
|
||||
// checkForwardedPortsConflict must check it explicitly.
|
||||
func TestCheckForwardedPortsConflict_CollidesWithAmneziawgnetSocksPort(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, `{}`)
|
||||
|
||||
var awgInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded row: %v", err)
|
||||
}
|
||||
relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
|
||||
|
||||
svc := &InboundService{}
|
||||
ctx, err := svc.loadPortConflictContext(database.GetDB())
|
||||
if err != nil {
|
||||
t.Fatalf("loadPortConflictContext: %v", err)
|
||||
}
|
||||
hit := svc.checkForwardedPortsConflict(ctx, fmt.Sprintf("%d", relayPort))
|
||||
if !strings.Contains(hit, "SOCKS5") {
|
||||
t.Fatalf("expected a collision naming the AmneziaWG inbound's SOCKS5 relay port, got %q", hit)
|
||||
}
|
||||
}
|
||||
|
||||
// A cleared DNS field is meaningful (no DNS line in client configs) and must
|
||||
// survive the save round-trip instead of resurrecting the frontend defaults.
|
||||
func TestNormalizeAmneziaWGSettingsKeepsClearedDNS(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
server, err := defaultAmneziaWGServer()
|
||||
if err != nil {
|
||||
t.Fatalf("defaultAmneziaWGServer: %v", err)
|
||||
}
|
||||
server.PrimaryDNS = ""
|
||||
server.SecondaryDNS = ""
|
||||
bs, err := json.Marshal(amneziawg.InboundSettings{Server: server, Clients: []model.Client{}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal settings: %v", err)
|
||||
}
|
||||
inbound := &model.Inbound{Protocol: model.AmneziaWG, Settings: string(bs)}
|
||||
if err := (&InboundService{}).normalizeAmneziaWGSettings(inbound); err != nil {
|
||||
t.Fatalf("normalizeAmneziaWGSettings: %v", err)
|
||||
}
|
||||
for _, key := range []string{`"primaryDns"`, `"secondaryDns"`} {
|
||||
if !strings.Contains(inbound.Settings, key) {
|
||||
t.Fatalf("cleared %s dropped from persisted settings:\n%s", key, inbound.Settings)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,24 @@ func inboundCanEnableTlsFlow(protocol, streamSettings, settings string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// nodeEligibleProtocols mirrors the frontend's NODE_ELIGIBLE_PROTOCOLS. The
|
||||
// sidecar-managed protocols are absent because their reconcile loops only query
|
||||
// NodeID IS NULL rows, so a node-assigned one would never be reconciled at all.
|
||||
// A new protocol defaults to ineligible until added here, as on the frontend.
|
||||
var nodeEligibleProtocols = map[model.Protocol]bool{
|
||||
model.VLESS: true,
|
||||
model.VMESS: true,
|
||||
model.Trojan: true,
|
||||
model.Shadowsocks: true,
|
||||
model.Hysteria: true,
|
||||
model.WireGuard: true,
|
||||
}
|
||||
|
||||
// isNodeEligibleProtocol reports whether protocol may be assigned to a node.
|
||||
func isNodeEligibleProtocol(protocol model.Protocol) bool {
|
||||
return nodeEligibleProtocols[protocol]
|
||||
}
|
||||
|
||||
// vlessEncryptionEnabled reports whether a VLESS inbound has VLESS-level
|
||||
// encryption (vlessenc / ML-KEM) configured. When enabled these fields hold a
|
||||
// generated dotted string (e.g. "mlkem768x25519plus.native.0rtt.<key>"); "none"
|
||||
|
||||
@@ -88,3 +88,21 @@ func TestInboundCanHostFallbacks_StaysTcpOnly(t *testing.T) {
|
||||
t.Errorf("inboundCanHostFallbacks(nil) = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
// Mirrors NODE_ELIGIBLE_PROTOCOLS in
|
||||
// frontend/src/pages/inbounds/form/InboundFormModal.tsx -- keep both lists
|
||||
// in sync if a protocol's node-eligibility ever changes.
|
||||
func TestIsNodeEligibleProtocol(t *testing.T) {
|
||||
eligible := []model.Protocol{model.VLESS, model.VMESS, model.Trojan, model.Shadowsocks, model.Hysteria, model.WireGuard}
|
||||
for _, p := range eligible {
|
||||
if !isNodeEligibleProtocol(p) {
|
||||
t.Errorf("isNodeEligibleProtocol(%q) = false, want true", p)
|
||||
}
|
||||
}
|
||||
ineligible := []model.Protocol{model.MTProto, model.AmneziaWG, model.Mixed, model.HTTP, model.Tunnel}
|
||||
for _, p := range ineligible {
|
||||
if isNodeEligibleProtocol(p) {
|
||||
t.Errorf("isNodeEligibleProtocol(%q) = true, want false", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +79,10 @@ func (s *InboundService) applyTrafficMutationBatch(b *trafficMutationBatch) bool
|
||||
s.applyLocalMtproto(plan.inbound.Id)
|
||||
continue
|
||||
}
|
||||
if plan.inbound.Protocol == model.AmneziaWG {
|
||||
s.applyLocalAmneziaWG(plan.inbound.Id)
|
||||
continue
|
||||
}
|
||||
rt, err := s.runtimeFor(&plan.inbound)
|
||||
if err == nil {
|
||||
switch plan.action {
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
||||
@@ -22,7 +24,7 @@ const (
|
||||
func inboundTransports(protocol model.Protocol, streamSettings, settings string) transportBits {
|
||||
// protocols that ignore streamSettings entirely.
|
||||
switch protocol {
|
||||
case model.Hysteria, model.WireGuard:
|
||||
case model.Hysteria, model.WireGuard, model.AmneziaWG:
|
||||
return transportUDP
|
||||
case model.MTProto:
|
||||
return transportTCP
|
||||
@@ -183,6 +185,36 @@ func checkPortConflictTx(db *gorm.DB, inbound *model.Inbound, ignoreId int) (*po
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Every enabled local AmneziaWG inbound gets its own automatic Xray
|
||||
// SOCKS5 relay inbound (see injectAmneziawgnetSocks) on 127.0.0.1 at a
|
||||
// port derived purely from its id (amneziawgnet.SOCKSPortForInbound) --
|
||||
// like the internal Xray API inbound above, that relay inbound is not
|
||||
// itself a database row, so the ordinary DB-backed query below can never
|
||||
// see it. Without this check, an unrelated inbound saved onto that exact
|
||||
// port silently fails at the next Xray start, taking every other
|
||||
// protocol down with it, not just AmneziaWG.
|
||||
if inbound.NodeID == nil && listenOverlaps("127.0.0.1", inbound.Listen) {
|
||||
conflict, err := checkAmneziawgnetSocksConflict(db, inbound, ignoreId, newBits)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if conflict != nil {
|
||||
return conflict, nil
|
||||
}
|
||||
}
|
||||
|
||||
// The reverse direction, only meaningful once the id is known (create's
|
||||
// ignoreId==0 means AddInbound must run this itself after Save assigns one).
|
||||
if inbound.Protocol == model.AmneziaWG && ignoreId > 0 {
|
||||
conflict, err := checkAmneziawgnetSocksReverseConflict(db, ignoreId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if conflict != nil {
|
||||
return conflict, nil
|
||||
}
|
||||
}
|
||||
|
||||
var candidates []*model.Inbound
|
||||
q := db.Model(model.Inbound{}).Where("port = ?", inbound.Port)
|
||||
if ignoreId > 0 {
|
||||
@@ -216,6 +248,72 @@ func checkPortConflictTx(db *gorm.DB, inbound *model.Inbound, ignoreId int) (*po
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// checkAmneziawgnetSocksConflict reports whether inbound's own port
|
||||
// collides with an existing, enabled local AmneziaWG inbound's automatic
|
||||
// Xray SOCKS5 relay port. Unlike the retired kernel-module bridge this
|
||||
// checks every qualifying AmneziaWG inbound unconditionally: the embedded
|
||||
// relay has no RouteThroughXray-style opt-in, every one of them gets a
|
||||
// relay inbound (see injectAmneziawgnetSocks). ignoreId excludes one inbound
|
||||
// id from the AmneziaWG candidates, the same way the general DB-backed
|
||||
// conflict query above excludes the inbound being edited from matching
|
||||
// itself. Takes db rather than fetching its own handle so it runs inside the
|
||||
// same serialized transaction as the rest of checkPortConflictTx (#6225) --
|
||||
// otherwise two concurrent AmneziaWG creates could both pass this check
|
||||
// before either row commits.
|
||||
func checkAmneziawgnetSocksConflict(db *gorm.DB, inbound *model.Inbound, ignoreId int, newBits transportBits) (*portConflictDetail, error) {
|
||||
var candidates []*model.Inbound
|
||||
q := db.Model(model.Inbound{}).Where("protocol = ? AND enable = ? AND node_id IS NULL", model.AmneziaWG, true)
|
||||
if ignoreId > 0 {
|
||||
q = q.Where("id != ?", ignoreId)
|
||||
}
|
||||
if err := q.Find(&candidates).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if _, ok := amneziawg.InstanceFromInbound(c); !ok {
|
||||
continue
|
||||
}
|
||||
if amneziawgnet.SOCKSPortForInbound(c.Id) != inbound.Port {
|
||||
continue
|
||||
}
|
||||
return &portConflictDetail{
|
||||
InboundID: c.Id,
|
||||
Remark: c.Remark,
|
||||
Tag: c.Tag,
|
||||
Listen: "127.0.0.1",
|
||||
Port: inbound.Port,
|
||||
Transports: newBits,
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// checkAmneziawgnetSocksReverseConflict mirrors checkAmneziawgnetSocksConflict:
|
||||
// does id's own derived relay port collide with some other inbound's port.
|
||||
func checkAmneziawgnetSocksReverseConflict(db *gorm.DB, id int) (*portConflictDetail, error) {
|
||||
relayPort := amneziawgnet.SOCKSPortForInbound(id)
|
||||
var candidates []*model.Inbound
|
||||
if err := db.Model(model.Inbound{}).
|
||||
Where("port = ? AND node_id IS NULL AND id != ?", relayPort, id).
|
||||
Find(&candidates).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if !listenOverlaps("127.0.0.1", c.Listen) {
|
||||
continue
|
||||
}
|
||||
return &portConflictDetail{
|
||||
InboundID: c.Id,
|
||||
Remark: c.Remark,
|
||||
Tag: c.Tag,
|
||||
Listen: c.Listen,
|
||||
Port: relayPort,
|
||||
Transports: transportTCP,
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func sameNode(a, b *int) bool {
|
||||
if a == nil && b == nil {
|
||||
return true
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/op/go-logging"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
@@ -729,3 +730,198 @@ func TestCheckPortConflict_ReservedAPIPortUDPCoexists(t *testing.T) {
|
||||
t.Fatalf("udp-only inbound must coexist with the tcp API inbound; got=%v err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// amneziawgRoutedSettings builds a minimal but complete AmneziaWG settings
|
||||
// blob with one qualifying, enabled peer -- the shape that makes
|
||||
// injectAmneziawgnetSocks (and therefore checkAmneziawgnetSocksConflict)
|
||||
// create a relay inbound at all. The routeThroughXray field is kept in the
|
||||
// JSON (a stale value from a pre-cutover install) specifically to prove
|
||||
// it's now ignored -- see the "RouteThroughXrayOff" test below.
|
||||
const amneziawgRoutedSettings = `{"server":{"privateKey":"priv","publicKey":"pub","subnetIp":"10.8.1.0","subnetCidr":24,"routeThroughXray":true},"clients":[{"email":"a@x","enable":true,"publicKey":"pub-a","allowedIPs":["10.8.1.2/32"]}]}`
|
||||
|
||||
// An enabled AmneziaWG inbound's automatic Xray SOCKS5 relay inbound
|
||||
// (injectAmneziawgnetSocks) is a synthetic loopback inbound, not a database
|
||||
// row, so checkPortConflict needs its own check to catch a collision --
|
||||
// exactly the same shape of problem as the reserved API port above.
|
||||
func TestCheckPortConflict_AmneziawgnetSocksRelayBlockedLocal(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
|
||||
|
||||
var awgInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded row: %v", err)
|
||||
}
|
||||
relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
|
||||
|
||||
svc := &InboundService{}
|
||||
candidate := &model.Inbound{
|
||||
Tag: "vless-bridge",
|
||||
Listen: "0.0.0.0",
|
||||
Port: relayPort,
|
||||
Protocol: model.VLESS,
|
||||
}
|
||||
got, err := svc.checkPortConflict(candidate, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("checkPortConflict: %v", err)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatalf("a local inbound on the AmneziaWG relay port %d must conflict", relayPort)
|
||||
}
|
||||
if msg := got.String(); !strings.Contains(msg, "awg-1") {
|
||||
t.Fatalf("conflict message should name the owning AmneziaWG inbound; got %q", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Nodes run their own Xray, so a node inbound landing on the central panel's
|
||||
// AmneziaWG relay port must be allowed -- the relay inbound only ever binds
|
||||
// 127.0.0.1 on the local panel's own Xray.
|
||||
func TestCheckPortConflict_AmneziawgnetSocksRelayAllowedOnNode(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
|
||||
|
||||
var awgInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded row: %v", err)
|
||||
}
|
||||
relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
|
||||
|
||||
svc := &InboundService{}
|
||||
candidate := &model.Inbound{
|
||||
Tag: "node-bridge",
|
||||
Listen: "0.0.0.0",
|
||||
Port: relayPort,
|
||||
Protocol: model.VLESS,
|
||||
NodeID: new(1),
|
||||
}
|
||||
if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
|
||||
t.Fatalf("a node inbound on the local AmneziaWG relay port must be allowed; got=%v err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A disabled AmneziaWG inbound never gets a relay inbound injected
|
||||
// (injectAmneziawgnetSocks skips !inbound.Enable), so its "reserved" port
|
||||
// must not block anything.
|
||||
func TestCheckPortConflict_AmneziawgnetSocksRelayIgnoredWhenDisabled(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
awg := &model.Inbound{Tag: "awg-1", Enable: false, Listen: "0.0.0.0", Port: 51820, Protocol: model.AmneziaWG, Settings: `{}`}
|
||||
if err := database.GetDB().Create(awg).Error; err != nil {
|
||||
t.Fatalf("seed disabled awg inbound: %v", err)
|
||||
}
|
||||
relayPort := amneziawgnet.SOCKSPortForInbound(awg.Id)
|
||||
|
||||
svc := &InboundService{}
|
||||
candidate := &model.Inbound{
|
||||
Tag: "vless-bridge",
|
||||
Listen: "0.0.0.0",
|
||||
Port: relayPort,
|
||||
Protocol: model.VLESS,
|
||||
}
|
||||
if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
|
||||
t.Fatalf("a disabled AmneziaWG inbound's port must not be reserved; got=%v err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Unlike the retired kernel-module bridge, the embedded relay has no
|
||||
// RouteThroughXray-style opt-in -- every qualifying AmneziaWG inbound
|
||||
// reserves its relay port regardless of that (now-vestigial) field's value,
|
||||
// including a stale routeThroughXray:true left over from a pre-cutover
|
||||
// install (amneziawgRoutedSettings).
|
||||
func TestCheckPortConflict_AmneziawgnetSocksRelayReservedRegardlessOfLegacyRouteThroughXrayField(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, `{"server":{"privateKey":"priv","publicKey":"pub","subnetIp":"10.8.1.0","subnetCidr":24},"clients":[{"email":"a@x","enable":true,"publicKey":"pub-a","allowedIPs":["10.8.1.2/32"]}]}`)
|
||||
|
||||
var awgInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded row: %v", err)
|
||||
}
|
||||
relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
|
||||
|
||||
svc := &InboundService{}
|
||||
candidate := &model.Inbound{
|
||||
Tag: "vless-bridge",
|
||||
Listen: "0.0.0.0",
|
||||
Port: relayPort,
|
||||
Protocol: model.VLESS,
|
||||
}
|
||||
got, err := svc.checkPortConflict(candidate, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("checkPortConflict: %v", err)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatalf("an enabled, qualifying AmneziaWG inbound must reserve its relay port even with RouteThroughXray left at its default")
|
||||
}
|
||||
}
|
||||
|
||||
// A qualifying AmneziaWG inbound with no enabled/valid peer at all never
|
||||
// gets a relay inbound (amneziawg.InstanceFromInbound returns ok=false), so
|
||||
// its port isn't reserved.
|
||||
func TestCheckPortConflict_AmneziawgnetSocksRelayIgnoredWhenNoQualifyingPeer(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, `{}`)
|
||||
|
||||
var awgInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded row: %v", err)
|
||||
}
|
||||
relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
|
||||
|
||||
svc := &InboundService{}
|
||||
candidate := &model.Inbound{
|
||||
Tag: "vless-bridge",
|
||||
Listen: "0.0.0.0",
|
||||
Port: relayPort,
|
||||
Protocol: model.VLESS,
|
||||
}
|
||||
if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
|
||||
t.Fatalf("an AmneziaWG inbound with no qualifying peer must not reserve its relay port; got=%v err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// An unrelated port never conflicts with the relay inbound.
|
||||
func TestCheckPortConflict_AmneziawgnetSocksRelayDifferentPortAllowed(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
|
||||
|
||||
svc := &InboundService{}
|
||||
candidate := &model.Inbound{
|
||||
Tag: "vless-elsewhere",
|
||||
Listen: "0.0.0.0",
|
||||
Port: 9999,
|
||||
Protocol: model.VLESS,
|
||||
}
|
||||
if got, err := svc.checkPortConflict(candidate, 0); err != nil || got != nil {
|
||||
t.Fatalf("an unrelated port must not conflict with the AmneziaWG relay inbound; got=%v err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The reverse direction: saving an AmneziaWG inbound whose own derived relay
|
||||
// port happens to equal another inbound's real port must also be rejected,
|
||||
// not just the already-covered "someone else picks my relay port" case.
|
||||
func TestCheckPortConflict_AmneziawgnetSocksRelayReverseDirectionBlockedOnUpdate(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
|
||||
|
||||
var awgInbound model.Inbound
|
||||
if err := database.GetDB().Where("tag = ?", "awg-1").First(&awgInbound).Error; err != nil {
|
||||
t.Fatalf("read seeded row: %v", err)
|
||||
}
|
||||
relayPort := amneziawgnet.SOCKSPortForInbound(awgInbound.Id)
|
||||
seedInboundConflict(t, "vless-1", "0.0.0.0", relayPort, model.VLESS, ``, `{}`)
|
||||
|
||||
svc := &InboundService{}
|
||||
candidate := &model.Inbound{
|
||||
Id: awgInbound.Id,
|
||||
Tag: "awg-1",
|
||||
Listen: "0.0.0.0",
|
||||
Port: 51820,
|
||||
Protocol: model.AmneziaWG,
|
||||
Settings: amneziawgRoutedSettings,
|
||||
}
|
||||
got, err := svc.checkPortConflict(candidate, awgInbound.Id)
|
||||
if err != nil {
|
||||
t.Fatalf("checkPortConflict: %v", err)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatalf("awg-1's own derived relay port %d collides with vless-1's real port; must be rejected", relayPort)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"archive/zip"
|
||||
"bufio"
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"mime/multipart"
|
||||
stdnet "net"
|
||||
"net/http"
|
||||
@@ -28,6 +30,8 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
@@ -89,6 +93,13 @@ type Status struct {
|
||||
ErrorMsg string `json:"errorMsg"`
|
||||
Version string `json:"version"`
|
||||
} `json:"xray"`
|
||||
// AmneziaWG gates the overview's AmneziaWG log view: Configured stays true
|
||||
// while an inbound exists but its embedded interface isn't up yet, which
|
||||
// is exactly when that view's event lines are worth reading.
|
||||
AmneziaWG struct {
|
||||
Configured bool `json:"configured"`
|
||||
Running bool `json:"running"`
|
||||
} `json:"amneziawg"`
|
||||
PanelVersion string `json:"panelVersion"`
|
||||
PanelGuid string `json:"panelGuid"`
|
||||
Uptime uint64 `json:"uptime"`
|
||||
@@ -611,6 +622,16 @@ func (s *ServerService) GetStatus(lastStatus *Status) *Status {
|
||||
status.Xray.ErrorMsg = s.xrayService.GetXrayResult()
|
||||
}
|
||||
status.Xray.Version = s.xrayService.GetXrayVersion()
|
||||
|
||||
var amneziawgCount int64
|
||||
if err := database.GetDB().Model(model.Inbound{}).
|
||||
Where("protocol = ? AND enable = ? AND node_id IS NULL", model.AmneziaWG, true).
|
||||
Count(&amneziawgCount).Error; err != nil {
|
||||
logger.Warning("count amneziawg inbounds failed:", err)
|
||||
}
|
||||
status.AmneziaWG.Configured = amneziawgCount > 0
|
||||
status.AmneziaWG.Running = amneziawgnet.GetManager().HasRunning()
|
||||
|
||||
status.PanelVersion = config.GetPanelVersion()
|
||||
if guid, err := s.settingService.GetPanelGuid(); err == nil {
|
||||
status.PanelGuid = guid
|
||||
@@ -1167,6 +1188,148 @@ func parseAccessLogFields(line string) LogEntry {
|
||||
return entry
|
||||
}
|
||||
|
||||
// PeerActivity is one peer's live embedded-Device-reported state, the
|
||||
// counterpart of an Xray access-log entry: a tunnel logs no requests, only
|
||||
// handshakes and bytes.
|
||||
type PeerActivity struct {
|
||||
Interface string `json:"interface" example:"awg1"`
|
||||
Tag string `json:"tag" example:"inbound-51820"`
|
||||
InboundId int `json:"inboundId" example:"1"`
|
||||
Email string `json:"email" example:"peer@example.com"`
|
||||
Endpoint string `json:"endpoint" example:"203.0.113.9:51820"`
|
||||
AllowedIPs string `json:"allowedIPs" example:"10.8.1.2/32"`
|
||||
// Handshake is unix milliseconds, 0 when the peer has never connected.
|
||||
Handshake int64 `json:"handshake" example:"1735732800000"`
|
||||
Up int64 `json:"up" example:"1048576"`
|
||||
Down int64 `json:"down" example:"4194304"`
|
||||
Online bool `json:"online" example:"true"`
|
||||
}
|
||||
|
||||
// amneziawgOnlineWindow mirrors the standard WireGuard convention (and this
|
||||
// fork's own prior kernel-module behavior): a handshake this recent counts
|
||||
// as online.
|
||||
const amneziawgOnlineWindow = 180 * time.Second
|
||||
|
||||
// AmneziaWGLogs is what the overview's AmneziaWG log view renders: the live
|
||||
// per-peer activity of every running embedded interface, plus the panel's
|
||||
// own recent AmneziaWG lifecycle log lines that explain a peer being absent
|
||||
// from Peers at all.
|
||||
type AmneziaWGLogs struct {
|
||||
Peers []PeerActivity `json:"peers"`
|
||||
Events []string `json:"events" example:"[\"2025/01/01 12:00:00 amneziawg: started interface awg1 for inbound 1\"]"`
|
||||
Running bool `json:"running" example:"true"`
|
||||
}
|
||||
|
||||
// amneziawgEventMarker selects the panel's own AmneziaWG log lines: every
|
||||
// logger call in internal/amneziawg, internal/amneziawgnet and their jobs
|
||||
// prefixes its message with it.
|
||||
const amneziawgEventMarker = "amneziawg"
|
||||
|
||||
// amneziawgLogActivity gathers live PeerActivity rows across every enabled,
|
||||
// non-node-hosted AmneziaWG inbound, newest handshake first. An inbound
|
||||
// amneziawgnet has no running Device for yet (not reconciled, disabled,
|
||||
// errored) contributes no rows -- not reported as an error, since the
|
||||
// caller (GetAmneziaWGLogs) already has a device-agnostic Running flag from
|
||||
// amneziawgnet.GetManager().HasRunning() for that.
|
||||
// clampUint64ToInt64 saturates at math.MaxInt64 instead of wrapping negative,
|
||||
// for a live uint64 byte counter (amneziawgnet's own UAPI-dump snapshot, not
|
||||
// a DB-accumulated total) going into an int64 API field -- unreachable in
|
||||
// practice at real traffic volumes, but a silent negative value would be
|
||||
// worse than a saturated one if it were ever hit.
|
||||
func clampUint64ToInt64(v uint64) int64 {
|
||||
if v > math.MaxInt64 {
|
||||
return math.MaxInt64
|
||||
}
|
||||
return int64(v)
|
||||
}
|
||||
|
||||
func amneziawgLogActivity() []PeerActivity {
|
||||
var inbounds []*model.Inbound
|
||||
if err := database.GetDB().
|
||||
Where("protocol = ? AND enable = ? AND node_id IS NULL", model.AmneziaWG, true).
|
||||
Find(&inbounds).Error; err != nil {
|
||||
logger.Warning("amneziawg logs: list inbounds failed:", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
var out []PeerActivity
|
||||
for _, inbound := range inbounds {
|
||||
inst, ok := amneziawg.InstanceFromInbound(inbound)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
diag := amneziawgnet.Diagnose(inbound.Id, inst.Peers)
|
||||
if !diag.Running {
|
||||
continue
|
||||
}
|
||||
for _, cd := range diag.Clients {
|
||||
var handshakeMs int64
|
||||
online := false
|
||||
if !cd.LastHandshake.IsZero() {
|
||||
handshakeMs = cd.LastHandshake.UnixMilli()
|
||||
online = now.Sub(cd.LastHandshake) < amneziawgOnlineWindow
|
||||
}
|
||||
out = append(out, PeerActivity{
|
||||
Interface: inst.InterfaceName,
|
||||
Tag: inbound.Tag,
|
||||
InboundId: inbound.Id,
|
||||
Email: cd.Email,
|
||||
Endpoint: cd.Endpoint,
|
||||
AllowedIPs: cd.AllowedIPs,
|
||||
Handshake: handshakeMs,
|
||||
Up: clampUint64ToInt64(cd.RxBytes),
|
||||
Down: clampUint64ToInt64(cd.TxBytes),
|
||||
Online: online,
|
||||
})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(out, func(a, b PeerActivity) int {
|
||||
if a.Handshake != b.Handshake {
|
||||
return cmp.Compare(b.Handshake, a.Handshake)
|
||||
}
|
||||
return strings.Compare(a.Email, b.Email)
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// GetAmneziaWGLogs returns at most count peer rows and count event lines,
|
||||
// optionally narrowed to rows whose text contains filter (case-insensitive),
|
||||
// mirroring GetXrayLogs' own count+filter contract.
|
||||
func (s *ServerService) GetAmneziaWGLogs(count string, filter string) *AmneziaWGLogs {
|
||||
limit, err := strconv.Atoi(count)
|
||||
if err != nil || limit < 1 || limit > 10000 {
|
||||
limit = 100
|
||||
}
|
||||
needle := strings.ToLower(strings.TrimSpace(filter))
|
||||
|
||||
logs := &AmneziaWGLogs{Peers: []PeerActivity{}, Events: []string{}, Running: amneziawgnet.GetManager().HasRunning()}
|
||||
|
||||
for _, peer := range amneziawgLogActivity() {
|
||||
if len(logs.Peers) >= limit {
|
||||
break
|
||||
}
|
||||
if needle != "" && !strings.Contains(strings.ToLower(peer.Email+" "+peer.Tag+" "+peer.Interface+" "+peer.Endpoint+" "+peer.AllowedIPs), needle) {
|
||||
continue
|
||||
}
|
||||
logs.Peers = append(logs.Peers, peer)
|
||||
}
|
||||
|
||||
for _, line := range logger.GetLogs(10000, "debug") {
|
||||
if len(logs.Events) >= limit {
|
||||
break
|
||||
}
|
||||
if !strings.Contains(strings.ToLower(line), amneziawgEventMarker) {
|
||||
continue
|
||||
}
|
||||
if needle != "" && !strings.Contains(strings.ToLower(line), needle) {
|
||||
continue
|
||||
}
|
||||
logs.Events = append(logs.Events, line)
|
||||
}
|
||||
return logs
|
||||
}
|
||||
|
||||
func (s *ServerService) GetXrayLogs(
|
||||
count string,
|
||||
filter string,
|
||||
|
||||
@@ -158,6 +158,7 @@ func (t *Tgbot) getInboundsAddClient() (*telego.InlineKeyboardMarkup, error) {
|
||||
model.Tunnel: true,
|
||||
model.Mixed: true,
|
||||
model.WireGuard: true,
|
||||
model.AmneziaWG: true,
|
||||
model.HTTP: true,
|
||||
}
|
||||
|
||||
@@ -202,6 +203,7 @@ func (t *Tgbot) getInboundsAttachPicker() (*telego.InlineKeyboardMarkup, error)
|
||||
model.Tunnel: true,
|
||||
model.Mixed: true,
|
||||
model.WireGuard: true,
|
||||
model.AmneziaWG: true,
|
||||
model.HTTP: true,
|
||||
}
|
||||
selected := make(map[int]bool, len(receiver_inbound_IDs))
|
||||
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
@@ -172,7 +174,7 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
|
||||
if inbound.NodeID != nil {
|
||||
continue
|
||||
}
|
||||
if inbound.Protocol == model.MTProto {
|
||||
if inbound.Protocol == model.MTProto || inbound.Protocol == model.AmneziaWG {
|
||||
continue
|
||||
}
|
||||
settings := map[string]any{}
|
||||
@@ -369,6 +371,27 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
|
||||
injectMtprotoEgress(xrayConfig, inbound)
|
||||
}
|
||||
|
||||
// Every AmneziaWG inbound is embedded (internal/amneziawgnet: amneziawg-go
|
||||
// over a gVisor netstack, no kernel module) and relays every peer's
|
||||
// decapsulated traffic into its own loopback SOCKS5 inbound, always on —
|
||||
// unlike mtproto's bridge above, there's no opt-in gate here: once
|
||||
// traffic is decapsulated in gVisor, Xray's own freedom outbound is the
|
||||
// only way it reaches the real internet at all, not an optional extra
|
||||
// hop. Whether it goes anywhere beyond Xray's default routing is up to
|
||||
// whatever rules the admin adds through the stock Routing page, exactly
|
||||
// like routing any other protocol.
|
||||
injectAmneziawgnetSocks(xrayConfig, inbounds)
|
||||
|
||||
// Restores each opted-in peer's own distinct public IPv6 source identity
|
||||
// for its outbound connections — a peer that has an IPv6 address in its
|
||||
// AllowedIPs, on an inbound with IPv6Enabled, gets its own freedom
|
||||
// outbound bound to that exact address via sendThrough.
|
||||
// internal/amneziawgnet's own Manager is responsible for actually
|
||||
// aliasing that address onto the host (see v6alias.go) so the kernel
|
||||
// lets Xray bind an egress socket to it at all; this call only builds
|
||||
// the Xray-side outbound/routing-rule half.
|
||||
injectAmneziawgV6Egress(xrayConfig, inbounds)
|
||||
|
||||
// Wire the panel's own HTTP traffic through the configured outbound, after
|
||||
// the subscription merge so subscription outbound tags are valid targets.
|
||||
if egressTag, err := s.settingService.GetPanelOutbound(); err != nil {
|
||||
@@ -663,6 +686,223 @@ func injectMtprotoEgress(cfg *xray.Config, inbound *model.Inbound) {
|
||||
})
|
||||
}
|
||||
|
||||
// amneziawgEgressSniffingSettings matches this fork's normal per-inbound
|
||||
// default (see default.json's "mixed" inbound). Without this, domain-based
|
||||
// Routing rules can never match this relay: the peer resolved DNS
|
||||
// itself, through the tunnel, before ever sending a packet — by the time the
|
||||
// embedded forwarder recovers the decapsulated traffic, the destination is
|
||||
// already a bare IP, with no domain name attached at the network layer at
|
||||
// all. Sniffing recovers it from the payload itself (TLS SNI / HTTP Host /
|
||||
// QUIC) the same way it already does for every other inbound; without it,
|
||||
// only tag/IP/network-based rules can ever match this traffic, and any
|
||||
// domain rule above it in the list is silently unreachable.
|
||||
const amneziawgEgressSniffingSettings = `{"enabled":true,"destOverride":["http","tls","quic","fakedns"]}`
|
||||
|
||||
// injectAmneziawgnetSocks gives every enabled AmneziaWG inbound with at
|
||||
// least one qualifying peer its own loopback SOCKS5 inbound for the
|
||||
// embedded (amneziawg-go) relay path (internal/amneziawgnet) -- always on,
|
||||
// since there is no alternative datapath once traffic is decapsulated in
|
||||
// gVisor: Xray's own freedom outbound is how it reaches the real internet at
|
||||
// all (see internal/amneziawgnet/relay.go's doc comment, Finding 3 of the
|
||||
// migration plan). Tagged with the inbound's own real tag: it's already
|
||||
// selectable in the panel's stock Routing page (InboundService.GetInboundTags
|
||||
// is protocol-blind), and per-inbound traffic totals
|
||||
// (internal/web/service/inbound_traffic.go's addClientTraffic) match by
|
||||
// exact tag -- reusing it isn't a style choice.
|
||||
func injectAmneziawgnetSocks(cfg *xray.Config, inbounds []*model.Inbound) {
|
||||
existingTags := make(map[string]struct{}, len(cfg.InboundConfigs))
|
||||
for i := range cfg.InboundConfigs {
|
||||
existingTags[cfg.InboundConfigs[i].Tag] = struct{}{}
|
||||
}
|
||||
|
||||
for _, inbound := range inbounds {
|
||||
if inbound.Protocol != model.AmneziaWG || !inbound.Enable || inbound.NodeID != nil {
|
||||
continue
|
||||
}
|
||||
inst, ok := amneziawg.InstanceFromInbound(inbound)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if _, taken := existingTags[inbound.Tag]; taken {
|
||||
logger.Warning("amneziawgnet socks: inbound tag [", inbound.Tag, "] already present in generated config, skipping its relay inbound")
|
||||
continue
|
||||
}
|
||||
|
||||
emails := make([]string, 0, len(inst.Peers))
|
||||
for _, p := range inst.Peers {
|
||||
if p.Email != "" {
|
||||
emails = append(emails, p.Email)
|
||||
}
|
||||
}
|
||||
if len(emails) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
settings, err := amneziawgnet.SocksInboundSettings(emails, amneziawgnet.SocksPassword())
|
||||
if err != nil {
|
||||
logger.Warning("amneziawgnet socks: building settings for inbound [", inbound.Tag, "]: ", err)
|
||||
continue
|
||||
}
|
||||
|
||||
existingTags[inbound.Tag] = struct{}{}
|
||||
cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
|
||||
Listen: json_util.RawMessage(`"127.0.0.1"`),
|
||||
Port: amneziawgnet.SOCKSPortForInbound(inbound.Id),
|
||||
Protocol: "socks",
|
||||
Settings: json_util.RawMessage(settings),
|
||||
Sniffing: json_util.RawMessage(amneziawgEgressSniffingSettings),
|
||||
Tag: inbound.Tag,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// amneziawgV6EgressTag returns the stable, globally-unique freedom outbound
|
||||
// tag for one peer's IPv6 source-identity egress. Stable across config
|
||||
// regenerations (a pure function of two stable identifiers), so
|
||||
// internal/xray/hot_diff.go's tag-keyed outbound/routing diffing recognizes
|
||||
// "unchanged" rather than remove+recreate on every poll. The inbound.Id
|
||||
// prefix is defense in depth, not load-bearing on its own: email is already
|
||||
// enforced globally unique across the whole panel's client table
|
||||
// (model.ClientRecord.Email has a gorm uniqueIndex) — kept anyway since it
|
||||
// costs nothing and makes the tag self-describing, matching
|
||||
// NodeEgressInboundTag's own style.
|
||||
func amneziawgV6EgressTag(inboundID int, email string) string {
|
||||
return fmt.Sprintf("amneziawg-v6-%d-%s", inboundID, email)
|
||||
}
|
||||
|
||||
// injectAmneziawgV6Egress gives every enabled, non-node-hosted AmneziaWG
|
||||
// peer with an IPv6 AllowedIPs entry its own single-purpose freedom
|
||||
// outbound, bound via sendThrough to that exact address, plus a routing
|
||||
// rule sending only that peer's own traffic through it — restoring the
|
||||
// per-client public IPv6 identity the hard cutover temporarily dropped
|
||||
// (Phase 3.5 of the migration plan). Scoped to outbound source identity
|
||||
// only: it depends on internal/amneziawgnet's own alias mechanism actually
|
||||
// giving the host that address at the OS level (see v6alias.go's
|
||||
// V6AliasesActive, the exact same gate this function uses below) — without
|
||||
// that, sendThrough fails to bind and every connection through it errors
|
||||
// outright (freedom.go's dial failure); there is no fallback outbound.
|
||||
//
|
||||
// The routing rule matches both inboundTag and user: SocksInboundSettings
|
||||
// (used by injectAmneziawgnetSocks above) already authenticates each
|
||||
// connection as the peer's own email via stock SOCKS5 auth, and a stock
|
||||
// Xray SOCKS5 inbound sets that connection's stats/routing identity from
|
||||
// the authenticated username — so "user" reliably isolates exactly one
|
||||
// peer's traffic, the same building block Finding 3 of the migration plan
|
||||
// already established for per-client stats.
|
||||
//
|
||||
// Modeled on injectNodeEgresses (the established N-per-slice inbound+rule
|
||||
// precedent, not injectAmneziawgnetSocks itself, which only ever emits a
|
||||
// single inbound and never touches outbounds/routing) and
|
||||
// mergeSubscriptionOutbounds's unmarshal-append-remarshal pattern for
|
||||
// cfg.OutboundConfigs. Synthetic rules are prepended ahead of whatever's
|
||||
// already in the routing rules array, the same pattern injectNodeEgresses/
|
||||
// injectMtprotoEgress already use for their own always-must-win infra
|
||||
// rules — this never touches the admin's own saved Routing-page rule
|
||||
// order.
|
||||
func injectAmneziawgV6Egress(cfg *xray.Config, inbounds []*model.Inbound) {
|
||||
// Protocol is checked alongside Tag, not just Tag alone: a tag collision
|
||||
// with some unrelated (non-socks) inbound must not be mistaken for this
|
||||
// instance's own relay having been created.
|
||||
liveInboundTags := make(map[string]struct{}, len(cfg.InboundConfigs))
|
||||
for i := range cfg.InboundConfigs {
|
||||
if cfg.InboundConfigs[i].Protocol == "socks" {
|
||||
liveInboundTags[cfg.InboundConfigs[i].Tag] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
var existingOutbounds []any
|
||||
if len(cfg.OutboundConfigs) > 0 {
|
||||
if err := json.Unmarshal(cfg.OutboundConfigs, &existingOutbounds); err != nil {
|
||||
logger.Warning("amneziawg v6 egress: outbounds section is unparsable, skipping injection:", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
usedOutboundTags := make(map[string]struct{}, len(existingOutbounds))
|
||||
for _, o := range existingOutbounds {
|
||||
if m, ok := o.(map[string]any); ok {
|
||||
if t, ok := m["tag"].(string); ok {
|
||||
usedOutboundTags[t] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
routing := map[string]any{}
|
||||
if len(cfg.RouterConfig) > 0 {
|
||||
if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
|
||||
logger.Warning("amneziawg v6 egress: routing section is unparsable, skipping injection:", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
rules, _ := routing["rules"].([]any)
|
||||
newRules := make([]any, 0)
|
||||
newOutbounds := make([]any, 0)
|
||||
|
||||
for _, inbound := range inbounds {
|
||||
if inbound.Protocol != model.AmneziaWG || !inbound.Enable || inbound.NodeID != nil {
|
||||
continue
|
||||
}
|
||||
if _, live := liveInboundTags[inbound.Tag]; !live {
|
||||
// The relay inbound itself wasn't created this pass (e.g. a tag
|
||||
// collision inside injectAmneziawgnetSocks) -- no SOCKS5 inbound
|
||||
// exists for hot_diff.go's inboundTag match to ever fire against.
|
||||
continue
|
||||
}
|
||||
inst, ok := amneziawg.InstanceFromInbound(inbound)
|
||||
if !ok || !amneziawgnet.V6AliasesActive(inst) {
|
||||
continue
|
||||
}
|
||||
for _, p := range inst.Peers {
|
||||
if p.Email == "" {
|
||||
continue
|
||||
}
|
||||
v6 := amneziawg.FirstIPv6(p.AllowedIPs)
|
||||
if v6 == "" {
|
||||
continue
|
||||
}
|
||||
tag := amneziawgV6EgressTag(inbound.Id, p.Email)
|
||||
if _, taken := usedOutboundTags[tag]; taken {
|
||||
logger.Warning("amneziawg v6 egress: outbound tag [", tag, "] already exists, skipping peer [", p.Email, "]")
|
||||
continue
|
||||
}
|
||||
usedOutboundTags[tag] = struct{}{}
|
||||
newOutbounds = append(newOutbounds, map[string]any{
|
||||
"tag": tag,
|
||||
"protocol": "freedom",
|
||||
"sendThrough": v6,
|
||||
"settings": map[string]any{},
|
||||
})
|
||||
newRules = append(newRules, map[string]any{
|
||||
"type": "field",
|
||||
"inboundTag": []any{inbound.Tag},
|
||||
"user": []any{p.Email},
|
||||
"outboundTag": tag,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if len(newOutbounds) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
merged := make([]any, 0, len(existingOutbounds))
|
||||
merged = append(merged, existingOutbounds...)
|
||||
merged = append(merged, newOutbounds...)
|
||||
combined, err := json.MarshalIndent(merged, "", " ")
|
||||
if err != nil {
|
||||
logger.Warning("amneziawg v6 egress: failed to rebuild outbounds section, skipping injection:", err)
|
||||
return
|
||||
}
|
||||
cfg.OutboundConfigs = json_util.RawMessage(combined)
|
||||
|
||||
routing["rules"] = append(newRules, rules...)
|
||||
newRouting, err := json.Marshal(routing)
|
||||
if err != nil {
|
||||
logger.Warning("amneziawg v6 egress: failed to rebuild routing section, skipping injection:", err)
|
||||
return
|
||||
}
|
||||
cfg.RouterConfig = json_util.RawMessage(newRouting)
|
||||
}
|
||||
|
||||
// mergeSubscriptionOutbounds appends the subscription outbounds to the
|
||||
// OutboundConfigs array of the xray config. It works on the already-unmarshaled
|
||||
// template so that manually configured outbounds are never overwritten.
|
||||
|
||||
@@ -3,8 +3,11 @@ package service
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
|
||||
@@ -557,3 +560,456 @@ func TestInjectMtprotoEgress_BadRoutingSkips(t *testing.T) {
|
||||
t.Fatalf("unparsable routing must be left untouched, got %s", cfg.RouterConfig)
|
||||
}
|
||||
}
|
||||
|
||||
func amneziawgInbound(id int, tag string, clients []model.Client) *model.Inbound {
|
||||
server := amneziawg.ServerSettings{SubnetIP: "10.8.1.0", SubnetCIDR: 24}
|
||||
settings, _ := json.Marshal(amneziawg.InboundSettings{Server: &server, Clients: clients})
|
||||
return &model.Inbound{Id: id, Tag: tag, Protocol: model.AmneziaWG, Enable: true, Settings: string(settings)}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgnetSocks_CreatesRelayTaggedWithInboundsOwnTag(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
before := string(cfg.RouterConfig)
|
||||
inbound := amneziawgInbound(7, "awg-7", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32"}},
|
||||
})
|
||||
injectAmneziawgnetSocks(cfg, []*model.Inbound{inbound})
|
||||
|
||||
if len(cfg.InboundConfigs) != 2 {
|
||||
t.Fatalf("expected the relay inbound to be appended, got %d inbounds", len(cfg.InboundConfigs))
|
||||
}
|
||||
ib := cfg.InboundConfigs[1]
|
||||
if ib.Tag != "awg-7" || ib.Protocol != "socks" || ib.Port != amneziawgnet.SOCKSPortForInbound(7) {
|
||||
t.Fatalf("relay inbound must reuse the inbound's own tag (so per-inbound stats totals keep matching, and it's already selectable in the stock Routing page) and this instance's own derived port, got %+v", ib)
|
||||
}
|
||||
if string(ib.Listen) != `"127.0.0.1"` {
|
||||
t.Fatalf("relay inbound must listen on loopback, got %s", ib.Listen)
|
||||
}
|
||||
if !strings.Contains(string(ib.Settings), `"auth":"password"`) || !strings.Contains(string(ib.Settings), `"udp":true`) {
|
||||
t.Fatalf("relay inbound must require password auth and allow UDP ASSOCIATE, got %s", ib.Settings)
|
||||
}
|
||||
if !strings.Contains(string(ib.Settings), `"a@x"`) {
|
||||
t.Fatalf("relay inbound must have an account for the peer's email, got %s", ib.Settings)
|
||||
}
|
||||
if !strings.Contains(string(ib.Sniffing), `"enabled":true`) {
|
||||
t.Fatalf("relay inbound must enable sniffing -- a peer's own DNS resolution means the decapsulated traffic never carries a domain at the network layer, so domain-based Routing rules can only ever match via sniffing the payload, got %s", ib.Sniffing)
|
||||
}
|
||||
// No auto-generated routing rule: it's entirely up to the admin's own
|
||||
// Routing-page rules, same as any other protocol's inbound tag.
|
||||
if string(cfg.RouterConfig) != before {
|
||||
t.Fatalf("injectAmneziawgnetSocks must never touch the routing section, got %s", cfg.RouterConfig)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgnetSocks_MultipleInboundsEachGetOwnRelay(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
inbound1 := amneziawgInbound(1, "awg-1", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32"}},
|
||||
})
|
||||
inbound2 := amneziawgInbound(2, "awg-2", []model.Client{
|
||||
{Email: "b@x", Enable: true, PublicKey: "pub-b", AllowedIPs: []string{"10.9.1.2/32"}},
|
||||
})
|
||||
injectAmneziawgnetSocks(cfg, []*model.Inbound{inbound1, inbound2})
|
||||
|
||||
if len(cfg.InboundConfigs) != 3 {
|
||||
t.Fatalf("expected one relay inbound per inbound (plus the pre-existing one), got %d inbounds: %+v", len(cfg.InboundConfigs), cfg.InboundConfigs)
|
||||
}
|
||||
byTag := map[string]int{}
|
||||
for _, ib := range cfg.InboundConfigs[1:] {
|
||||
byTag[ib.Tag] = ib.Port
|
||||
}
|
||||
if byTag["awg-1"] != amneziawgnet.SOCKSPortForInbound(1) || byTag["awg-2"] != amneziawgnet.SOCKSPortForInbound(2) {
|
||||
t.Fatalf("each inbound must get its own tag and its own derived port, got %+v", byTag)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgnetSocks_NoQualifyingPeerSkipsRelay(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
client model.Client
|
||||
enable bool
|
||||
}{
|
||||
{"client disabled", model.Client{Email: "a@x", Enable: false, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32"}}, true},
|
||||
{"no PublicKey", model.Client{Email: "a@x", Enable: true, AllowedIPs: []string{"10.8.1.2/32"}}, true},
|
||||
{"no AllowedIPs", model.Client{Email: "a@x", Enable: true, PublicKey: "pub-a"}, true},
|
||||
{"inbound disabled", model.Client{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32"}}, false},
|
||||
{"no Email", model.Client{Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32"}}, true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
inbound := amneziawgInbound(1, "awg-1", []model.Client{c.client})
|
||||
inbound.Enable = c.enable
|
||||
injectAmneziawgnetSocks(cfg, []*model.Inbound{inbound})
|
||||
if len(cfg.InboundConfigs) != 1 {
|
||||
t.Fatalf("%s must be a no-op, got %d inbounds", c.name, len(cfg.InboundConfigs))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgnetSocks_AlwaysOnRegardlessOfLegacyRouteThroughXrayField(t *testing.T) {
|
||||
// Unlike the retired kernel-module bridge, the embedded relay has no
|
||||
// opt-in gate: there is no alternative datapath once traffic is
|
||||
// decapsulated in gVisor. A stale RouteThroughXray=false left over from
|
||||
// a pre-cutover install must not suppress the relay inbound.
|
||||
cfg := egressTestConfig()
|
||||
server := amneziawg.ServerSettings{SubnetIP: "10.8.1.0", SubnetCIDR: 24, RouteThroughXray: false}
|
||||
settings, _ := json.Marshal(amneziawg.InboundSettings{
|
||||
Server: &server,
|
||||
Clients: []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32"}},
|
||||
},
|
||||
})
|
||||
inbound := &model.Inbound{Id: 1, Tag: "awg-1", Protocol: model.AmneziaWG, Enable: true, Settings: string(settings)}
|
||||
injectAmneziawgnetSocks(cfg, []*model.Inbound{inbound})
|
||||
if len(cfg.InboundConfigs) != 2 {
|
||||
t.Fatalf("the relay inbound must always be created regardless of RouteThroughXray, got %+v", cfg.InboundConfigs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgnetSocks_WrongProtocolOrNodeSkipped(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
vless := &model.Inbound{Id: 1, Tag: "in-1", Protocol: model.VLESS, Enable: true}
|
||||
nodeID := 5
|
||||
nodeHosted := amneziawgInbound(2, "awg-2", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32"}},
|
||||
})
|
||||
nodeHosted.NodeID = &nodeID
|
||||
injectAmneziawgnetSocks(cfg, []*model.Inbound{vless, nodeHosted})
|
||||
if len(cfg.InboundConfigs) != 1 {
|
||||
t.Fatalf("a non-AmneziaWG or node-hosted inbound must never get a relay inbound, got %+v", cfg.InboundConfigs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgnetSocks_TagCollisionSkipsThatInboundOnly(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
cfg.InboundConfigs = append(cfg.InboundConfigs,
|
||||
xray.InboundConfig{Port: 1234, Protocol: "vless", Tag: "awg-1"})
|
||||
inbound1 := amneziawgInbound(1, "awg-1", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32"}},
|
||||
})
|
||||
inbound2 := amneziawgInbound(2, "awg-2", []model.Client{
|
||||
{Email: "b@x", Enable: true, PublicKey: "pub-b", AllowedIPs: []string{"10.9.1.2/32"}},
|
||||
})
|
||||
injectAmneziawgnetSocks(cfg, []*model.Inbound{inbound1, inbound2})
|
||||
|
||||
// Started with 2 (api + the colliding vless entry); only awg-2's relay
|
||||
// inbound should have been added, awg-1's skipped since its tag is taken.
|
||||
if len(cfg.InboundConfigs) != 3 {
|
||||
t.Fatalf("expected only the non-colliding inbound's relay inbound to be added, got %+v", cfg.InboundConfigs)
|
||||
}
|
||||
found := false
|
||||
for _, ib := range cfg.InboundConfigs {
|
||||
if ib.Tag == "awg-2" && ib.Protocol == "socks" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("awg-2's relay inbound must still be created despite awg-1's tag collision")
|
||||
}
|
||||
}
|
||||
|
||||
// amneziawgV6Inbound builds an AmneziaWG inbound with IPv6 enabled and a
|
||||
// given external interface -- amneziawgInbound's own ServerSettings never
|
||||
// sets these, so injectAmneziawgV6Egress's tests need their own variant.
|
||||
func amneziawgV6Inbound(id int, tag string, ext6 string, clients []model.Client) *model.Inbound {
|
||||
server := amneziawg.ServerSettings{
|
||||
SubnetIP: "10.8.1.0", SubnetCIDR: 24,
|
||||
IPv6Enabled: true, IPv6ExternalInterface: ext6,
|
||||
}
|
||||
settings, _ := json.Marshal(amneziawg.InboundSettings{Server: &server, Clients: clients})
|
||||
return &model.Inbound{Id: id, Tag: tag, Protocol: model.AmneziaWG, Enable: true, Settings: string(settings)}
|
||||
}
|
||||
|
||||
// amneziawgV6InboundNotActive builds an inbound that fails V6AliasesActive
|
||||
// (either toggle can do it), unlike amneziawgV6Inbound which always passes it.
|
||||
func amneziawgV6InboundNotActive(id int, tag string, ipv6Enabled bool, ext6 string, clients []model.Client) *model.Inbound {
|
||||
server := amneziawg.ServerSettings{
|
||||
SubnetIP: "10.8.1.0", SubnetCIDR: 24,
|
||||
IPv6Enabled: ipv6Enabled, IPv6ExternalInterface: ext6,
|
||||
}
|
||||
settings, _ := json.Marshal(amneziawg.InboundSettings{Server: &server, Clients: clients})
|
||||
return &model.Inbound{Id: id, Tag: tag, Protocol: model.AmneziaWG, Enable: true, Settings: string(settings)}
|
||||
}
|
||||
|
||||
// injectAmneziawgV6Egress runs after injectAmneziawgnetSocks in the real
|
||||
// GetXrayConfig() pipeline and depends on its relay inbound already
|
||||
// existing (see the "live" tag check) -- every test below calls both, in
|
||||
// that order, to match production.
|
||||
func injectAmneziawgSocksThenV6(cfg *xray.Config, inbounds []*model.Inbound) {
|
||||
injectAmneziawgnetSocks(cfg, inbounds)
|
||||
injectAmneziawgV6Egress(cfg, inbounds)
|
||||
}
|
||||
|
||||
type v6EgressRouting struct {
|
||||
Rules []struct {
|
||||
InboundTag []string `json:"inboundTag"`
|
||||
User []string `json:"user"`
|
||||
OutboundTag string `json:"outboundTag"`
|
||||
Type string `json:"type"`
|
||||
} `json:"rules"`
|
||||
}
|
||||
|
||||
type v6EgressOutbound struct {
|
||||
Tag string `json:"tag"`
|
||||
Protocol string `json:"protocol"`
|
||||
SendThrough string `json:"sendThrough"`
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgV6Egress_CreatesOutboundAndRuleForV6Peer(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
inbound := amneziawgV6Inbound(7, "awg-7", "eth0", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32", "fd86:ea04:1115::2/128"}},
|
||||
})
|
||||
injectAmneziawgSocksThenV6(cfg, []*model.Inbound{inbound})
|
||||
|
||||
var outbounds []v6EgressOutbound
|
||||
if err := json.Unmarshal(cfg.OutboundConfigs, &outbounds); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantTag := amneziawgV6EgressTag(7, "a@x")
|
||||
var got *v6EgressOutbound
|
||||
for i := range outbounds {
|
||||
if outbounds[i].Tag == wantTag {
|
||||
got = &outbounds[i]
|
||||
}
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatalf("expected an outbound tagged %q, got %+v", wantTag, outbounds)
|
||||
}
|
||||
if got.Protocol != "freedom" || got.SendThrough != "fd86:ea04:1115::2" {
|
||||
t.Fatalf("outbound must be a freedom outbound bound to the peer's own v6 address, got %+v", got)
|
||||
}
|
||||
// Pre-existing outbounds (direct, warp) must survive untouched.
|
||||
if len(outbounds) != 3 {
|
||||
t.Fatalf("expected the 2 pre-existing outbounds plus 1 new one, got %+v", outbounds)
|
||||
}
|
||||
|
||||
var routing v6EgressRouting
|
||||
if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ruleIdx := -1
|
||||
for i := range routing.Rules {
|
||||
if routing.Rules[i].OutboundTag == wantTag {
|
||||
ruleIdx = i
|
||||
}
|
||||
}
|
||||
if ruleIdx == -1 {
|
||||
t.Fatalf("expected a routing rule targeting %q, got %+v", wantTag, routing.Rules)
|
||||
}
|
||||
rule := routing.Rules[ruleIdx]
|
||||
if rule.Type != "field" || len(rule.User) != 1 || rule.User[0] != "a@x" ||
|
||||
len(rule.InboundTag) != 1 || rule.InboundTag[0] != "awg-7" {
|
||||
t.Fatalf("rule must match this peer's email and inbound tag, got %+v", rule)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgV6Egress_SkipsPeerWithoutV6Address(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
before := string(cfg.OutboundConfigs)
|
||||
inbound := amneziawgV6Inbound(1, "awg-1", "eth0", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32"}}, // v4 only
|
||||
})
|
||||
injectAmneziawgSocksThenV6(cfg, []*model.Inbound{inbound})
|
||||
if string(cfg.OutboundConfigs) != before {
|
||||
t.Fatalf("a peer with no v6 AllowedIPs entry must not get an outbound, got %s", cfg.OutboundConfigs)
|
||||
}
|
||||
}
|
||||
|
||||
// The documented "leave the interface blank to auto-detect" happy path must
|
||||
// not silently emit a sendThrough for an address the host was never told to
|
||||
// own -- there is no auto-detect, so that would fail every connection.
|
||||
func TestInjectAmneziawgV6Egress_SkipsWhenIPv6EnabledButInterfaceBlank(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
before := string(cfg.OutboundConfigs)
|
||||
inbound := amneziawgV6InboundNotActive(1, "awg-1", true, "", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32", "fd86::2/128"}},
|
||||
})
|
||||
injectAmneziawgSocksThenV6(cfg, []*model.Inbound{inbound})
|
||||
if string(cfg.OutboundConfigs) != before {
|
||||
t.Fatalf("IPv6Enabled with a blank interface must not get an outbound (no auto-detect exists), got %s", cfg.OutboundConfigs)
|
||||
}
|
||||
}
|
||||
|
||||
// The inverse of amneziawgV6Inbound's own always-true IPv6Enabled: a filled
|
||||
// IPv6ExternalInterface alone (e.g. left over from a previous enable) must
|
||||
// not activate egress on its own.
|
||||
func TestInjectAmneziawgV6Egress_SkipsWhenIPv6DisabledEvenWithInterfaceSet(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
before := string(cfg.OutboundConfigs)
|
||||
inbound := amneziawgV6InboundNotActive(1, "awg-1", false, "eth0", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"10.8.1.2/32", "fd86::2/128"}},
|
||||
})
|
||||
injectAmneziawgSocksThenV6(cfg, []*model.Inbound{inbound})
|
||||
if string(cfg.OutboundConfigs) != before {
|
||||
t.Fatalf("IPv6Enabled false must not get an outbound even with a leftover interface set, got %s", cfg.OutboundConfigs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgV6Egress_MultiplePeersEachGetOwnOutboundAndRule(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
inbound := amneziawgV6Inbound(1, "awg-1", "eth0", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"fd86:ea04:1115::2/128"}},
|
||||
{Email: "b@x", Enable: true, PublicKey: "pub-b", AllowedIPs: []string{"fd86:ea04:1115::3/128"}},
|
||||
})
|
||||
injectAmneziawgSocksThenV6(cfg, []*model.Inbound{inbound})
|
||||
|
||||
var outbounds []v6EgressOutbound
|
||||
if err := json.Unmarshal(cfg.OutboundConfigs, &outbounds); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tagA, tagB := amneziawgV6EgressTag(1, "a@x"), amneziawgV6EgressTag(1, "b@x")
|
||||
seen := map[string]string{}
|
||||
for _, o := range outbounds {
|
||||
seen[o.Tag] = o.SendThrough
|
||||
}
|
||||
if seen[tagA] != "fd86:ea04:1115::2" || seen[tagB] != "fd86:ea04:1115::3" {
|
||||
t.Fatalf("each peer must get its own outbound bound to its own address, got %+v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgV6Egress_StableTagAcrossRegenerations(t *testing.T) {
|
||||
// Same instance data, two independent injections -- hot_diff.go relies on
|
||||
// the tag being a pure function of (inboundID, email) so it recognizes
|
||||
// "unchanged" rather than remove+recreate on every poll.
|
||||
inbound := amneziawgV6Inbound(1, "awg-1", "eth0", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"fd86:ea04:1115::2/128"}},
|
||||
})
|
||||
cfg1 := egressTestConfig()
|
||||
injectAmneziawgSocksThenV6(cfg1, []*model.Inbound{inbound})
|
||||
cfg2 := egressTestConfig()
|
||||
injectAmneziawgSocksThenV6(cfg2, []*model.Inbound{inbound})
|
||||
|
||||
var out1, out2 []v6EgressOutbound
|
||||
json.Unmarshal(cfg1.OutboundConfigs, &out1)
|
||||
json.Unmarshal(cfg2.OutboundConfigs, &out2)
|
||||
if len(out1) != len(out2) || out1[len(out1)-1].Tag != out2[len(out2)-1].Tag {
|
||||
t.Fatalf("tag must be stable across independent regenerations, got %+v vs %+v", out1, out2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgV6Egress_SkipsWrongProtocolOrNodeHostedOrDisabled(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
before := string(cfg.OutboundConfigs)
|
||||
vless := &model.Inbound{Id: 1, Tag: "in-1", Protocol: model.VLESS, Enable: true}
|
||||
nodeID := 5
|
||||
nodeHosted := amneziawgV6Inbound(2, "awg-2", "eth0", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"fd86:ea04:1115::2/128"}},
|
||||
})
|
||||
nodeHosted.NodeID = &nodeID
|
||||
disabled := amneziawgV6Inbound(3, "awg-3", "eth0", []model.Client{
|
||||
{Email: "b@x", Enable: true, PublicKey: "pub-b", AllowedIPs: []string{"fd86:ea04:1115::3/128"}},
|
||||
})
|
||||
disabled.Enable = false
|
||||
injectAmneziawgSocksThenV6(cfg, []*model.Inbound{vless, nodeHosted, disabled})
|
||||
if string(cfg.OutboundConfigs) != before {
|
||||
t.Fatalf("wrong-protocol, node-hosted, and disabled inbounds must never get a v6 outbound, got %s", cfg.OutboundConfigs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgV6Egress_SkipsWhenRelayInboundNotCreated(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
// A pre-existing inbound already holds this AmneziaWG inbound's tag, so
|
||||
// injectAmneziawgnetSocks (called first, matching production order)
|
||||
// skips creating its relay SOCKS5 inbound entirely.
|
||||
cfg.InboundConfigs = append(cfg.InboundConfigs,
|
||||
xray.InboundConfig{Port: 1234, Protocol: "vless", Tag: "awg-1"})
|
||||
before := string(cfg.OutboundConfigs)
|
||||
inbound := amneziawgV6Inbound(1, "awg-1", "eth0", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"fd86:ea04:1115::2/128"}},
|
||||
})
|
||||
injectAmneziawgSocksThenV6(cfg, []*model.Inbound{inbound})
|
||||
if string(cfg.OutboundConfigs) != before {
|
||||
t.Fatalf("no v6 outbound should be created when the relay inbound itself never got created, got %s", cfg.OutboundConfigs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgV6Egress_OutboundTagCollisionSkipsThatPeerOnly(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
inbound := amneziawgV6Inbound(1, "awg-1", "eth0", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"fd86:ea04:1115::2/128"}},
|
||||
{Email: "b@x", Enable: true, PublicKey: "pub-b", AllowedIPs: []string{"fd86:ea04:1115::3/128"}},
|
||||
})
|
||||
// Pre-seed a colliding outbound tag for a@x specifically.
|
||||
collidingTag := amneziawgV6EgressTag(1, "a@x")
|
||||
existing, _ := json.Marshal([]any{map[string]any{"tag": collidingTag, "protocol": "freedom"}})
|
||||
cfg.OutboundConfigs = json_util.RawMessage(existing)
|
||||
|
||||
injectAmneziawgSocksThenV6(cfg, []*model.Inbound{inbound})
|
||||
|
||||
var outbounds []v6EgressOutbound
|
||||
if err := json.Unmarshal(cfg.OutboundConfigs, &outbounds); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tagB := amneziawgV6EgressTag(1, "b@x")
|
||||
foundB := false
|
||||
countA := 0
|
||||
for _, o := range outbounds {
|
||||
if o.Tag == collidingTag {
|
||||
countA++
|
||||
}
|
||||
if o.Tag == tagB {
|
||||
foundB = true
|
||||
}
|
||||
}
|
||||
if countA != 1 {
|
||||
t.Fatalf("a@x's pre-existing outbound must not be duplicated, got %d copies", countA)
|
||||
}
|
||||
if !foundB {
|
||||
t.Fatal("b@x must still get its own outbound despite a@x's tag collision")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgV6Egress_BadOutboundsOrRoutingSkips(t *testing.T) {
|
||||
inbound := amneziawgV6Inbound(1, "awg-1", "eth0", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"fd86:ea04:1115::2/128"}},
|
||||
})
|
||||
|
||||
cfg := egressTestConfig()
|
||||
cfg.OutboundConfigs = json_util.RawMessage(`{not json`)
|
||||
injectAmneziawgSocksThenV6(cfg, []*model.Inbound{inbound})
|
||||
if string(cfg.OutboundConfigs) != `{not json` {
|
||||
t.Fatalf("unparsable outbounds must be left untouched, got %s", cfg.OutboundConfigs)
|
||||
}
|
||||
|
||||
cfg2 := egressTestConfig()
|
||||
cfg2.RouterConfig = json_util.RawMessage(`{not json`)
|
||||
injectAmneziawgSocksThenV6(cfg2, []*model.Inbound{inbound})
|
||||
if string(cfg2.RouterConfig) != `{not json` {
|
||||
t.Fatalf("unparsable routing must be left untouched, got %s", cfg2.RouterConfig)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgV6Egress_NoQualifyingPeerLeavesConfigUntouched(t *testing.T) {
|
||||
cfg := egressTestConfig()
|
||||
beforeOut, beforeRoute := string(cfg.OutboundConfigs), string(cfg.RouterConfig)
|
||||
inbound := amneziawgV6Inbound(1, "awg-1", "eth0", nil) // no clients at all
|
||||
injectAmneziawgV6Egress(cfg, []*model.Inbound{inbound})
|
||||
if string(cfg.OutboundConfigs) != beforeOut || string(cfg.RouterConfig) != beforeRoute {
|
||||
t.Fatalf("an inbound with no qualifying peer must leave the config byte-identical")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectAmneziawgV6Egress_RulesPrependedBeforeExistingRules(t *testing.T) {
|
||||
cfg := egressTestConfig() // already has one rule, targeting "api"
|
||||
inbound := amneziawgV6Inbound(1, "awg-1", "eth0", []model.Client{
|
||||
{Email: "a@x", Enable: true, PublicKey: "pub-a", AllowedIPs: []string{"fd86:ea04:1115::2/128"}},
|
||||
})
|
||||
injectAmneziawgSocksThenV6(cfg, []*model.Inbound{inbound})
|
||||
|
||||
var routing v6EgressRouting
|
||||
if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(routing.Rules) != 2 {
|
||||
t.Fatalf("expected the new rule plus the pre-existing one, got %+v", routing.Rules)
|
||||
}
|
||||
if routing.Rules[0].OutboundTag != amneziawgV6EgressTag(1, "a@x") {
|
||||
t.Fatalf("the new infra rule must be prepended ahead of the pre-existing rule, got %+v", routing.Rules[0])
|
||||
}
|
||||
if routing.Rules[1].OutboundTag != "api" {
|
||||
t.Fatalf("the pre-existing rule must survive, got %+v", routing.Rules[1])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "السجلات",
|
||||
"accessLogs": "سجلات الوصول",
|
||||
"autoUpdate": "تحديث تلقائي",
|
||||
"amneziawgLogs": "سجلات AmneziaWG",
|
||||
"amneziawgHandshake": "آخر مصافحة",
|
||||
"amneziawgInterface": "الواجهة",
|
||||
"amneziawgInbound": "الوارد",
|
||||
"amneziawgEndpoint": "نقطة الاتصال",
|
||||
"amneziawgIdle": "خامل",
|
||||
"amneziawgEvents": "الأحداث",
|
||||
"amneziawgNoPeers": "لا يوجد أقران AmneziaWG نشطون حاليًا",
|
||||
"amneziawgNoEvents": "لم تُسجَّل أحداث AmneziaWG بعد",
|
||||
"config": "الإعدادات",
|
||||
"backupTitle": "نسخ احتياطي واستعادة",
|
||||
"exportDatabase": "اخزن نسخة",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "مفتاح وايرغارد المشترك مسبقًا",
|
||||
"wireguardAllowedIPs": "عناوين IP المسموحة لوايرغارد",
|
||||
"wireguardAllowedIPsHint": "اتركه فارغًا للتعيين التلقائي؛ افصل بين الإدخالات بفواصل",
|
||||
"amneziaWgPrivateKey": "مفتاح AmneziaWG الخاص",
|
||||
"amneziaWgPublicKey": "مفتاح AmneziaWG العام",
|
||||
"amneziaWgPreSharedKey": "مفتاح AmneziaWG المشترك مسبقًا",
|
||||
"amneziaWgAllowedIPs": "عناوين IP المسموحة لـ AmneziaWG",
|
||||
"amneziaWgAllowedIPsHint": "اتركه فارغًا للتعيين التلقائي؛ افصل بين الإدخالات بفواصل",
|
||||
"amneziaWgForwardedPorts": "المنافذ المُعاد توجيهها",
|
||||
"amneziaWgForwardedPortsHint": "المنافذ/النطاقات المُعاد توجيهها (DNAT) لهذا العميل، مثل 80, 443, 8000-8100. اتركها فارغة إن لم تكن مطلوبة.",
|
||||
"amneziaWgConfig": "إعدادات AmneziaWG",
|
||||
"mtprotoSecret": "سر MTProto",
|
||||
"mtprotoSecretHint": "سر FakeTLS الخاص بالعميل. أعد التوليد لتغييره.",
|
||||
"mtprotoAdTag": "علامة إعلانية (قناة مموّلة)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "المفتاح السري",
|
||||
"publicKey": "المفتاح العام",
|
||||
"subnetIp": "الشبكة الفرعية",
|
||||
"subnetCidr": "بادئة الشبكة الفرعية (CIDR)",
|
||||
"allowedIPs": "عناوين IP المسموح بها",
|
||||
"endpoint": "النهاية",
|
||||
"domainStrategy": "استراتيجية الدومين"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "المفتاح الخاص",
|
||||
"publicKey": "المفتاح العام",
|
||||
"subnetIp": "الشبكة الفرعية",
|
||||
"subnetCidr": "بادئة الشبكة الفرعية (CIDR)",
|
||||
"mtu": "الحد الأقصى لوحدة النقل (MTU)",
|
||||
"primaryDns": "DNS الأساسي",
|
||||
"secondaryDns": "DNS الثانوي",
|
||||
"externalInterface": "الواجهة الخارجية",
|
||||
"externalInterfaceHint": "واجهة الشبكة على الخادم المستخدمة لـ NAT (PostUp/PostDown). اتركها فارغة للاكتشاف التلقائي.",
|
||||
"ipv6Enabled": "تفعيل IPv6",
|
||||
"ipv6Subnet": "الشبكة الفرعية IPv6",
|
||||
"ipv6SubnetHint": "مثل fd86:ea04:1115::/64. مطلوب عند تفعيل IPv6.",
|
||||
"ipv6ExternalInterface": "الواجهة الخارجية لـ IPv6",
|
||||
"ipv6ExternalInterfaceHint": "واجهة الشبكة على الخادم لإدخالات وكيل NDP. اتركها فارغة لاستخدام الواجهة الخارجية.",
|
||||
"obfuscation": "معاملات التمويه",
|
||||
"regenerateObfuscation": "إعادة التوليد",
|
||||
"jc": "Jc (عدد الحزم العشوائية)",
|
||||
"jmin": "Jmin (الحد الأدنى لحجم الحزمة العشوائية)",
|
||||
"jmax": "Jmax (الحد الأقصى لحجم الحزمة العشوائية)",
|
||||
"s1": "S1 (حجم حشو حزمة init)",
|
||||
"s2": "S2 (حجم حشو حزمة response)",
|
||||
"s3": "S3 (حشو رد الكوكي)",
|
||||
"s4": "S4 (حشو حزمة النقل)",
|
||||
"h1": "H1 (رأس سحري)",
|
||||
"h2": "H2 (رأس سحري)",
|
||||
"h3": "H3 (رأس سحري)",
|
||||
"h4": "H4 (رأس سحري)",
|
||||
"hHint": "رقم واحد أو نطاق. اتركه فارغًا للقيم الافتراضية الكلاسيكية 1/2/3/4.",
|
||||
"i1": "I1 (حزمة التوقيع)",
|
||||
"i1Hint": "حزمة توقيع اختيارية. اتركه فارغًا لعدم إرسالها.",
|
||||
"i2": "I2 (حزمة التوقيع)",
|
||||
"i3": "I3 (حزمة التوقيع)",
|
||||
"i4": "I4 (حزمة التوقيع)",
|
||||
"i5": "I5 (حزمة التوقيع)",
|
||||
"headerProtectionKey": "HeaderProtectionKey (حماية الترويسات)",
|
||||
"headerProtectionKeyHint": "مفتاح Base64 بطول 32 بايت؛ يجب أن يتطابق في إعدادات كل عميل. اتركه فارغًا لتعطيل حماية الترويسات.",
|
||||
"contentPaddingAddition": "ContentPaddingAddition (حشو المحتوى)",
|
||||
"contentPaddingAdditionHint": "عدد صحيح أو نطاق بايتات يُضاف إلى حزم المحتوى. اتركه فارغًا للتعطيل.",
|
||||
"rekeyAfterTime": "RekeyAfterTime (ثوانٍ)",
|
||||
"rekeyTimeout": "RekeyTimeout (ثوانٍ)",
|
||||
"rejectAfterTime": "RejectAfterTime (ثوانٍ)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout (ثوانٍ)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "عدد صحيح أو نطاق. اتركه فارغًا لاستخدام قيمة WireGuard الافتراضية.",
|
||||
"maxHandshakeAttemptsHint": "عدد محاولات المصافحة قبل التوقف. اتركه فارغًا للقيمة الافتراضية.",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "يضيف بايتات عشوائية إلى نهاية كل حزمة. يتطلب AmneziaWG 3.1+ على الطرفين.",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "عدم إرسال ردود الكوكي — يزيل بصمة DPI لكنه يضعف الحماية من الفيضانات."
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "مستوى المستخدم"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "Logs",
|
||||
"accessLogs": "Access Logs",
|
||||
"autoUpdate": "Auto Update",
|
||||
"amneziawgLogs": "AmneziaWG Logs",
|
||||
"amneziawgHandshake": "Last Handshake",
|
||||
"amneziawgInterface": "Interface",
|
||||
"amneziawgInbound": "Inbound",
|
||||
"amneziawgEndpoint": "Endpoint",
|
||||
"amneziawgIdle": "Idle",
|
||||
"amneziawgEvents": "Events",
|
||||
"amneziawgNoPeers": "No AmneziaWG peers are currently up",
|
||||
"amneziawgNoEvents": "No AmneziaWG events recorded yet",
|
||||
"config": "Config",
|
||||
"backupTitle": "Backup & Restore",
|
||||
"exportDatabase": "Back Up",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "WireGuard Pre-Shared Key",
|
||||
"wireguardAllowedIPs": "WireGuard Allowed IPs",
|
||||
"wireguardAllowedIPsHint": "Leave empty to auto-assign; separate entries with commas",
|
||||
"amneziaWgPrivateKey": "AmneziaWG Private Key",
|
||||
"amneziaWgPublicKey": "AmneziaWG Public Key",
|
||||
"amneziaWgPreSharedKey": "AmneziaWG Pre-Shared Key",
|
||||
"amneziaWgAllowedIPs": "AmneziaWG Allowed IPs",
|
||||
"amneziaWgAllowedIPsHint": "Leave empty to auto-assign; separate entries with commas",
|
||||
"amneziaWgForwardedPorts": "Forwarded Ports",
|
||||
"amneziaWgForwardedPortsHint": "Ports/ranges DNAT'd to this client, e.g. 80, 443, 8000-8100. Leave empty for none.",
|
||||
"amneziaWgConfig": "AmneziaWG config",
|
||||
"mtprotoSecret": "MTProto secret",
|
||||
"mtprotoSecretHint": "The client's FakeTLS secret. Regenerate to rotate it.",
|
||||
"mtprotoAdTag": "Ad-tag (sponsored channel)",
|
||||
@@ -1887,10 +1904,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "Secret Key",
|
||||
"publicKey": "Public Key",
|
||||
"subnetIp": "Subnet",
|
||||
"subnetCidr": "Subnet CIDR",
|
||||
"allowedIPs": "Allowed IPs",
|
||||
"endpoint": "Endpoint",
|
||||
"domainStrategy": "Domain Strategy"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "Private Key",
|
||||
"publicKey": "Public Key",
|
||||
"subnetIp": "Subnet",
|
||||
"subnetCidr": "Subnet CIDR",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "Primary DNS",
|
||||
"secondaryDns": "Secondary DNS",
|
||||
"externalInterface": "External Interface",
|
||||
"externalInterfaceHint": "Host NIC for NAT (PostUp/PostDown). Leave empty to auto-detect.",
|
||||
"ipv6Enabled": "Enable IPv6",
|
||||
"ipv6Subnet": "IPv6 Subnet",
|
||||
"ipv6SubnetHint": "e.g. fd86:ea04:1115::/64. Required when IPv6 is enabled.",
|
||||
"ipv6ExternalInterface": "IPv6 External Interface",
|
||||
"ipv6ExternalInterfaceHint": "Host NIC each peer's IPv6 address is aliased onto. Leave empty to reuse External Interface.",
|
||||
"obfuscation": "Obfuscation parameters",
|
||||
"regenerateObfuscation": "Regenerate",
|
||||
"jc": "Jc (junk packet count)",
|
||||
"jmin": "Jmin (junk packet min size)",
|
||||
"jmax": "Jmax (junk packet max size)",
|
||||
"s1": "S1 (init packet junk size)",
|
||||
"s2": "S2 (response packet junk size)",
|
||||
"s3": "S3 (cookie reply padding)",
|
||||
"s4": "S4 (transport packet padding)",
|
||||
"h1": "H1 (magic header)",
|
||||
"h2": "H2 (magic header)",
|
||||
"h3": "H3 (magic header)",
|
||||
"h4": "H4 (magic header)",
|
||||
"hHint": "A single integer or a low-high range. Leave empty for the classic 1/2/3/4 default.",
|
||||
"i1": "I1 (signature packet)",
|
||||
"i1Hint": "Optional signature packet. Leave empty to omit it.",
|
||||
"i2": "I2 (signature packet)",
|
||||
"i3": "I3 (signature packet)",
|
||||
"i4": "I4 (signature packet)",
|
||||
"i5": "I5 (signature packet)",
|
||||
"headerProtectionKey": "HeaderProtectionKey (header protection)",
|
||||
"headerProtectionKeyHint": "Base64 32-byte key; must match on every client config. Leave empty to disable header protection.",
|
||||
"contentPaddingAddition": "ContentPaddingAddition (content padding)",
|
||||
"contentPaddingAdditionHint": "A single integer or low-high byte range added to content packets. Leave empty to disable.",
|
||||
"rekeyAfterTime": "RekeyAfterTime (seconds)",
|
||||
"rekeyTimeout": "RekeyTimeout (seconds)",
|
||||
"rejectAfterTime": "RejectAfterTime (seconds)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout (seconds)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "A single integer or a low-high range. Leave empty to keep the WireGuard default.",
|
||||
"maxHandshakeAttemptsHint": "Handshake retries before giving up. Leave empty for the default.",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "Appends random bytes to every packet. Both ends need AmneziaWG 3.1+.",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "Never send cookie replies — removes a DPI fingerprint; weakens flood mitigation."
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "User Level"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "Registros",
|
||||
"accessLogs": "Registros de acceso",
|
||||
"autoUpdate": "Actualización automática",
|
||||
"amneziawgLogs": "Registros de AmneziaWG",
|
||||
"amneziawgHandshake": "Último handshake",
|
||||
"amneziawgInterface": "Interfaz",
|
||||
"amneziawgInbound": "Entrada",
|
||||
"amneziawgEndpoint": "Endpoint",
|
||||
"amneziawgIdle": "Inactivo",
|
||||
"amneziawgEvents": "Eventos",
|
||||
"amneziawgNoPeers": "No hay peers de AmneziaWG activos",
|
||||
"amneziawgNoEvents": "Aún no hay eventos de AmneziaWG registrados",
|
||||
"config": "Configuración",
|
||||
"backupTitle": "Copia & Restauración",
|
||||
"exportDatabase": "Copia de seguridad",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "Clave precompartida de WireGuard",
|
||||
"wireguardAllowedIPs": "IP permitidas de WireGuard",
|
||||
"wireguardAllowedIPsHint": "Déjalo vacío para asignar automáticamente; separa las entradas con comas",
|
||||
"amneziaWgPrivateKey": "Clave privada de AmneziaWG",
|
||||
"amneziaWgPublicKey": "Clave pública de AmneziaWG",
|
||||
"amneziaWgPreSharedKey": "Clave precompartida de AmneziaWG",
|
||||
"amneziaWgAllowedIPs": "IP permitidas de AmneziaWG",
|
||||
"amneziaWgAllowedIPsHint": "Déjalo vacío para asignar automáticamente; separa las entradas con comas",
|
||||
"amneziaWgForwardedPorts": "Puertos reenviados",
|
||||
"amneziaWgForwardedPortsHint": "Puertos/rangos redirigidos (DNAT) a este cliente, p. ej. 80, 443, 8000-8100. Déjalo vacío si no aplica.",
|
||||
"amneziaWgConfig": "Configuración de AmneziaWG",
|
||||
"mtprotoSecret": "Secreto MTProto",
|
||||
"mtprotoSecretHint": "El secreto FakeTLS del cliente. Vuelve a generarlo para cambiarlo.",
|
||||
"mtprotoAdTag": "Ad-tag (canal patrocinado)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "Llave secreta",
|
||||
"publicKey": "Llave pública",
|
||||
"subnetIp": "Subred",
|
||||
"subnetCidr": "CIDR de la subred",
|
||||
"allowedIPs": "IP permitidas",
|
||||
"endpoint": "Punto final",
|
||||
"domainStrategy": "Estrategia de dominio"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "Clave privada",
|
||||
"publicKey": "Clave pública",
|
||||
"subnetIp": "Subred",
|
||||
"subnetCidr": "CIDR de la subred",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "DNS primario",
|
||||
"secondaryDns": "DNS secundario",
|
||||
"externalInterface": "Interfaz externa",
|
||||
"externalInterfaceHint": "Interfaz de red del host para NAT (PostUp/PostDown). Déjalo vacío para autodetectar.",
|
||||
"ipv6Enabled": "Habilitar IPv6",
|
||||
"ipv6Subnet": "Subred IPv6",
|
||||
"ipv6SubnetHint": "p. ej. fd86:ea04:1115::/64. Obligatorio cuando IPv6 está habilitado.",
|
||||
"ipv6ExternalInterface": "Interfaz externa IPv6",
|
||||
"ipv6ExternalInterfaceHint": "Interfaz de red del host para las entradas de proxy NDP. Déjalo vacío para reutilizar la interfaz externa.",
|
||||
"obfuscation": "Parámetros de ofuscación",
|
||||
"regenerateObfuscation": "Regenerar",
|
||||
"jc": "Jc (cantidad de paquetes basura)",
|
||||
"jmin": "Jmin (tamaño mínimo de paquete basura)",
|
||||
"jmax": "Jmax (tamaño máximo de paquete basura)",
|
||||
"s1": "S1 (relleno del paquete init)",
|
||||
"s2": "S2 (relleno del paquete response)",
|
||||
"s3": "S3 (relleno de cookie reply)",
|
||||
"s4": "S4 (relleno del paquete de transporte)",
|
||||
"h1": "H1 (cabecera mágica)",
|
||||
"h2": "H2 (cabecera mágica)",
|
||||
"h3": "H3 (cabecera mágica)",
|
||||
"h4": "H4 (cabecera mágica)",
|
||||
"hHint": "Un número entero o un rango. Déjalo vacío para los valores clásicos 1/2/3/4.",
|
||||
"i1": "I1 (paquete de firma)",
|
||||
"i1Hint": "Paquete de firma opcional. Déjalo vacío para omitirlo.",
|
||||
"i2": "I2 (paquete de firma)",
|
||||
"i3": "I3 (paquete de firma)",
|
||||
"i4": "I4 (paquete de firma)",
|
||||
"i5": "I5 (paquete de firma)",
|
||||
"headerProtectionKey": "HeaderProtectionKey (protección de cabeceras)",
|
||||
"headerProtectionKeyHint": "Clave Base64 de 32 bytes; debe coincidir en la configuración de cada cliente. Déjalo vacío para desactivar la protección de cabeceras.",
|
||||
"contentPaddingAddition": "ContentPaddingAddition (relleno de contenido)",
|
||||
"contentPaddingAdditionHint": "Un entero o un rango de bytes añadido a los paquetes de contenido. Déjalo vacío para desactivarlo.",
|
||||
"rekeyAfterTime": "RekeyAfterTime (segundos)",
|
||||
"rekeyTimeout": "RekeyTimeout (segundos)",
|
||||
"rejectAfterTime": "RejectAfterTime (segundos)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout (segundos)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "Un entero o un rango. Déjalo vacío para mantener el valor por defecto de WireGuard.",
|
||||
"maxHandshakeAttemptsHint": "Reintentos de handshake antes de abandonar. Déjalo vacío para el valor por defecto.",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "Añade bytes aleatorios a cada paquete. Ambos extremos necesitan AmneziaWG 3.1+.",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "No enviar cookie replies — elimina una huella para DPI, pero debilita la mitigación de inundaciones."
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "Nivel de Usuario"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "لاگها",
|
||||
"accessLogs": "لاگهای دسترسی",
|
||||
"autoUpdate": "بهروزرسانی خودکار",
|
||||
"amneziawgLogs": "لاگهای AmneziaWG",
|
||||
"amneziawgHandshake": "آخرین دستدهی",
|
||||
"amneziawgInterface": "رابط شبکه",
|
||||
"amneziawgInbound": "ورودی",
|
||||
"amneziawgEndpoint": "نقطه اتصال",
|
||||
"amneziawgIdle": "بیکار",
|
||||
"amneziawgEvents": "رویدادها",
|
||||
"amneziawgNoPeers": "هیچ پیر فعالی برای AmneziaWG وجود ندارد",
|
||||
"amneziawgNoEvents": "هنوز رویدادی برای AmneziaWG ثبت نشده است",
|
||||
"config": "پیکربندی",
|
||||
"backupTitle": "پشتیبانگیری و بازیابی",
|
||||
"exportDatabase": "پشتیبانگیری",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "کلید پیشاشتراکی وایرگارد",
|
||||
"wireguardAllowedIPs": "آیپیهای مجاز وایرگارد",
|
||||
"wireguardAllowedIPsHint": "برای تخصیص خودکار خالی بگذارید؛ ورودیها را با کاما جدا کنید",
|
||||
"amneziaWgPrivateKey": "کلید خصوصی AmneziaWG",
|
||||
"amneziaWgPublicKey": "کلید عمومی AmneziaWG",
|
||||
"amneziaWgPreSharedKey": "کلید پیشاشتراکی AmneziaWG",
|
||||
"amneziaWgAllowedIPs": "آیپیهای مجاز AmneziaWG",
|
||||
"amneziaWgAllowedIPsHint": "برای تخصیص خودکار خالی بگذارید؛ ورودیها را با کاما جدا کنید",
|
||||
"amneziaWgForwardedPorts": "پورتهای هدایتشده",
|
||||
"amneziaWgForwardedPortsHint": "پورتها/محدودههای DNAT شده به این کلاینت، مثلاً 80, 443, 8000-8100. برای غیرفعال بودن خالی بگذارید.",
|
||||
"amneziaWgConfig": "پیکربندی AmneziaWG",
|
||||
"mtprotoSecret": "سکرت MTProto",
|
||||
"mtprotoSecretHint": "سکرت FakeTLS این کلاینت. برای تعویض، دوباره تولید کنید.",
|
||||
"mtprotoAdTag": "برچسب تبلیغاتی (کانال حامی)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "کلید شخصی",
|
||||
"publicKey": "کلید عمومی",
|
||||
"subnetIp": "زیرشبکه",
|
||||
"subnetCidr": "پیشوند زیرشبکه (CIDR)",
|
||||
"allowedIPs": "آیپیهای مجاز",
|
||||
"endpoint": "نقطه پایانی",
|
||||
"domainStrategy": "استراتژی حل دامنه"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "کلید خصوصی",
|
||||
"publicKey": "کلید عمومی",
|
||||
"subnetIp": "زیرشبکه",
|
||||
"subnetCidr": "پیشوند زیرشبکه (CIDR)",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "DNS اصلی",
|
||||
"secondaryDns": "DNS ثانویه",
|
||||
"externalInterface": "رابط خارجی",
|
||||
"externalInterfaceHint": "رابط شبکه میزبان برای NAT (PostUp/PostDown). برای تشخیص خودکار خالی بگذارید.",
|
||||
"ipv6Enabled": "فعالسازی IPv6",
|
||||
"ipv6Subnet": "زیرشبکه IPv6",
|
||||
"ipv6SubnetHint": "مثلاً fd86:ea04:1115::/64. هنگام فعال بودن IPv6 الزامی است.",
|
||||
"ipv6ExternalInterface": "رابط خارجی IPv6",
|
||||
"ipv6ExternalInterfaceHint": "رابط شبکه میزبان برای ورودیهای پراکسی NDP. برای استفاده از رابط خارجی خالی بگذارید.",
|
||||
"obfuscation": "پارامترهای مبهمسازی",
|
||||
"regenerateObfuscation": "بازتولید",
|
||||
"jc": "Jc (تعداد بستههای زباله)",
|
||||
"jmin": "Jmin (حداقل اندازه بسته زباله)",
|
||||
"jmax": "Jmax (حداکثر اندازه بسته زباله)",
|
||||
"s1": "S1 (اندازه پرکننده بسته init)",
|
||||
"s2": "S2 (اندازه پرکننده بسته response)",
|
||||
"s3": "S3 (پرکننده cookie reply)",
|
||||
"s4": "S4 (پرکننده بسته انتقال)",
|
||||
"h1": "H1 (سرصفحه جادویی)",
|
||||
"h2": "H2 (سرصفحه جادویی)",
|
||||
"h3": "H3 (سرصفحه جادویی)",
|
||||
"h4": "H4 (سرصفحه جادویی)",
|
||||
"hHint": "یک عدد صحیح یا یک بازه. برای مقادیر پیشفرض کلاسیک ۱/۲/۳/۴ خالی بگذارید.",
|
||||
"i1": "I1 (بسته امضا)",
|
||||
"i1Hint": "بسته امضای اختیاری. برای حذف آن خالی بگذارید.",
|
||||
"i2": "I2 (بسته امضا)",
|
||||
"i3": "I3 (بسته امضا)",
|
||||
"i4": "I4 (بسته امضا)",
|
||||
"i5": "I5 (بسته امضا)",
|
||||
"headerProtectionKey": "HeaderProtectionKey (محافظت سرآیند)",
|
||||
"headerProtectionKeyHint": "کلید Base64 با طول ۳۲ بایت؛ باید در پیکربندی همه کلاینتها یکسان باشد. برای غیرفعال کردن محافظت سرآیند خالی بگذارید.",
|
||||
"contentPaddingAddition": "ContentPaddingAddition (پرکننده محتوا)",
|
||||
"contentPaddingAdditionHint": "یک عدد صحیح یا بازه بایت که به بستههای محتوا افزوده میشود. برای غیرفعال کردن خالی بگذارید.",
|
||||
"rekeyAfterTime": "RekeyAfterTime (ثانیه)",
|
||||
"rekeyTimeout": "RekeyTimeout (ثانیه)",
|
||||
"rejectAfterTime": "RejectAfterTime (ثانیه)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout (ثانیه)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "یک عدد صحیح یا یک بازه. برای استفاده از مقدار پیشفرض WireGuard خالی بگذارید.",
|
||||
"maxHandshakeAttemptsHint": "تعداد تلاشهای دوباره دستدهی پیش از انصراف. برای مقدار پیشفرض خالی بگذارید.",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "به انتهای هر بسته بایتهای تصادفی میافزاید. هر دو طرف باید AmneziaWG 3.1+ باشند.",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "هرگز پاسخ کوکی ارسال نشود — اثر انگشت DPI را حذف میکند اما دفاع در برابر سیلآسا را ضعیف میکند."
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "سطح کاربر"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "Log",
|
||||
"accessLogs": "Log Akses",
|
||||
"autoUpdate": "Pembaruan Otomatis",
|
||||
"amneziawgLogs": "Log AmneziaWG",
|
||||
"amneziawgHandshake": "Handshake Terakhir",
|
||||
"amneziawgInterface": "Antarmuka",
|
||||
"amneziawgInbound": "Inbound",
|
||||
"amneziawgEndpoint": "Endpoint",
|
||||
"amneziawgIdle": "Idle",
|
||||
"amneziawgEvents": "Peristiwa",
|
||||
"amneziawgNoPeers": "Tidak ada peer AmneziaWG yang aktif",
|
||||
"amneziawgNoEvents": "Belum ada peristiwa AmneziaWG yang tercatat",
|
||||
"config": "Konfigurasi",
|
||||
"backupTitle": "Cadangan & Pulihkan",
|
||||
"exportDatabase": "Cadangkan",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "Kunci Pra-Berbagi WireGuard",
|
||||
"wireguardAllowedIPs": "IP yang Diizinkan WireGuard",
|
||||
"wireguardAllowedIPsHint": "Biarkan kosong untuk penetapan otomatis; pisahkan entri dengan koma",
|
||||
"amneziaWgPrivateKey": "Kunci Privat AmneziaWG",
|
||||
"amneziaWgPublicKey": "Kunci Publik AmneziaWG",
|
||||
"amneziaWgPreSharedKey": "Kunci Pra-Berbagi AmneziaWG",
|
||||
"amneziaWgAllowedIPs": "IP yang Diizinkan AmneziaWG",
|
||||
"amneziaWgAllowedIPsHint": "Biarkan kosong untuk penetapan otomatis; pisahkan entri dengan koma",
|
||||
"amneziaWgForwardedPorts": "Port yang Diteruskan",
|
||||
"amneziaWgForwardedPortsHint": "Port/rentang yang di-DNAT ke klien ini, mis. 80, 443, 8000-8100. Biarkan kosong jika tidak ada.",
|
||||
"amneziaWgConfig": "Konfigurasi AmneziaWG",
|
||||
"mtprotoSecret": "Secret MTProto",
|
||||
"mtprotoSecretHint": "Secret FakeTLS klien. Buat ulang untuk menggantinya.",
|
||||
"mtprotoAdTag": "Ad-tag (kanal bersponsor)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "Kunci Rahasia",
|
||||
"publicKey": "Kunci Publik",
|
||||
"subnetIp": "Subnet",
|
||||
"subnetCidr": "CIDR Subnet",
|
||||
"allowedIPs": "IP yang Diizinkan",
|
||||
"endpoint": "Titik Akhir",
|
||||
"domainStrategy": "Strategi Domain"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "Kunci Privat",
|
||||
"publicKey": "Kunci Publik",
|
||||
"subnetIp": "Subnet",
|
||||
"subnetCidr": "CIDR Subnet",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "DNS Utama",
|
||||
"secondaryDns": "DNS Cadangan",
|
||||
"externalInterface": "Antarmuka Eksternal",
|
||||
"externalInterfaceHint": "NIC host untuk NAT (PostUp/PostDown). Biarkan kosong untuk deteksi otomatis.",
|
||||
"ipv6Enabled": "Aktifkan IPv6",
|
||||
"ipv6Subnet": "Subnet IPv6",
|
||||
"ipv6SubnetHint": "mis. fd86:ea04:1115::/64. Wajib diisi saat IPv6 diaktifkan.",
|
||||
"ipv6ExternalInterface": "NIC Eksternal IPv6",
|
||||
"ipv6ExternalInterfaceHint": "NIC host untuk entri proxy NDP. Biarkan kosong untuk menggunakan NIC Eksternal.",
|
||||
"obfuscation": "Parameter obfuskasi",
|
||||
"regenerateObfuscation": "Buat ulang",
|
||||
"jc": "Jc (jumlah paket sampah)",
|
||||
"jmin": "Jmin (ukuran min paket sampah)",
|
||||
"jmax": "Jmax (ukuran maks paket sampah)",
|
||||
"s1": "S1 (padding paket init)",
|
||||
"s2": "S2 (padding paket response)",
|
||||
"s3": "S3 (padding cookie reply)",
|
||||
"s4": "S4 (padding paket transport)",
|
||||
"h1": "H1 (header ajaib)",
|
||||
"h2": "H2 (header ajaib)",
|
||||
"h3": "H3 (header ajaib)",
|
||||
"h4": "H4 (header ajaib)",
|
||||
"hHint": "Satu bilangan bulat atau rentang. Biarkan kosong untuk nilai klasik 1/2/3/4.",
|
||||
"i1": "I1 (paket tanda tangan)",
|
||||
"i1Hint": "Paket tanda tangan opsional. Biarkan kosong untuk melewatkannya.",
|
||||
"i2": "I2 (paket tanda tangan)",
|
||||
"i3": "I3 (paket tanda tangan)",
|
||||
"i4": "I4 (paket tanda tangan)",
|
||||
"i5": "I5 (paket tanda tangan)",
|
||||
"headerProtectionKey": "HeaderProtectionKey (perlindungan header)",
|
||||
"headerProtectionKeyHint": "Kunci Base64 32 byte; harus sama di konfigurasi setiap klien. Biarkan kosong untuk menonaktifkan perlindungan header.",
|
||||
"contentPaddingAddition": "ContentPaddingAddition (padding konten)",
|
||||
"contentPaddingAdditionHint": "Satu bilangan bulat atau rentang byte yang ditambahkan ke paket konten. Biarkan kosong untuk menonaktifkan.",
|
||||
"rekeyAfterTime": "RekeyAfterTime (detik)",
|
||||
"rekeyTimeout": "RekeyTimeout (detik)",
|
||||
"rejectAfterTime": "RejectAfterTime (detik)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout (detik)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "Satu bilangan bulat atau rentang. Biarkan kosong untuk memakai bawaan WireGuard.",
|
||||
"maxHandshakeAttemptsHint": "Jumlah percobaan ulang handshake sebelum menyerah. Biarkan kosong untuk nilai bawaan.",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "Menambahkan byte acak ke setiap paket. Kedua sisi butuh AmneziaWG 3.1+.",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "Tidak pernah mengirim cookie reply — menghapus sidik jari DPI, tetapi melemahkan mitigasi banjir."
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "Level Pengguna"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "ログ",
|
||||
"accessLogs": "アクセスログ",
|
||||
"autoUpdate": "自動更新",
|
||||
"amneziawgLogs": "AmneziaWG ログ",
|
||||
"amneziawgHandshake": "最終ハンドシェイク",
|
||||
"amneziawgInterface": "インターフェース",
|
||||
"amneziawgInbound": "インバウンド",
|
||||
"amneziawgEndpoint": "エンドポイント",
|
||||
"amneziawgIdle": "アイドル",
|
||||
"amneziawgEvents": "イベント",
|
||||
"amneziawgNoPeers": "稼働中の AmneziaWG ピアはありません",
|
||||
"amneziawgNoEvents": "AmneziaWG のイベントはまだ記録されていません",
|
||||
"config": "設定",
|
||||
"backupTitle": "バックアップと復元",
|
||||
"exportDatabase": "バックアップ",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "WireGuard 事前共有鍵",
|
||||
"wireguardAllowedIPs": "WireGuard 許可IP",
|
||||
"wireguardAllowedIPsHint": "空欄で自動割り当て。複数指定はカンマ区切り",
|
||||
"amneziaWgPrivateKey": "AmneziaWG 秘密鍵",
|
||||
"amneziaWgPublicKey": "AmneziaWG 公開鍵",
|
||||
"amneziaWgPreSharedKey": "AmneziaWG 事前共有鍵",
|
||||
"amneziaWgAllowedIPs": "AmneziaWG 許可IP",
|
||||
"amneziaWgAllowedIPsHint": "空欄で自動割り当て。複数指定はカンマ区切り",
|
||||
"amneziaWgForwardedPorts": "転送ポート",
|
||||
"amneziaWgForwardedPortsHint": "このクライアントに転送するポート/範囲。例: 80, 443, 8000-8100。空欄で転送なし。",
|
||||
"amneziaWgConfig": "AmneziaWG 設定",
|
||||
"mtprotoSecret": "MTProto シークレット",
|
||||
"mtprotoSecretHint": "このクライアントの FakeTLS シークレット。変更するには再生成します。",
|
||||
"mtprotoAdTag": "広告タグ(スポンサーチャンネル)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "シークレットキー",
|
||||
"publicKey": "公開鍵",
|
||||
"subnetIp": "サブネット",
|
||||
"subnetCidr": "サブネットCIDR",
|
||||
"allowedIPs": "許可されたIP",
|
||||
"endpoint": "エンドポイント",
|
||||
"domainStrategy": "ドメイン戦略"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "秘密鍵",
|
||||
"publicKey": "公開鍵",
|
||||
"subnetIp": "サブネット",
|
||||
"subnetCidr": "サブネットCIDR",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "プライマリDNS",
|
||||
"secondaryDns": "セカンダリDNS",
|
||||
"externalInterface": "外部インターフェース",
|
||||
"externalInterfaceHint": "NAT(PostUp/PostDown)に使用するホストのNIC。空欄で自動検出。",
|
||||
"ipv6Enabled": "IPv6を有効化",
|
||||
"ipv6Subnet": "IPv6サブネット",
|
||||
"ipv6SubnetHint": "例: fd86:ea04:1115::/64。IPv6有効時は必須。",
|
||||
"ipv6ExternalInterface": "IPv6外部NIC",
|
||||
"ipv6ExternalInterfaceHint": "NDPプロキシエントリに使用するホストのNIC。空欄で外部NICを使用。",
|
||||
"obfuscation": "難読化パラメータ",
|
||||
"regenerateObfuscation": "再生成",
|
||||
"jc": "Jc(ジャンクパケット数)",
|
||||
"jmin": "Jmin(ジャンクパケット最小サイズ)",
|
||||
"jmax": "Jmax(ジャンクパケット最大サイズ)",
|
||||
"s1": "S1(initパケットのパディングサイズ)",
|
||||
"s2": "S2(responseパケットのパディングサイズ)",
|
||||
"s3": "S3(cookie replyパディング)",
|
||||
"s4": "S4(トランスポートパケットパディング)",
|
||||
"h1": "H1(マジックヘッダー)",
|
||||
"h2": "H2(マジックヘッダー)",
|
||||
"h3": "H3(マジックヘッダー)",
|
||||
"h4": "H4(マジックヘッダー)",
|
||||
"hHint": "整数または範囲を指定。空欄の場合は従来の1/2/3/4がデフォルトになります。",
|
||||
"i1": "I1(署名パケット)",
|
||||
"i1Hint": "任意の署名パケット。空欄の場合は送信しません。",
|
||||
"i2": "I2(署名パケット)",
|
||||
"i3": "I3(署名パケット)",
|
||||
"i4": "I4(署名パケット)",
|
||||
"i5": "I5(署名パケット)",
|
||||
"headerProtectionKey": "HeaderProtectionKey(ヘッダー保護)",
|
||||
"headerProtectionKeyHint": "Base64の32バイト鍵。全クライアントの設定と一致する必要があります。空欄でヘッダー保護を無効にします。",
|
||||
"contentPaddingAddition": "ContentPaddingAddition(コンテンツパディング)",
|
||||
"contentPaddingAdditionHint": "整数またはlow-highのバイト範囲をコンテンツパケットに追加します。空欄で無効になります。",
|
||||
"rekeyAfterTime": "RekeyAfterTime(秒)",
|
||||
"rekeyTimeout": "RekeyTimeout(秒)",
|
||||
"rejectAfterTime": "RejectAfterTime(秒)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout(秒)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "整数または範囲を指定。空欄の場合はWireGuardのデフォルトを使用します。",
|
||||
"maxHandshakeAttemptsHint": "諦めるまでのハンドシェイク再試行回数。空欄でデフォルトになります。",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "各パケットにランダムなバイトを追加します。両端にAmneziaWG 3.1+が必要です。",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "cookie replyを送信しません。DPIの指紋を消しますが、フラッド緩和は弱まります。"
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "ユーザーレベル"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "Logs",
|
||||
"accessLogs": "Logs de acesso",
|
||||
"autoUpdate": "Atualização automática",
|
||||
"amneziawgLogs": "Logs do AmneziaWG",
|
||||
"amneziawgHandshake": "Último handshake",
|
||||
"amneziawgInterface": "Interface",
|
||||
"amneziawgInbound": "Entrada",
|
||||
"amneziawgEndpoint": "Endpoint",
|
||||
"amneziawgIdle": "Ocioso",
|
||||
"amneziawgEvents": "Eventos",
|
||||
"amneziawgNoPeers": "Nenhum peer do AmneziaWG está ativo",
|
||||
"amneziawgNoEvents": "Nenhum evento do AmneziaWG registrado ainda",
|
||||
"config": "Configuração",
|
||||
"backupTitle": "Backup & Restauração",
|
||||
"exportDatabase": "Backup",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "Chave pré-compartilhada do WireGuard",
|
||||
"wireguardAllowedIPs": "IPs permitidos do WireGuard",
|
||||
"wireguardAllowedIPsHint": "Deixe vazio para atribuir automaticamente; separe as entradas com vírgulas",
|
||||
"amneziaWgPrivateKey": "Chave privada do AmneziaWG",
|
||||
"amneziaWgPublicKey": "Chave pública do AmneziaWG",
|
||||
"amneziaWgPreSharedKey": "Chave pré-compartilhada do AmneziaWG",
|
||||
"amneziaWgAllowedIPs": "IPs permitidos do AmneziaWG",
|
||||
"amneziaWgAllowedIPsHint": "Deixe vazio para atribuir automaticamente; separe as entradas com vírgulas",
|
||||
"amneziaWgForwardedPorts": "Portas encaminhadas",
|
||||
"amneziaWgForwardedPortsHint": "Portas/intervalos redirecionados (DNAT) para este cliente, ex. 80, 443, 8000-8100. Deixe vazio se não aplicável.",
|
||||
"amneziaWgConfig": "Configuração do AmneziaWG",
|
||||
"mtprotoSecret": "Segredo MTProto",
|
||||
"mtprotoSecretHint": "O segredo FakeTLS do cliente. Gere novamente para trocá-lo.",
|
||||
"mtprotoAdTag": "Ad-tag (canal patrocinado)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "Chave Secreta",
|
||||
"publicKey": "Chave Pública",
|
||||
"subnetIp": "Sub-rede",
|
||||
"subnetCidr": "CIDR da Sub-rede",
|
||||
"allowedIPs": "IPs Permitidos",
|
||||
"endpoint": "Ponto Final",
|
||||
"domainStrategy": "Estratégia de Domínio"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "Chave Privada",
|
||||
"publicKey": "Chave Pública",
|
||||
"subnetIp": "Sub-rede",
|
||||
"subnetCidr": "CIDR da Sub-rede",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "DNS Primário",
|
||||
"secondaryDns": "DNS Secundário",
|
||||
"externalInterface": "Interface Externa",
|
||||
"externalInterfaceHint": "Interface de rede do host para NAT (PostUp/PostDown). Deixe vazio para detecção automática.",
|
||||
"ipv6Enabled": "Ativar IPv6",
|
||||
"ipv6Subnet": "Sub-rede IPv6",
|
||||
"ipv6SubnetHint": "ex. fd86:ea04:1115::/64. Obrigatório quando o IPv6 está ativado.",
|
||||
"ipv6ExternalInterface": "Interface externa IPv6",
|
||||
"ipv6ExternalInterfaceHint": "Interface de rede do host para as entradas de proxy NDP. Deixe vazio para reutilizar a interface externa.",
|
||||
"obfuscation": "Parâmetros de ofuscação",
|
||||
"regenerateObfuscation": "Regenerar",
|
||||
"jc": "Jc (quantidade de pacotes de lixo)",
|
||||
"jmin": "Jmin (tamanho mínimo do pacote de lixo)",
|
||||
"jmax": "Jmax (tamanho máximo do pacote de lixo)",
|
||||
"s1": "S1 (preenchimento do pacote init)",
|
||||
"s2": "S2 (preenchimento do pacote response)",
|
||||
"s3": "S3 (preenchimento de cookie reply)",
|
||||
"s4": "S4 (preenchimento do pacote de transporte)",
|
||||
"h1": "H1 (cabeçalho mágico)",
|
||||
"h2": "H2 (cabeçalho mágico)",
|
||||
"h3": "H3 (cabeçalho mágico)",
|
||||
"h4": "H4 (cabeçalho mágico)",
|
||||
"hHint": "Um número inteiro ou um intervalo. Deixe vazio para os valores clássicos 1/2/3/4.",
|
||||
"i1": "I1 (pacote de assinatura)",
|
||||
"i1Hint": "Pacote de assinatura opcional. Deixe vazio para omiti-lo.",
|
||||
"i2": "I2 (pacote de assinatura)",
|
||||
"i3": "I3 (pacote de assinatura)",
|
||||
"i4": "I4 (pacote de assinatura)",
|
||||
"i5": "I5 (pacote de assinatura)",
|
||||
"headerProtectionKey": "HeaderProtectionKey (proteção de cabeçalhos)",
|
||||
"headerProtectionKeyHint": "Chave Base64 de 32 bytes; deve coincidir na configuração de cada cliente. Deixe vazio para desativar a proteção de cabeçalhos.",
|
||||
"contentPaddingAddition": "ContentPaddingAddition (preenchimento de conteúdo)",
|
||||
"contentPaddingAdditionHint": "Um inteiro ou um intervalo de bytes adicionado aos pacotes de conteúdo. Deixe vazio para desativar.",
|
||||
"rekeyAfterTime": "RekeyAfterTime (segundos)",
|
||||
"rekeyTimeout": "RekeyTimeout (segundos)",
|
||||
"rejectAfterTime": "RejectAfterTime (segundos)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout (segundos)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "Um inteiro ou um intervalo. Deixe vazio para manter o padrão do WireGuard.",
|
||||
"maxHandshakeAttemptsHint": "Tentativas de handshake antes de desistir. Deixe vazio para o padrão.",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "Acrescenta bytes aleatórios a cada pacote. Ambos os lados precisam do AmneziaWG 3.1+.",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "Nunca enviar cookie replies — remove uma impressão digital de DPI, mas enfraquece a mitigação de inundações."
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "Nível do Usuário"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "Логи",
|
||||
"accessLogs": "Логи доступа",
|
||||
"autoUpdate": "Автообновление",
|
||||
"amneziawgLogs": "Логи AmneziaWG",
|
||||
"amneziawgHandshake": "Последнее рукопожатие",
|
||||
"amneziawgInterface": "Интерфейс",
|
||||
"amneziawgInbound": "Входящее",
|
||||
"amneziawgEndpoint": "Точка подключения",
|
||||
"amneziawgIdle": "Простой",
|
||||
"amneziawgEvents": "События",
|
||||
"amneziawgNoPeers": "Нет активных пиров AmneziaWG",
|
||||
"amneziawgNoEvents": "События AmneziaWG пока не зафиксированы",
|
||||
"config": "Конфигурация",
|
||||
"backupTitle": "Бэкап и восстановление",
|
||||
"exportDatabase": "Экспорт базы данных",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "Общий ключ WireGuard",
|
||||
"wireguardAllowedIPs": "Разрешённые IP WireGuard",
|
||||
"wireguardAllowedIPsHint": "Оставьте пустым для автоназначения; разделяйте записи запятыми",
|
||||
"amneziaWgPrivateKey": "Приватный ключ AmneziaWG",
|
||||
"amneziaWgPublicKey": "Публичный ключ AmneziaWG",
|
||||
"amneziaWgPreSharedKey": "Общий ключ AmneziaWG",
|
||||
"amneziaWgAllowedIPs": "Разрешённые IP AmneziaWG",
|
||||
"amneziaWgAllowedIPsHint": "Оставьте пустым для автоназначения; разделяйте записи запятыми",
|
||||
"amneziaWgForwardedPorts": "Проброс портов",
|
||||
"amneziaWgForwardedPortsHint": "Порты/диапазоны, DNAT'ящиеся на этого клиента, например 80, 443, 8000-8100. Оставьте пустым, если не нужно.",
|
||||
"amneziaWgConfig": "Конфиг AmneziaWG",
|
||||
"mtprotoSecret": "Секрет MTProto",
|
||||
"mtprotoSecretHint": "Секрет FakeTLS клиента. Перегенерируйте, чтобы сменить.",
|
||||
"mtprotoAdTag": "Рекламный тег (спонсорский канал)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "Секретный ключ",
|
||||
"publicKey": "Публичный ключ",
|
||||
"subnetIp": "Подсеть",
|
||||
"subnetCidr": "Маска подсети (CIDR)",
|
||||
"allowedIPs": "Разрешенные IP-адреса",
|
||||
"endpoint": "Конечная точка",
|
||||
"domainStrategy": "Стратегия домена"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "Приватный ключ",
|
||||
"publicKey": "Публичный ключ",
|
||||
"subnetIp": "Подсеть",
|
||||
"subnetCidr": "Маска подсети (CIDR)",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "Основной DNS",
|
||||
"secondaryDns": "Резервный DNS",
|
||||
"externalInterface": "Внешний интерфейс",
|
||||
"externalInterfaceHint": "Сетевой интерфейс хоста для NAT (PostUp/PostDown). Оставьте пустым для автоопределения.",
|
||||
"ipv6Enabled": "Включить IPv6",
|
||||
"ipv6Subnet": "Подсеть IPv6",
|
||||
"ipv6SubnetHint": "Например, fd86:ea04:1115::/64. Обязательно при включённом IPv6.",
|
||||
"ipv6ExternalInterface": "Внешний интерфейс для IPv6",
|
||||
"ipv6ExternalInterfaceHint": "Сетевой интерфейс хоста, на который алиасится IPv6-адрес каждого клиента. Оставьте пустым, чтобы использовать «Внешний интерфейс».",
|
||||
"obfuscation": "Параметры обфускации",
|
||||
"regenerateObfuscation": "Сгенерировать заново",
|
||||
"jc": "Jc (кол-во мусорных пакетов)",
|
||||
"jmin": "Jmin (мин. размер мусорного пакета)",
|
||||
"jmax": "Jmax (макс. размер мусорного пакета)",
|
||||
"s1": "S1 (мусор init-пакета)",
|
||||
"s2": "S2 (мусор response-пакета)",
|
||||
"s3": "S3 (паддинг cookie reply)",
|
||||
"s4": "S4 (паддинг transport-пакета)",
|
||||
"h1": "H1 (магический заголовок)",
|
||||
"h2": "H2 (магический заголовок)",
|
||||
"h3": "H3 (магический заголовок)",
|
||||
"h4": "H4 (магический заголовок)",
|
||||
"hHint": "Целое число или диапазон low-high. Оставьте пустым для классических значений 1/2/3/4.",
|
||||
"i1": "I1 (сигнатурный пакет)",
|
||||
"i1Hint": "Необязательный сигнатурный пакет. Оставьте пустым, чтобы не отправлять.",
|
||||
"i2": "I2 (сигнатурный пакет)",
|
||||
"i3": "I3 (сигнатурный пакет)",
|
||||
"i4": "I4 (сигнатурный пакет)",
|
||||
"i5": "I5 (сигнатурный пакет)",
|
||||
"headerProtectionKey": "HeaderProtectionKey (защита заголовков)",
|
||||
"headerProtectionKeyHint": "Ключ Base64 длиной 32 байта; должен совпадать в конфигурации каждого клиента. Оставьте пустым, чтобы отключить защиту заголовков.",
|
||||
"contentPaddingAddition": "ContentPaddingAddition (паддинг содержимого)",
|
||||
"contentPaddingAdditionHint": "Целое число или диапазон байт, добавляемых к пакетам с данными. Оставьте пустым, чтобы отключить.",
|
||||
"rekeyAfterTime": "RekeyAfterTime (секунды)",
|
||||
"rekeyTimeout": "RekeyTimeout (секунды)",
|
||||
"rejectAfterTime": "RejectAfterTime (секунды)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout (секунды)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "Целое число или диапазон low-high. Оставьте пустым для значения WireGuard по умолчанию.",
|
||||
"maxHandshakeAttemptsHint": "Число повторов рукопожатия до отказа. Оставьте пустым для значения по умолчанию.",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "Добавляет случайные байты в конец каждого пакета. Обе стороны должны поддерживать AmneziaWG 3.1+.",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "Не отправлять cookie reply — убирает сигнатуру для DPI, но ослабляет защиту от флуда."
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "Уровень пользователя"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "Günlükler",
|
||||
"accessLogs": "Erişim Günlükleri",
|
||||
"autoUpdate": "Otomatik Güncelleme",
|
||||
"amneziawgLogs": "AmneziaWG Günlükleri",
|
||||
"amneziawgHandshake": "Son El Sıkışma",
|
||||
"amneziawgInterface": "Arayüz",
|
||||
"amneziawgInbound": "Gelen",
|
||||
"amneziawgEndpoint": "Uç Nokta",
|
||||
"amneziawgIdle": "Boşta",
|
||||
"amneziawgEvents": "Olaylar",
|
||||
"amneziawgNoPeers": "Şu anda etkin AmneziaWG eşi yok",
|
||||
"amneziawgNoEvents": "Henüz AmneziaWG olayı kaydedilmedi",
|
||||
"config": "Yapılandırma",
|
||||
"backupTitle": "Yedekleme ve Geri Yükleme",
|
||||
"exportDatabase": "Yedekle",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "WireGuard Ön Paylaşımlı Anahtar",
|
||||
"wireguardAllowedIPs": "WireGuard İzin Verilen IP'ler",
|
||||
"wireguardAllowedIPsHint": "Otomatik atama için boş bırakın; girişleri virgülle ayırın",
|
||||
"amneziaWgPrivateKey": "AmneziaWG Özel Anahtarı",
|
||||
"amneziaWgPublicKey": "AmneziaWG Genel Anahtarı",
|
||||
"amneziaWgPreSharedKey": "AmneziaWG Ön Paylaşımlı Anahtar",
|
||||
"amneziaWgAllowedIPs": "AmneziaWG İzin Verilen IP'ler",
|
||||
"amneziaWgAllowedIPsHint": "Otomatik atama için boş bırakın; girişleri virgülle ayırın",
|
||||
"amneziaWgForwardedPorts": "Yönlendirilen Portlar",
|
||||
"amneziaWgForwardedPortsHint": "Bu istemciye DNAT ile yönlendirilen port/aralıklar, örn. 80, 443, 8000-8100. Yoksa boş bırakın.",
|
||||
"amneziaWgConfig": "AmneziaWG Yapılandırması",
|
||||
"mtprotoSecret": "MTProto sırrı",
|
||||
"mtprotoSecretHint": "İstemcinin FakeTLS sırrı. Değiştirmek için yeniden oluşturun.",
|
||||
"mtprotoAdTag": "Reklam etiketi (sponsorlu kanal)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "Gizli Anahtar",
|
||||
"publicKey": "Genel Anahtar",
|
||||
"subnetIp": "Alt Ağ",
|
||||
"subnetCidr": "Alt Ağ CIDR",
|
||||
"allowedIPs": "İzin Verilen IP'ler",
|
||||
"endpoint": "Uç Nokta",
|
||||
"domainStrategy": "Alan Adı Stratejisi"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "Özel Anahtar",
|
||||
"publicKey": "Genel Anahtar",
|
||||
"subnetIp": "Alt Ağ",
|
||||
"subnetCidr": "Alt Ağ CIDR",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "Birincil DNS",
|
||||
"secondaryDns": "İkincil DNS",
|
||||
"externalInterface": "Harici Arayüz",
|
||||
"externalInterfaceHint": "NAT (PostUp/PostDown) için sunucu ağ arayüzü. Otomatik algılama için boş bırakın.",
|
||||
"ipv6Enabled": "IPv6'yı Etkinleştir",
|
||||
"ipv6Subnet": "IPv6 Alt Ağı",
|
||||
"ipv6SubnetHint": "örn. fd86:ea04:1115::/64. IPv6 etkinken zorunludur.",
|
||||
"ipv6ExternalInterface": "IPv6 Harici Arayüzü",
|
||||
"ipv6ExternalInterfaceHint": "NDP proxy girişleri için sunucu ağ arayüzü. Harici Arayüzü kullanmak için boş bırakın.",
|
||||
"obfuscation": "Gizleme parametreleri",
|
||||
"regenerateObfuscation": "Yeniden oluştur",
|
||||
"jc": "Jc (gereksiz paket sayısı)",
|
||||
"jmin": "Jmin (min gereksiz paket boyutu)",
|
||||
"jmax": "Jmax (maks gereksiz paket boyutu)",
|
||||
"s1": "S1 (init paketi dolgu boyutu)",
|
||||
"s2": "S2 (response paketi dolgu boyutu)",
|
||||
"s3": "S3 (cookie reply dolgusu)",
|
||||
"s4": "S4 (transport paketi dolgusu)",
|
||||
"h1": "H1 (sihirli başlık)",
|
||||
"h2": "H2 (sihirli başlık)",
|
||||
"h3": "H3 (sihirli başlık)",
|
||||
"h4": "H4 (sihirli başlık)",
|
||||
"hHint": "Tek bir tam sayı veya bir aralık. Klasik 1/2/3/4 varsayılanları için boş bırakın.",
|
||||
"i1": "I1 (imza paketi)",
|
||||
"i1Hint": "İsteğe bağlı imza paketi. Göndermemek için boş bırakın.",
|
||||
"i2": "I2 (imza paketi)",
|
||||
"i3": "I3 (imza paketi)",
|
||||
"i4": "I4 (imza paketi)",
|
||||
"i5": "I5 (imza paketi)",
|
||||
"headerProtectionKey": "HeaderProtectionKey (başlık koruması)",
|
||||
"headerProtectionKeyHint": "32 baytlık Base64 anahtar; her istemcinin yapılandırmasıyla eşleşmelidir. Başlık korumasını devre dışı bırakmak için boş bırakın.",
|
||||
"contentPaddingAddition": "ContentPaddingAddition (içerik dolgusu)",
|
||||
"contentPaddingAdditionHint": "İçerik paketlerine eklenen tek bir tam sayı veya bayt aralığı. Devre dışı bırakmak için boş bırakın.",
|
||||
"rekeyAfterTime": "RekeyAfterTime (saniye)",
|
||||
"rekeyTimeout": "RekeyTimeout (saniye)",
|
||||
"rejectAfterTime": "RejectAfterTime (saniye)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout (saniye)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "Tek bir tam sayı veya bir aralık. WireGuard varsayılanı için boş bırakın.",
|
||||
"maxHandshakeAttemptsHint": "Vazgeçmeden önceki el sıkışma denemesi sayısı. Varsayılan için boş bırakın.",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "Her paketin sonuna rastgele baytlar ekler. Her iki uç da AmneziaWG 3.1+ gerektirir.",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "Cookie reply asla gönderilmez — bir DPI parmak izini kaldırır ancak taşma korumasını zayıflatır."
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "Kullanıcı Seviyesi"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "Логи",
|
||||
"accessLogs": "Логи доступу",
|
||||
"autoUpdate": "Автооновлення",
|
||||
"amneziawgLogs": "Логи AmneziaWG",
|
||||
"amneziawgHandshake": "Останнє рукостискання",
|
||||
"amneziawgInterface": "Інтерфейс",
|
||||
"amneziawgInbound": "Вхідне",
|
||||
"amneziawgEndpoint": "Точка підключення",
|
||||
"amneziawgIdle": "Очікування",
|
||||
"amneziawgEvents": "Події",
|
||||
"amneziawgNoPeers": "Немає активних пірів AmneziaWG",
|
||||
"amneziawgNoEvents": "Подій AmneziaWG ще не зафіксовано",
|
||||
"config": "Конфігурація",
|
||||
"backupTitle": "Резервне копіювання та відновлення",
|
||||
"exportDatabase": "Резервна копія",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "Спільний ключ WireGuard",
|
||||
"wireguardAllowedIPs": "Дозволені IP WireGuard",
|
||||
"wireguardAllowedIPsHint": "Залиште порожнім для автопризначення; розділяйте записи комами",
|
||||
"amneziaWgPrivateKey": "Приватний ключ AmneziaWG",
|
||||
"amneziaWgPublicKey": "Публічний ключ AmneziaWG",
|
||||
"amneziaWgPreSharedKey": "Спільний ключ AmneziaWG",
|
||||
"amneziaWgAllowedIPs": "Дозволені IP AmneziaWG",
|
||||
"amneziaWgAllowedIPsHint": "Залиште порожнім для автопризначення; розділяйте записи комами",
|
||||
"amneziaWgForwardedPorts": "Перенаправлені порти",
|
||||
"amneziaWgForwardedPortsHint": "Порти/діапазони, що перенаправляються (DNAT) на цього клієнта, напр. 80, 443, 8000-8100. Залиште порожнім, якщо не потрібно.",
|
||||
"amneziaWgConfig": "Конфігурація AmneziaWG",
|
||||
"mtprotoSecret": "Секрет MTProto",
|
||||
"mtprotoSecretHint": "Секрет FakeTLS клієнта. Згенеруйте заново, щоб змінити.",
|
||||
"mtprotoAdTag": "Рекламний тег (спонсорський канал)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "Приватний ключ",
|
||||
"publicKey": "Публічний ключ",
|
||||
"subnetIp": "Підмережа",
|
||||
"subnetCidr": "CIDR підмережі",
|
||||
"allowedIPs": "Дозволені IP-адреси",
|
||||
"endpoint": "Кінцева точка",
|
||||
"domainStrategy": "Стратегія домену"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "Приватний ключ",
|
||||
"publicKey": "Публічний ключ",
|
||||
"subnetIp": "Підмережа",
|
||||
"subnetCidr": "CIDR підмережі",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "Основний DNS",
|
||||
"secondaryDns": "Резервний DNS",
|
||||
"externalInterface": "Зовнішній інтерфейс",
|
||||
"externalInterfaceHint": "Мережевий інтерфейс хоста для NAT (PostUp/PostDown). Залиште порожнім для автовизначення.",
|
||||
"ipv6Enabled": "Увімкнути IPv6",
|
||||
"ipv6Subnet": "Підмережа IPv6",
|
||||
"ipv6SubnetHint": "напр. fd86:ea04:1115::/64. Обов'язково, якщо IPv6 увімкнено.",
|
||||
"ipv6ExternalInterface": "Зовнішній інтерфейс IPv6",
|
||||
"ipv6ExternalInterfaceHint": "Мережевий інтерфейс хоста для записів NDP-проксі. Залиште порожнім, щоб використовувати Зовнішній інтерфейс.",
|
||||
"obfuscation": "Параметри обфускації",
|
||||
"regenerateObfuscation": "Згенерувати заново",
|
||||
"jc": "Jc (кількість сміттєвих пакетів)",
|
||||
"jmin": "Jmin (мін. розмір сміттєвого пакета)",
|
||||
"jmax": "Jmax (макс. розмір сміттєвого пакета)",
|
||||
"s1": "S1 (заповнення пакета init)",
|
||||
"s2": "S2 (заповнення пакета response)",
|
||||
"s3": "S3 (заповнення cookie reply)",
|
||||
"s4": "S4 (заповнення транспортного пакета)",
|
||||
"h1": "H1 (магічний заголовок)",
|
||||
"h2": "H2 (магічний заголовок)",
|
||||
"h3": "H3 (магічний заголовок)",
|
||||
"h4": "H4 (магічний заголовок)",
|
||||
"hHint": "Ціле число або діапазон. Залиште порожнім для класичних значень 1/2/3/4.",
|
||||
"i1": "I1 (пакет підпису)",
|
||||
"i1Hint": "Необов'язковий пакет підпису. Залиште порожнім, щоб не надсилати.",
|
||||
"i2": "I2 (пакет підпису)",
|
||||
"i3": "I3 (пакет підпису)",
|
||||
"i4": "I4 (пакет підпису)",
|
||||
"i5": "I5 (пакет підпису)",
|
||||
"headerProtectionKey": "HeaderProtectionKey (захист заголовків)",
|
||||
"headerProtectionKeyHint": "Ключ Base64 довжиною 32 байти; має збігатися в конфігурації кожного клієнта. Залиште порожнім, щоб вимкнути захист заголовків.",
|
||||
"contentPaddingAddition": "ContentPaddingAddition (заповнення вмісту)",
|
||||
"contentPaddingAdditionHint": "Ціле число або діапазон байтів, що додаються до пакетів із даними. Залиште порожнім, щоб вимкнути.",
|
||||
"rekeyAfterTime": "RekeyAfterTime (секунди)",
|
||||
"rekeyTimeout": "RekeyTimeout (секунди)",
|
||||
"rejectAfterTime": "RejectAfterTime (секунди)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout (секунди)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "Ціле число або діапазон. Залиште порожнім для типового значення WireGuard.",
|
||||
"maxHandshakeAttemptsHint": "Кількість повторних спроб рукостискання. Залиште порожнім для типового значення.",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "Додає випадкові байти в кінець кожного пакета. Обидві сторони мають підтримувати AmneziaWG 3.1+.",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "Ніколи не надсилати cookie reply — прибирає відбиток для DPI, але послаблює захист від флуду."
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "Рівень користувача"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "Nhật ký",
|
||||
"accessLogs": "Nhật ký truy cập",
|
||||
"autoUpdate": "Tự động cập nhật",
|
||||
"amneziawgLogs": "Nhật ký AmneziaWG",
|
||||
"amneziawgHandshake": "Bắt tay gần nhất",
|
||||
"amneziawgInterface": "Giao diện mạng",
|
||||
"amneziawgInbound": "Inbound",
|
||||
"amneziawgEndpoint": "Điểm cuối",
|
||||
"amneziawgIdle": "Nhàn rỗi",
|
||||
"amneziawgEvents": "Sự kiện",
|
||||
"amneziawgNoPeers": "Hiện không có peer AmneziaWG nào hoạt động",
|
||||
"amneziawgNoEvents": "Chưa ghi nhận sự kiện AmneziaWG nào",
|
||||
"config": "Cấu hình",
|
||||
"backupTitle": "Sao lưu & Khôi phục",
|
||||
"exportDatabase": "Sao lưu",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "Khóa chia sẻ trước WireGuard",
|
||||
"wireguardAllowedIPs": "IP được phép WireGuard",
|
||||
"wireguardAllowedIPsHint": "Để trống để tự động gán; phân tách các mục bằng dấu phẩy",
|
||||
"amneziaWgPrivateKey": "Khóa riêng AmneziaWG",
|
||||
"amneziaWgPublicKey": "Khóa công khai AmneziaWG",
|
||||
"amneziaWgPreSharedKey": "Khóa chia sẻ trước AmneziaWG",
|
||||
"amneziaWgAllowedIPs": "IP được phép AmneziaWG",
|
||||
"amneziaWgAllowedIPsHint": "Để trống để tự động gán; phân tách các mục bằng dấu phẩy",
|
||||
"amneziaWgForwardedPorts": "Cổng chuyển tiếp",
|
||||
"amneziaWgForwardedPortsHint": "Cổng/dải cổng được chuyển tiếp (DNAT) đến client này, vd. 80, 443, 8000-8100. Để trống nếu không cần.",
|
||||
"amneziaWgConfig": "Cấu hình AmneziaWG",
|
||||
"mtprotoSecret": "Secret MTProto",
|
||||
"mtprotoSecretHint": "Secret FakeTLS của client. Tạo lại để thay đổi.",
|
||||
"mtprotoAdTag": "Ad-tag (kênh tài trợ)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "Khoá bí mật",
|
||||
"publicKey": "Khóa công khai",
|
||||
"subnetIp": "Mạng con",
|
||||
"subnetCidr": "CIDR mạng con",
|
||||
"allowedIPs": "IP được phép",
|
||||
"endpoint": "Điểm cuối",
|
||||
"domainStrategy": "Chiến lược tên miền"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "Khóa riêng",
|
||||
"publicKey": "Khóa công khai",
|
||||
"subnetIp": "Mạng con",
|
||||
"subnetCidr": "CIDR mạng con",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "DNS chính",
|
||||
"secondaryDns": "DNS phụ",
|
||||
"externalInterface": "Giao diện ngoài",
|
||||
"externalInterfaceHint": "Card mạng của host dùng cho NAT (PostUp/PostDown). Để trống để tự động phát hiện.",
|
||||
"ipv6Enabled": "Bật IPv6",
|
||||
"ipv6Subnet": "Subnet IPv6",
|
||||
"ipv6SubnetHint": "vd. fd86:ea04:1115::/64. Bắt buộc khi bật IPv6.",
|
||||
"ipv6ExternalInterface": "Card mạng ngoài IPv6",
|
||||
"ipv6ExternalInterfaceHint": "Card mạng của host dùng cho các mục NDP proxy. Để trống để dùng lại Card mạng ngoài.",
|
||||
"obfuscation": "Tham số làm rối (obfuscation)",
|
||||
"regenerateObfuscation": "Tạo lại",
|
||||
"jc": "Jc (số lượng gói rác)",
|
||||
"jmin": "Jmin (kích thước tối thiểu gói rác)",
|
||||
"jmax": "Jmax (kích thước tối đa gói rác)",
|
||||
"s1": "S1 (đệm gói init)",
|
||||
"s2": "S2 (đệm gói response)",
|
||||
"s3": "S3 (đệm cookie reply)",
|
||||
"s4": "S4 (đệm gói transport)",
|
||||
"h1": "H1 (tiêu đề ma thuật)",
|
||||
"h2": "H2 (tiêu đề ma thuật)",
|
||||
"h3": "H3 (tiêu đề ma thuật)",
|
||||
"h4": "H4 (tiêu đề ma thuật)",
|
||||
"hHint": "Một số nguyên hoặc một khoảng. Để trống để dùng giá trị mặc định cổ điển 1/2/3/4.",
|
||||
"i1": "I1 (gói chữ ký)",
|
||||
"i1Hint": "Gói chữ ký tùy chọn. Để trống để bỏ qua.",
|
||||
"i2": "I2 (gói chữ ký)",
|
||||
"i3": "I3 (gói chữ ký)",
|
||||
"i4": "I4 (gói chữ ký)",
|
||||
"i5": "I5 (gói chữ ký)",
|
||||
"headerProtectionKey": "HeaderProtectionKey (bảo vệ header)",
|
||||
"headerProtectionKeyHint": "Khóa Base64 dài 32 byte; phải trùng khớp trong cấu hình của mọi client. Để trống để tắt bảo vệ header.",
|
||||
"contentPaddingAddition": "ContentPaddingAddition (đệm nội dung)",
|
||||
"contentPaddingAdditionHint": "Một số nguyên hoặc khoảng byte được thêm vào các gói nội dung. Để trống để tắt.",
|
||||
"rekeyAfterTime": "RekeyAfterTime (giây)",
|
||||
"rekeyTimeout": "RekeyTimeout (giây)",
|
||||
"rejectAfterTime": "RejectAfterTime (giây)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout (giây)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "Một số nguyên hoặc một khoảng. Để trống để dùng giá trị mặc định của WireGuard.",
|
||||
"maxHandshakeAttemptsHint": "Số lần thử lại bắt tay trước khi bỏ cuộc. Để trống để dùng giá trị mặc định.",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "Thêm các byte ngẫu nhiên vào cuối mỗi gói. Cả hai đầu cần AmneziaWG 3.1+.",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "Không bao giờ gửi cookie reply — xóa một dấu vết DPI nhưng làm yếu khả năng chống flood."
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "Mức Người Dùng"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "日志",
|
||||
"accessLogs": "访问日志",
|
||||
"autoUpdate": "自动更新",
|
||||
"amneziawgLogs": "AmneziaWG 日志",
|
||||
"amneziawgHandshake": "最后握手",
|
||||
"amneziawgInterface": "网络接口",
|
||||
"amneziawgInbound": "入站",
|
||||
"amneziawgEndpoint": "端点",
|
||||
"amneziawgIdle": "空闲",
|
||||
"amneziawgEvents": "事件",
|
||||
"amneziawgNoPeers": "当前没有活动的 AmneziaWG 对端",
|
||||
"amneziawgNoEvents": "尚未记录 AmneziaWG 事件",
|
||||
"config": "配置",
|
||||
"backupTitle": "备份和恢复",
|
||||
"exportDatabase": "备份",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "WireGuard 预共享密钥",
|
||||
"wireguardAllowedIPs": "WireGuard 允许的 IP",
|
||||
"wireguardAllowedIPsHint": "留空则自动分配;多个条目用逗号分隔",
|
||||
"amneziaWgPrivateKey": "AmneziaWG 私钥",
|
||||
"amneziaWgPublicKey": "AmneziaWG 公钥",
|
||||
"amneziaWgPreSharedKey": "AmneziaWG 预共享密钥",
|
||||
"amneziaWgAllowedIPs": "AmneziaWG 允许的 IP",
|
||||
"amneziaWgAllowedIPsHint": "留空则自动分配;多个条目用逗号分隔",
|
||||
"amneziaWgForwardedPorts": "转发端口",
|
||||
"amneziaWgForwardedPortsHint": "转发到此客户端的端口/范围,例如 80, 443, 8000-8100。留空则不转发。",
|
||||
"amneziaWgConfig": "AmneziaWG 配置",
|
||||
"mtprotoSecret": "MTProto 密钥",
|
||||
"mtprotoSecretHint": "该客户端的 FakeTLS 密钥。重新生成即可更换。",
|
||||
"mtprotoAdTag": "广告标签(赞助频道)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "密钥",
|
||||
"publicKey": "公钥",
|
||||
"subnetIp": "子网",
|
||||
"subnetCidr": "子网 CIDR",
|
||||
"allowedIPs": "允许的 IP",
|
||||
"endpoint": "端点",
|
||||
"domainStrategy": "域策略"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "私钥",
|
||||
"publicKey": "公钥",
|
||||
"subnetIp": "子网",
|
||||
"subnetCidr": "子网 CIDR",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "主 DNS",
|
||||
"secondaryDns": "备用 DNS",
|
||||
"externalInterface": "外部网卡",
|
||||
"externalInterfaceHint": "用于 NAT(PostUp/PostDown)的主机网卡。留空则自动检测。",
|
||||
"ipv6Enabled": "启用 IPv6",
|
||||
"ipv6Subnet": "IPv6 子网",
|
||||
"ipv6SubnetHint": "例如 fd86:ea04:1115::/64。启用 IPv6 时必填。",
|
||||
"ipv6ExternalInterface": "IPv6 外部网卡",
|
||||
"ipv6ExternalInterfaceHint": "用于 NDP 代理条目的主机网卡。留空则使用外部网卡。",
|
||||
"obfuscation": "混淆参数",
|
||||
"regenerateObfuscation": "重新生成",
|
||||
"jc": "Jc(垃圾包数量)",
|
||||
"jmin": "Jmin(垃圾包最小大小)",
|
||||
"jmax": "Jmax(垃圾包最大大小)",
|
||||
"s1": "S1(init 包填充大小)",
|
||||
"s2": "S2(response 包填充大小)",
|
||||
"s3": "S3(cookie reply 填充)",
|
||||
"s4": "S4(传输包填充)",
|
||||
"h1": "H1(魔术头)",
|
||||
"h2": "H2(魔术头)",
|
||||
"h3": "H3(魔术头)",
|
||||
"h4": "H4(魔术头)",
|
||||
"hHint": "单个整数或范围。留空则使用经典默认值 1/2/3/4。",
|
||||
"i1": "I1(签名包)",
|
||||
"i1Hint": "可选的签名包。留空则不发送。",
|
||||
"i2": "I2(签名包)",
|
||||
"i3": "I3(签名包)",
|
||||
"i4": "I4(签名包)",
|
||||
"i5": "I5(签名包)",
|
||||
"headerProtectionKey": "HeaderProtectionKey(头部保护)",
|
||||
"headerProtectionKeyHint": "Base64 编码的 32 字节密钥;必须与每个客户端配置一致。留空则禁用头部保护。",
|
||||
"contentPaddingAddition": "ContentPaddingAddition(内容填充)",
|
||||
"contentPaddingAdditionHint": "单个整数或 low-high 字节范围,附加到内容数据包。留空则禁用。",
|
||||
"rekeyAfterTime": "RekeyAfterTime(秒)",
|
||||
"rekeyTimeout": "RekeyTimeout(秒)",
|
||||
"rejectAfterTime": "RejectAfterTime(秒)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout(秒)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "单个整数或范围。留空则使用 WireGuard 默认值。",
|
||||
"maxHandshakeAttemptsHint": "放弃前的握手重试次数。留空则使用默认值。",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "在每个数据包末尾追加随机字节。两端都需要 AmneziaWG 3.1+。",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "从不发送 cookie reply——消除一个 DPI 指纹,但会削弱抗洪泛能力。"
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "用户级别"
|
||||
},
|
||||
|
||||
@@ -232,6 +232,15 @@
|
||||
"logs": "記錄",
|
||||
"accessLogs": "存取記錄",
|
||||
"autoUpdate": "自動更新",
|
||||
"amneziawgLogs": "AmneziaWG 日誌",
|
||||
"amneziawgHandshake": "最後握手",
|
||||
"amneziawgInterface": "網路介面",
|
||||
"amneziawgInbound": "入站",
|
||||
"amneziawgEndpoint": "端點",
|
||||
"amneziawgIdle": "閒置",
|
||||
"amneziawgEvents": "事件",
|
||||
"amneziawgNoPeers": "目前沒有活躍的 AmneziaWG 對端",
|
||||
"amneziawgNoEvents": "尚未記錄 AmneziaWG 事件",
|
||||
"config": "配置",
|
||||
"backupTitle": "備份和恢復",
|
||||
"exportDatabase": "備份",
|
||||
@@ -858,6 +867,14 @@
|
||||
"wireguardPreSharedKey": "WireGuard 預共用金鑰",
|
||||
"wireguardAllowedIPs": "WireGuard 允許的 IP",
|
||||
"wireguardAllowedIPsHint": "留空則自動分配;多個條目用逗號分隔",
|
||||
"amneziaWgPrivateKey": "AmneziaWG 私鑰",
|
||||
"amneziaWgPublicKey": "AmneziaWG 公鑰",
|
||||
"amneziaWgPreSharedKey": "AmneziaWG 預共用金鑰",
|
||||
"amneziaWgAllowedIPs": "AmneziaWG 允許的 IP",
|
||||
"amneziaWgAllowedIPsHint": "留空則自動分配;多個條目用逗號分隔",
|
||||
"amneziaWgForwardedPorts": "轉發連接埠",
|
||||
"amneziaWgForwardedPortsHint": "轉發到此客戶端的連接埠/範圍,例如 80, 443, 8000-8100。留空則不轉發。",
|
||||
"amneziaWgConfig": "AmneziaWG 設定",
|
||||
"mtprotoSecret": "MTProto 金鑰",
|
||||
"mtprotoSecretHint": "該用戶端的 FakeTLS 金鑰。重新產生即可更換。",
|
||||
"mtprotoAdTag": "廣告標籤(贊助頻道)",
|
||||
@@ -1769,10 +1786,63 @@
|
||||
"wireguard": {
|
||||
"secretKey": "金鑰",
|
||||
"publicKey": "公鑰",
|
||||
"subnetIp": "子網路",
|
||||
"subnetCidr": "子網路 CIDR",
|
||||
"allowedIPs": "允許的 IP",
|
||||
"endpoint": "端點",
|
||||
"domainStrategy": "域策略"
|
||||
},
|
||||
"amneziawg": {
|
||||
"privateKey": "私鑰",
|
||||
"publicKey": "公鑰",
|
||||
"subnetIp": "子網路",
|
||||
"subnetCidr": "子網路 CIDR",
|
||||
"mtu": "MTU",
|
||||
"primaryDns": "主要 DNS",
|
||||
"secondaryDns": "次要 DNS",
|
||||
"externalInterface": "外部網路介面",
|
||||
"externalInterfaceHint": "用於 NAT(PostUp/PostDown)的主機網路介面。留空則自動偵測。",
|
||||
"ipv6Enabled": "啟用 IPv6",
|
||||
"ipv6Subnet": "IPv6 子網路",
|
||||
"ipv6SubnetHint": "例如 fd86:ea04:1115::/64。啟用 IPv6 時必填。",
|
||||
"ipv6ExternalInterface": "IPv6 外部網路介面",
|
||||
"ipv6ExternalInterfaceHint": "用於 NDP 代理項目的主機網路介面。留空則使用外部網路介面。",
|
||||
"obfuscation": "混淆參數",
|
||||
"regenerateObfuscation": "重新產生",
|
||||
"jc": "Jc(垃圾封包數量)",
|
||||
"jmin": "Jmin(垃圾封包最小大小)",
|
||||
"jmax": "Jmax(垃圾封包最大大小)",
|
||||
"s1": "S1(init 封包填充大小)",
|
||||
"s2": "S2(response 封包填充大小)",
|
||||
"s3": "S3(cookie reply 填充)",
|
||||
"s4": "S4(傳輸封包填充)",
|
||||
"h1": "H1(魔術標頭)",
|
||||
"h2": "H2(魔術標頭)",
|
||||
"h3": "H3(魔術標頭)",
|
||||
"h4": "H4(魔術標頭)",
|
||||
"hHint": "單一整數或範圍。留空則使用經典預設值 1/2/3/4。",
|
||||
"i1": "I1(簽章封包)",
|
||||
"i1Hint": "可選的簽章封包。留空則不傳送。",
|
||||
"i2": "I2(簽章封包)",
|
||||
"i3": "I3(簽章封包)",
|
||||
"i4": "I4(簽章封包)",
|
||||
"i5": "I5(簽章封包)",
|
||||
"headerProtectionKey": "HeaderProtectionKey(標頭保護)",
|
||||
"headerProtectionKeyHint": "Base64 編碼的 32 位元組金鑰;必須與每個用戶端設定一致。留空則停用標頭保護。",
|
||||
"contentPaddingAddition": "ContentPaddingAddition(內容填充)",
|
||||
"contentPaddingAdditionHint": "單一整數或 low-high 位元組範圍,附加到內容封包。留空則停用。",
|
||||
"rekeyAfterTime": "RekeyAfterTime(秒)",
|
||||
"rekeyTimeout": "RekeyTimeout(秒)",
|
||||
"rejectAfterTime": "RejectAfterTime(秒)",
|
||||
"keepaliveTimeout": "KeepaliveTimeout(秒)",
|
||||
"maxHandshakeAttempts": "MaxHandshakeAttempts",
|
||||
"timingRangeHint": "單一整數或範圍。留空則使用 WireGuard 預設值。",
|
||||
"maxHandshakeAttemptsHint": "放棄前的交握重試次數。留空則使用預設值。",
|
||||
"randomTrailers": "RandomTrailers",
|
||||
"randomTrailersHint": "在每個封包結尾附加隨機位元組。兩端都需要 AmneziaWG 3.1+。",
|
||||
"disableCookies": "DisableCookies",
|
||||
"disableCookiesHint": "永不傳送 cookie reply——消除一個 DPI 指紋,但會削弱抗洪泛能力。"
|
||||
},
|
||||
"tun": {
|
||||
"userLevel": "用戶級別"
|
||||
},
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/eventbus"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
@@ -291,6 +292,7 @@ const (
|
||||
cadenceXrayRestart = "@every 30s"
|
||||
cadenceXrayTraffic = "@every 5s"
|
||||
cadenceMtproto = "@every 10s"
|
||||
cadenceAmneziaWG = "@every 10s"
|
||||
cadenceClientIPScan = "@every 10s"
|
||||
cadenceNodeHeartbeat = "@every 5s"
|
||||
cadenceNodeTraffic = "@every 5s"
|
||||
@@ -332,6 +334,11 @@ func (s *Server) startTask(restartXray bool, loc *time.Location) {
|
||||
_, _ = s.cron.AddJob(cadenceMtproto, mtJob)
|
||||
go mtJob.Run()
|
||||
|
||||
// Reconcile embedded AmneziaWG interfaces; traffic rides Xray's own stats
|
||||
awgJob := job.NewAmneziaWGJob()
|
||||
_, _ = s.cron.AddJob(cadenceAmneziaWG, awgJob)
|
||||
go awgJob.Run()
|
||||
|
||||
// check client ips from log file every 10 sec
|
||||
_, _ = s.cron.AddJob(cadenceClientIPScan, job.NewCheckClientIpJob())
|
||||
|
||||
@@ -691,6 +698,7 @@ func (s *Server) stop(stopXray bool, stopTgBot bool) error {
|
||||
if stopXray {
|
||||
_ = s.xrayService.StopXray()
|
||||
mtproto.GetManager().StopAll()
|
||||
amneziawgnet.GetManager().StopAll()
|
||||
}
|
||||
if s.cron != nil {
|
||||
s.cron.Stop()
|
||||
|
||||
Reference in New Issue
Block a user