mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-02 03:05:02 +03:00
56ac8d0fc7
* feat(amneziawg): add opt-in Linux kernel datapath Add the kernel backend as an explicit per-inbound option while keeping the embedded backend as the default. Include host preflight, UI/API support, the bundled installer CLI, lifecycle and accounting integration, regression tests, and upstream-facing documentation. Kernel mode is NAT-only and rejects unsupported routing, IPv6, forwarding, and pinned-listen configurations. Local saves check the local host; remote nodes check their own host during apply. Preserve adopted interface accounting across panel restarts, retain manager state after failed teardown so the job can retry, prevent embedded startup while a kernel interface remains live, and prune collector state for removed peers. Tested the restart accounting path on Debian 13 with XanMod 7.1.11 on x86_64; Docker and cross-kernel coverage are not claimed. * fix(amneziawg): align readiness and endpoint reporting Expire endpoint sightings using the latest handshake and sweep stale addresses for the polled interface. Keep the readiness API schema, generated client types, and ready-host empty blocker list consistent; watch the nested form field and defer local readiness checks for remote targets. Document safe rollback before using a build without kernel support. Regression evidence: the idle endpoint test failed before the collector change because the old address remained visible after 31 minutes; endpoint tests pass after the fix. The form component suite passes 3 tests; restoring the invalid array watch made its off-mode severity test fail, while the corrected dot-path watch passes. Targeted Go regressions across amneziawgkern, job, and service pass. * style(amneziawg): format readiness test * test: reproduce kernel AWG client validation gaps * test(service): cover kernel AWG shared client fanout * fix(amneziawg): validate kernel client fanout and config values * test(amneziawgkern): cover owned interface lifecycle recovery * fix(amneziawgkern): recover owned interfaces on restart * test(amneziawgkern): retain visibility after recovered cleanup failure * fix(amneziawgkern): report recovered interfaces while cleanup retries * style(amneziawgkern): satisfy static analysis * test(amneziawgkern): cover long rendered peer comments * fix(amneziawgkern): accept long generated config comments * test(amneziawgkern): refuse foreign occupied interfaces Capture the current Ensure ordering failure with real temporary config paths and manager side-effect boundaries. * test(amneziawgkern): cover stale interface collisions Extend the Ensure regression across absent links, mismatched live interfaces, cached manager state, and Remove teardown. * fix(amneziawgkern): verify interface ownership before mutation Refuse to replace or tear down links unless the canonical config is a valid panel-owned file and its key matches the live interface. Preserve normal adoption and key rotation, and document migration of legacy unmarked configs. Validation: go test ./internal/amneziawgkern -count=1; go test -race ./internal/amneziawgkern -count=1; golangci-lint run ./internal/amneziawgkern/...; git diff --check. * build: update Go toolchain to 1.27.3 * test(amneziawg): reproduce unsafe key rotation recovery Keep the previous owned config authoritative until teardown succeeds, and require fresh managers to rebuild structural key changes. These regressions expose the stuck live-key/disk-key mismatch after teardown failure. * fix(amneziawg): recover interrupted key rotations Keep the old owned config on disk until a structural rebuild has confirmed the previous interface is down. Fresh managers only adopt when the live config and desired structural identity match, so retries and removals retain the key needed to prove ownership. * fix(scanner): align Go image with module version * fix(docs): pin pnpm release with bootstrap fix pnpm 12.9.1 restores a Node launcher before its postinstall replaces the target with ELF; pnpm 11 then runs that binary as JavaScript. Pin 12.10.0, which includes the shim fix, so the docs CI bootstrap can switch versions safely. * fix(xray): build core from pinned module The configured Xray release asset tag is unpublished, and the latest published binary lacks GetUsersStats used by the panel. Build the packaged core from the exact Xray module version already selected in go.mod for Docker and release targets. * fix(tests): stabilize local network fixtures Keep the TUIC stream fragmentation check on a working UDP loopback path, allocate the AmneziaWG fixture ports dynamically, and wait for a real Xray stats response before starting API mutation assertions. Recreate failed readiness channels so an early connection cannot stall the probe. Verified host and offline parallel Go suites, repeated occupied-port and UDP tests, race/shuffle runs, and golangci-lint. Production behavior and dependency versions are unchanged. * fix(i18n): add the kernel-mode AmneziaWG keys to sk-SK main gained the sk-SK locale after this branch added its kernel-mode keys to the other 13, so i18n-dead-keys.test.ts failed on the merged tree. * refactor(amneziawgkern): apply kernel interfaces with direct commands, no awg-quick awg-quick evaluates PostUp/PostDown through a root shell, so every value the panel rendered into its config was one validation slip away from root command execution. The interface is now built with direct ip/awg/nft execs from a setconf-only file: link add, awg setconf, address, mtu, an atomically replaced nftables table per inbound, and the IPv4 forwarding sysctl written directly. - Panel-owned names and paths: xui-awg<id> interfaces, xui_awg<id> NAT tables and configs under the panel's data dir, so nothing collides with an operator's own awg0/awg1 awg-quick tunnels in /etc/amnezia/amneziawg. - FORWARD accepts (comment 3x-ui:xui-awg<id>) when iptables is present: Docker and ufw set the FORWARD policy to DROP, which silently black-holed the tunnel. - A full panel stop records the final counters and tears the interfaces down, like the embedded datapath; a stopped panel enforces no quota or expiry. Crash survivors are still adopted without a rebuild. - The job reads counters before reconciling, and from every managed interface, so a client disabled for quota, or a removed inbound, is charged for its last interval instead of losing it with the dropped peer. - An unchanged reconcile tick forks no process (it probed the live key with `awg show` every 10s); readiness no longer loads the module from a GET. Verified on the real module (WSL2 6.6 kernel, v3.1.20260906): create, peer and egress changes in place, SIGKILL adoption with the same ifindex, SIGTERM teardown leaving no link, table, FORWARD rule or config behind. * fix(amneziawg): gate kernel host readiness only when a save starts the datapath Every save of a kernel-mode inbound re-ran the host preflight, so a host that lost its module (a kernel upgrade without a DKMS rebuild) refused even disabling the inbound or switching it back to embedded mode. Host blockers now apply only when the save starts the kernel datapath: a new inbound, a switch from embedded, or enabling a disabled one. Feature blockers (IPv6, forwarded ports, pinned listen) still apply to every save. * feat(nodes): refuse kernel-mode AmneziaWG pushes to nodes that predate it A node built before kernel mode drops the unknown kernelMode field and serves the inbound on the embedded datapath while the master's form shows kernel mode on. Nodes now advertise awg-kernel in X-3x-Node-Caps, and Remote refuses to push a kernel-mode inbound to a node that has not advertised it, learning the caps with an inbound list first when this Remote has not heard from it. * fix(amneziawg): pin the kernel module installer to verified commits The installer ran as root and built whatever upstream tag sorted newest at install time. It now clones fixed tags (module v3.1.20260906, tools v3.1.20260812) and refuses unless each resolves to its recorded commit. The udp_tunnel perl patch is gone: those releases carry the kernel 7.1.5 compat upstream, so the patch never matched. * fix(i18n): translate the kernel-mode AmneziaWG strings All thirteen non-English locales carried the English text verbatim. * fix(amneziawg): skip the kernel traffic flush when no kernel interface runs Shutdown listed the desired AmneziaWG inbounds from the database even on a panel with no kernel interface, an unneeded query on every stop. A server stopped before its database was opened panicked on it, which turned TestServerStopWhenXrayNotRunningSucceeds red whenever it ran first. --------- Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
467 lines
16 KiB
Go
467 lines
16 KiB
Go
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/amneziawgkern"
|
|
"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"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/tuic"
|
|
wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
|
|
)
|
|
|
|
// 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
|
|
}
|
|
|
|
instances := make([]amneziawg.Instance, 0, len(inbounds))
|
|
for _, ib := range inbounds {
|
|
inst, ok := amneziawg.InstanceFromInbound(ib)
|
|
if !ok {
|
|
continue
|
|
}
|
|
instances = append(instances, inst)
|
|
}
|
|
emails := make([]string, 0)
|
|
for _, inst := range instances {
|
|
for _, e := range inst.Peers {
|
|
emails = append(emails, e.Email)
|
|
}
|
|
}
|
|
disabled, err := trafficDisabledEmails(db, emails)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
served := instances[:0]
|
|
for _, inst := range instances {
|
|
kept := make([]amneziawg.Peer, 0, len(inst.Peers))
|
|
for _, e := range inst.Peers {
|
|
if _, off := disabled[e.Email]; !off {
|
|
kept = append(kept, e)
|
|
}
|
|
}
|
|
inst.Peers = kept
|
|
if len(kept) > 0 {
|
|
served = append(served, inst)
|
|
}
|
|
}
|
|
return served, 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
|
|
}
|
|
|
|
// resolveAmneziaWGServerKeys settles the server keypair for a save. An omitted
|
|
// key means "unchanged", never "mint a new one": rotating it silently
|
|
// invalidates every client config already handed out.
|
|
func resolveAmneziaWGServerKeys(server *amneziawg.ServerSettings, oldSettings string) error {
|
|
if server.PrivateKey == "" {
|
|
storedPriv, storedPub := storedAmneziaWGServerKeys(oldSettings)
|
|
if storedPriv == "" {
|
|
return fillAmneziaWGServerKeys(server)
|
|
}
|
|
server.PrivateKey, server.PublicKey = storedPriv, storedPub
|
|
}
|
|
if server.PublicKey == "" {
|
|
pub, err := wgutil.PublicKeyFromPrivate(server.PrivateKey)
|
|
if err != nil {
|
|
return fmt.Errorf("amneziawg: derive server public key: %w", err)
|
|
}
|
|
server.PublicKey = pub
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// storedAmneziaWGServerKeys returns the keypair already saved for this inbound.
|
|
// oldSettings is empty on a first save, and need not be valid AmneziaWG JSON.
|
|
func storedAmneziaWGServerKeys(oldSettings string) (priv, pub string) {
|
|
if strings.TrimSpace(oldSettings) == "" {
|
|
return "", ""
|
|
}
|
|
var prev amneziawg.InboundSettings
|
|
if err := json.Unmarshal([]byte(oldSettings), &prev); err != nil || prev.Server == nil {
|
|
return "", ""
|
|
}
|
|
return prev.Server.PrivateKey, prev.Server.PublicKey
|
|
}
|
|
|
|
// 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, old *model.Inbound) error {
|
|
if inbound.Protocol != model.AmneziaWG {
|
|
return nil
|
|
}
|
|
oldSettings := ""
|
|
if old != nil {
|
|
oldSettings = old.Settings
|
|
}
|
|
|
|
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 err := resolveAmneziaWGServerKeys(parsed.Server, oldSettings); 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.ValidateServerObfuscation(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(), inbound.NodeID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for i := range parsed.Clients {
|
|
c := &parsed.Clients[i]
|
|
if err := s.amneziaWGForwardedPortsConflict(portCtx, c); err != nil {
|
|
return err
|
|
}
|
|
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)
|
|
}
|
|
// An enabled peer with no address is skipped by InstanceFromInbound, and
|
|
// if it was the only one the whole inbound never starts, silently.
|
|
if c.Enable && len(normalized) == 0 {
|
|
return fmt.Errorf("amneziawg: client %q: allowedIPs is required", c.Email)
|
|
}
|
|
c.AllowedIPs = normalized
|
|
}
|
|
|
|
bs, err := json.MarshalIndent(parsed, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
inbound.Settings = string(bs)
|
|
|
|
// Host readiness gates only a save that starts the kernel datapath: a host that
|
|
// later loses its module must still let the admin edit, disable or switch it.
|
|
if parsed.Server.KernelMode && inbound.NodeID == nil {
|
|
inst, ok := amneziawg.InstanceFromInbound(inbound)
|
|
if !ok {
|
|
inst = amneziawg.Instance{
|
|
Listen: inbound.Listen,
|
|
IPv6Enabled: parsed.Server.IPv6Enabled,
|
|
RouteThroughXray: parsed.Server.RouteThroughXray,
|
|
}
|
|
for _, client := range parsed.Clients {
|
|
if client.Enable {
|
|
inst.Peers = append(inst.Peers, amneziawg.Peer{
|
|
AllowedIPs: client.AllowedIPs,
|
|
ForwardedPorts: client.ForwardedPorts,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
check := amneziawgkern.ValidateInstanceFeatures
|
|
wasRunningKernel := old != nil && old.Enable && amneziawgKernelModeSettings(old.Settings)
|
|
if inbound.Enable && !wasRunningKernel {
|
|
check = amneziawgkern.Preflight
|
|
}
|
|
if err := check(inst, inst.RouteThroughXray); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// portConflictContext caches what checkForwardedPortsConflict needs about the
|
|
// host a forward listener binds on, so one save costs one query, not N.
|
|
type portConflictContext struct {
|
|
webPort int
|
|
inbounds []*model.Inbound
|
|
// onNode: the host is a node, whose web port and relay ports (derived from
|
|
// its own inbound ids) this panel does not know; the node re-checks both.
|
|
onNode bool
|
|
}
|
|
|
|
// loadPortConflictContext loads every enabled inbound hosted where nodeID's rows
|
|
// run -- this panel for nil, else that node -- plus this panel's own port.
|
|
func (s *InboundService) loadPortConflictContext(db *gorm.DB, nodeID *int) (portConflictContext, error) {
|
|
var ctx portConflictContext
|
|
q := db.Model(model.Inbound{}).Where("enable = ?", true)
|
|
if nodeID != nil {
|
|
ctx.onNode = true
|
|
q = q.Where("node_id = ?", *nodeID)
|
|
} else {
|
|
if webPort, err := (&SettingService{}).GetPort(); err == nil {
|
|
ctx.webPort = webPort
|
|
}
|
|
q = q.Where("node_id IS NULL")
|
|
}
|
|
err := q.Find(&ctx.inbounds).Error
|
|
return ctx, err
|
|
}
|
|
|
|
// amneziaWGForwardedPortsConflict renders one client's ForwardedPorts collision,
|
|
// or nil: the single copy both the pre-Save pass and the post-Save re-run use.
|
|
func (s *InboundService) amneziaWGForwardedPortsConflict(ctx portConflictContext, c *model.Client) error {
|
|
hit := s.checkForwardedPortsConflict(ctx, c.ForwardedPorts)
|
|
if hit == "" {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("amneziawg: client %q forwardedPorts collides with %s", c.Email, hit)
|
|
}
|
|
|
|
// checkAmneziaWGForwardedPorts re-runs the guard over one row's stored clients:
|
|
// on create it ran before Save, when the row's own ports were not in the context.
|
|
func (s *InboundService) checkAmneziaWGForwardedPorts(db *gorm.DB, settings string) error {
|
|
var parsed amneziawg.InboundSettings
|
|
if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
|
|
return nil
|
|
}
|
|
ctx, err := s.loadPortConflictContext(db, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for i := range parsed.Clients {
|
|
if err := s.amneziaWGForwardedPortsConflict(ctx, &parsed.Clients[i]); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkForwardedPortsConflict names the panel, inbound or AmneziaWG relay port a
|
|
// client's ForwardedPorts spec would collide with: a lost bind race kills the relay.
|
|
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 ctx.onNode {
|
|
continue
|
|
}
|
|
var socksPort int
|
|
switch ib.Protocol {
|
|
case model.AmneziaWG:
|
|
if amneziawgKernelMode(ib) {
|
|
continue
|
|
}
|
|
socksPort = amneziawgnet.SOCKSPortForInbound(ib.Id)
|
|
case model.TUIC:
|
|
socksPort = tuic.SOCKSPortForInbound(ib.Id)
|
|
default:
|
|
continue
|
|
}
|
|
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
|
|
}
|