[GH-ISSUE #6323] [Bug]: AmneziaWG session goes silent ~1s after the handshake — server stops receiving from the peer, every server-initiated rekey fails (no TCP ever completes) #4295

Closed
opened 2026-10-31 20:38:37 +07:00 by bsakaguchi · 9 comments
Owner

Originally created by @bharmalej on GitHub (Aug 25, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6323

Describe the bug

On v3.7.0 with the new native AmneziaWG inbound, a peer completes the handshake and shows online in the panel, DNS resolves through the tunnel, but no website ever loads.

The embedded amneziawgnet device relays UDP into its loopback SOCKS5 bridge correctly, but TCP essentially never gets relayed.

Hard numbers from Xray's access.log on the same instance, same routing rules, same time window:

Inbound accepted tcp: accepted udp:
AmneziaWG (in-40188-udp) 1 38
VLESS Reality (in-1080-tcp) 34 —

The single TCP session ever recorded from the AmneziaWG inbound was routed to blocked by a user geoip rule, i.e. it was not a successful relay either.

Reality proves Xray itself, the routing rules and outbound egress are healthy. Only the AmneziaWG path fails to deliver TCP.

This is not a network / MTU / path problem. A tcpdump on the UDP listener port shows healthy bidirectional traffic during a browsing attempt:

  • client -> server: 18 packets / 10 845 bytes, including 7 full-size 1264-byte data packets
  • server -> client: 100 packets / 46 620 bytes

So the peer is transmitting real payload and the server is answering. The traffic simply never materialises as TCP sessions inside Xray.

How to reproduce the problem

  1. 3x-ui v3.7.0 in Docker, Xray-core 26.7.28.
  2. Create an AmneziaWG inbound, publish its UDP port, add one client.
  3. Connect a client (reproduced with iOS). Handshake succeeds, panel shows the peer online and traffic counters increment.
  4. Try to browse any website.
  5. Filter access.log by the AmneziaWG inbound tag:
    • accepted udp:...:53 and accepted udp:...:443 (QUIC) entries appear normally
    • accepted tcp: entries do not appear at all

Expected behavior

TCP sessions originating from AmneziaWG peers reach the dispatcher and are routed like traffic from any other inbound, exactly as the UDP sessions already do.

Actual behavior

Only UDP is relayed. DNS (udp/53) and QUIC (udp/443) work, so the peer looks "online" and counters grow, but every TCP connection silently dies before reaching Xray — so no page loads.

Secondary observation: header protection cannot be cleared via reconcile

While narrowing this down I hit a separate defect. Clearing headerProtectionKey (and setting s3/s4 to 0) is rejected forever, because reconcile merges into the live device and merge cannot unset an already-enabled header protection. The warning repeats every 10 s indefinitely and leaves the peer stuck at "connecting" (see logs).

The only way out is to disable and re-enable the inbound, so the device is recreated from scratch instead of merged. Reconcile should probably tear down and rebuild the device when a parameter that cannot be merged changes.

Things already ruled out

  • MTU — tested at default and at 1280. DNS answers that never arrived were 71–264 bytes, far below any MTU. No change in behaviour.
  • Obfuscation parameters — simplified to a classic set (fixed H1–H4 instead of ranges; headerProtectionKey / contentPaddingAddition / I1 / randomTrailers removed; S3=S4=0; keeping Jc/Jmin/Jmax/S1/S2). No change: still UDP-only.
  • Firewall / NAT — DNAT rule present and correct, DOCKER-USER contains only two unrelated fail2ban ipset rules, and the packet capture confirms packets flow both ways.
  • Routing rules — the same ruleset is applied to the Reality inbound, which passes TCP fine.

Relevant logs

# interface starts cleanly, no errors
INFO - amneziawgnet: started embedded interface awg4 for inbound 4

# UDP relays fine - queries go out and answers are written back
INFO  - XRAY: [2783401348] proxy/socks: client UDP connection from udp:127.0.0.1:56509
DEBUG - XRAY: [2783401348] proxy/socks: send packet to udp:8.8.8.8:53 with 43 bytes
DEBUG - XRAY: [2783401348] proxy/socks: writing back UDP response with 198 bytes

# corresponding access.log entries - UDP only, never TCP
accepted udp:8.8.8.8:53      [in-40188-udp -> direct]
accepted udp:<redacted>:443  [in-40188-udp >> direct]   (QUIC)

# secondary defect: header protection cannot be cleared, repeats every 10s forever
WARNING - amneziawgnet: reconcile failed for inbound 4: amneziawgnet: reconfigure inbound 4: IPC error -22: failed to merge with device: S2 must be more then 12 to use headerProtection

Screenshots

No response

3x-ui version

3.7.0

Xray-core version

26.7.28

How did you install 3x-ui?

Docker / Docker Compose

Operating system

Ubuntu, Linux 5.15 x86_64, 1 GB RAM VPS

Which parts of the panel are affected?

No response

Browser (only if it is a UI bug)

No response

Is the panel behind a reverse proxy or CDN?

None

Before submitting

  • I searched existing issues and this bug has not been reported.
  • I am running the latest released version of 3x-ui (or have verified the bug still exists on it).
  • This bug report is written in English.
  • I have redacted any sensitive data (tokens, real domains, client UUIDs).
Originally created by @bharmalej on GitHub (Aug 25, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6323 ### Describe the bug On v3.7.0 with the new native AmneziaWG inbound, a peer completes the handshake and shows online in the panel, DNS resolves through the tunnel, but no website ever loads. The embedded `amneziawgnet` device relays **UDP** into its loopback SOCKS5 bridge correctly, but **TCP essentially never gets relayed**. Hard numbers from Xray's `access.log` on the same instance, same routing rules, same time window: | Inbound | `accepted tcp:` | `accepted udp:` | |---|---|---| | AmneziaWG (`in-40188-udp`) | **1** | 38 | | VLESS Reality (`in-1080-tcp`) | **34** | — | The single TCP session ever recorded from the AmneziaWG inbound was routed to `blocked` by a user geoip rule, i.e. it was not a successful relay either. Reality proves Xray itself, the routing rules and outbound egress are healthy. Only the AmneziaWG path fails to deliver TCP. **This is not a network / MTU / path problem.** A `tcpdump` on the UDP listener port shows healthy bidirectional traffic during a browsing attempt: - client -> server: 18 packets / 10 845 bytes, including 7 full-size 1264-byte data packets - server -> client: 100 packets / 46 620 bytes So the peer is transmitting real payload and the server is answering. The traffic simply never materialises as TCP sessions inside Xray. ### How to reproduce the problem 1. 3x-ui v3.7.0 in Docker, Xray-core 26.7.28. 2. Create an AmneziaWG inbound, publish its UDP port, add one client. 3. Connect a client (reproduced with iOS). Handshake succeeds, panel shows the peer online and traffic counters increment. 4. Try to browse any website. 5. Filter `access.log` by the AmneziaWG inbound tag: - `accepted udp:...:53` and `accepted udp:...:443` (QUIC) entries appear normally - `accepted tcp:` entries do not appear at all ### Expected behavior TCP sessions originating from AmneziaWG peers reach the dispatcher and are routed like traffic from any other inbound, exactly as the UDP sessions already do. ### Actual behavior Only UDP is relayed. DNS (udp/53) and QUIC (udp/443) work, so the peer looks "online" and counters grow, but every TCP connection silently dies before reaching Xray — so no page loads. ### Secondary observation: header protection cannot be cleared via reconcile While narrowing this down I hit a separate defect. Clearing `headerProtectionKey` (and setting `s3`/`s4` to 0) is rejected forever, because reconcile *merges* into the live device and merge cannot unset an already-enabled header protection. The warning repeats every 10 s indefinitely and leaves the peer stuck at "connecting" (see logs). The only way out is to disable and re-enable the inbound, so the device is recreated from scratch instead of merged. Reconcile should probably tear down and rebuild the device when a parameter that cannot be merged changes. ### Things already ruled out - **MTU** — tested at default and at 1280. DNS answers that never arrived were 71–264 bytes, far below any MTU. No change in behaviour. - **Obfuscation parameters** — simplified to a classic set (fixed `H1`–`H4` instead of ranges; `headerProtectionKey` / `contentPaddingAddition` / `I1` / `randomTrailers` removed; `S3`=`S4`=0; keeping `Jc`/`Jmin`/`Jmax`/`S1`/`S2`). No change: still UDP-only. - **Firewall / NAT** — DNAT rule present and correct, `DOCKER-USER` contains only two unrelated fail2ban ipset rules, and the packet capture confirms packets flow both ways. - **Routing rules** — the same ruleset is applied to the Reality inbound, which passes TCP fine. ### Relevant logs ```shell # interface starts cleanly, no errors INFO - amneziawgnet: started embedded interface awg4 for inbound 4 # UDP relays fine - queries go out and answers are written back INFO - XRAY: [2783401348] proxy/socks: client UDP connection from udp:127.0.0.1:56509 DEBUG - XRAY: [2783401348] proxy/socks: send packet to udp:8.8.8.8:53 with 43 bytes DEBUG - XRAY: [2783401348] proxy/socks: writing back UDP response with 198 bytes # corresponding access.log entries - UDP only, never TCP accepted udp:8.8.8.8:53 [in-40188-udp -> direct] accepted udp:<redacted>:443 [in-40188-udp >> direct] (QUIC) # secondary defect: header protection cannot be cleared, repeats every 10s forever WARNING - amneziawgnet: reconcile failed for inbound 4: amneziawgnet: reconfigure inbound 4: IPC error -22: failed to merge with device: S2 must be more then 12 to use headerProtection ``` ### Screenshots _No response_ ### 3x-ui version 3.7.0 ### Xray-core version 26.7.28 ### How did you install 3x-ui? Docker / Docker Compose ### Operating system Ubuntu, Linux 5.15 x86_64, 1 GB RAM VPS ### Which parts of the panel are affected? _No response_ ### Browser (only if it is a UI bug) _No response_ ### Is the panel behind a reverse proxy or CDN? None ### Before submitting - [x] I searched [existing issues](../issues?q=is%3Aissue) and this bug has not been reported. - [x] I am running the latest released version of 3x-ui (or have verified the bug still exists on it). - [x] This bug report is written in English. - [x] I have redacted any sensitive data (tokens, real domains, client UUIDs).
bsakaguchi 2026-10-31 20:38:37 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@github-actions[bot] commented on GitHub (Aug 25, 2026):

Your secondary observation is a real, confirmed bug and I can point at the exact line — clearing headerProtectionKey is impossible on a live interface, and the failed reconcile it causes leaves the device with zero peers, not just an unchanged setting. Your primary claim (TCP never relayed) I could not confirm from the source: I traced the whole TCP path and found no defect that would kill TCP while leaving UDP working, but I also found that every failure branch on that path logs nothing at all, so I need three specific things from you before I can call it. Details for both below.


1. Secondary defect — confirmed

buildUAPIConfig emits the AWG 3.x device lines only when they are non-empty:

// internal/amneziawgnet/device.go:216-222
if opts.HeaderProtectionKey != "" {
	hpHex, err := wireguard.KeyToHex(opts.HeaderProtectionKey)
	...
	fmt.Fprintf(&b, "header_protection_key=%s\n", hpHex)
}

Same gate for content_padding_addition (device.go:223), the four timers, and writeOptionalLine for h1-h4 / i1-i5 (device.go:265-274). On a UAPI set operation an absent line means "leave unchanged" — so clearing the field in the panel emits no line at all and the running device keeps the old key forever.

The project already knows this, for the two bool fields only:

// internal/amneziawgnet/device_test.go:385-388
// Unlike HeaderProtectionKey/ContentPaddingAddition, these two lines
// must always be present -- see DeviceOptions.RandomTrailers's own doc
// comment on why an absent line (instead of an explicit "false") would
// break the reconfigure-in-place diff for a true->false edit.

random_trailers / disable_cookies are therefore emitted unconditionally (device.go:241-242). The string fields were not given the same treatment, and there is no test for the on→off direction: TestEnsureHeaderProtectionKeyChangeReconfiguresInPlace (manager_test.go:250) only covers off→on.

Why it can never rebuild its way out: the rebuild-vs-reconfigure decision keys on MTU and addresses only —

// internal/amneziawgnet/manager.go:258-260
func addressFingerprint(inst amneziawg.Instance) string {
	return fmt.Sprintf("%d|%s", inst.MTU, strings.Join(inst.Address, ","))
}

so an obfuscation-only edit always takes the in-place branch (manager.go:125), and cur.uapiConfig is only updated after a successful IpcSet (manager.go:151-156) — a failing config is retried verbatim every 10s forever. That is exactly the repeat you saw.

There are two variants, and the quiet one is worse:

what you change what happens
clear headerProtectionKey, leave S1-S4 ≥ 12 IpcSet succeeds, header protection stays enabled on the live device, nothing is logged
clear headerProtectionKey and drop S3/S4 below 12 IpcSet fails with IPC error -22 every 10s — your case

The panel permits the second combination: ValidateObfuscation only enforces the ≥12 floor when the key is non-empty (internal/amneziawg/params.go:156-160), while S3/S4 are otherwise allowed down to 0 (params.go:139-143). And the panel always generates a key for a new inbound (params.go:66), so every inbound starts in the state that cannot be undone.

The peer wipe. buildUAPIConfig writes replace_peers=true at device.go:201, the header_protection_key line at device.go:216, and the peer blocks last at device.go:244. The panel's own comment states what replace_peers does:

// internal/amneziawgnet/manager.go:98-101
// amneziawg-go's IpcSet always includes replace_peers=true -- see
// buildUAPIConfig -- and its own implementation of that op is
// device.RemoveAllPeers(), unconditionally, even when the new peer list
// is byte-identical to the old one

So a config that fails at the header-protection stage has already dropped every peer and never re-adds them. That matches your "peer stuck at connecting", and it is why disable/re-enable (which forces the rebuild branch, manager.go:162-167) is the only way out. Inference, flagged as such: I could not read amneziawg-go's source from this checkout, so the exact point at which it validates the merged config — and therefore that the peer lines are never reached — is reasoned from the emit order above plus your log, not read from the library. Note also that your error text names S2 while the panel's own guard names S1-S4 (params.go:159); I can't see which value the library actually rejected, and I'm not going to invent a reason for the mismatch.

Workaround until this is fixed: never edit obfuscation on a live AmneziaWG inbound expecting a field to be cleared. Disable the inbound, save, re-enable it — that rebuilds the device from scratch and is the only path that applies a cleared value.

2. Primary claim — not confirmed, and here is exactly what I ruled out

What I could establish from the source:

  • The SOCKS5 relay itself is proven working by your own UDP log. The UDP path opens its association over a TCP control connection to the same inbound and does the same username/password handshake first (internal/amneziawgnet/relay.go:104-133, socks5Handshake at relay.go:139). Your proxy/socks: client UDP connection from udp:127.0.0.1:56509 line means that TCP connect and the auth succeeded. RelayTCP (relay.go:67-87) dials the identical address with the identical credentials, so it cannot be failing for connectivity or auth reasons. Something upstream of it is.
  • The relay inbound is not TCP-restricted. injectAmneziawgnetSocks emits a stock socks inbound with no network limit and reuses the AmneziaWG inbound's own tag (internal/web/service/xray.go:748-755) — that is why your entries carry in-40188-udp; the tag name has nothing to do with the protocol.
  • The TCP and UDP handlers do not collide. They register on different protocol numbers (forwarder.go:42, udp.go:34) and nothing else in the package calls SetTransportProtocolHandler.
  • Your MTU test does rule out the mechanism I'd otherwise reach for first (the AWG 3.1 per-packet padding overflowing a 1500-byte path — see #6303): at MTU 1280 the wire size cannot overflow, and a TCP SYN/SYN-ACK is small anyway, so it would not explain a missing accepted tcp: line.

What I could not establish, and why your report reads as "silent": the TCP path has no logging on any failure branch. If gVisor's forwarder cannot complete the handshake, the connection is dropped here with no message:

// internal/amneziawgnet/forwarder.go:31-35
ep, err := r.CreateEndpoint(&wq)
if err != nil {
	r.Complete(true)
	return
}

and the three peer-lookup bail-outs in manager.go:178-196 are three bare conn.Close() calls. RelayTCP has exactly two log lines it can ever emit — relay.go:73 and relay.go:78. So "no accepted tcp: and no warning" is consistent with several different failures and distinguishes none of them.

One more gap worth recording for the maintainer: the only end-to-end proof of the TCP relay, TestSocksRelayAgainstRealXray, configures the device with dev.Configure(inst, DeviceOptions{}) (relay_e2e_test.go:188) and a hand-written classic obfuscation set (relay_e2e_test.go:90-93) — no header protection, no content padding, no random trailers, no I1. It therefore never exercises the AWG 3.1 parameter set GenerateObfuscation31 actually produces for every new inbound. It is also gated behind XRAY_E2E_BINARY, so it does not run in CI.

What I need from you

  1. The panel log, filtered to amneziawgnet:, during one browsing attempt. Specifically: does any amneziawgnet: RelayTCP: line appear? Present → the failure is on the SOCKS5 leg; absent → it died inside the gVisor forwarder and never reached the relay. That single bit splits the search space in half.
  2. A run with the device's own verbose log. Restart the panel with AMNEZIAWGNET_DEBUG=1 in the environment (internal/amneziawgnet/manager.go:27-32 — any non-empty value) and paste what appears while a page fails to load. This is opt-in for exactly this kind of question.
  3. One controlled experiment: set RandomTrailers to off on the inbound and retest TCP. The panel defaults it to on for every new inbound (internal/amneziawg/params.go:94), it is documented as needing both ends to agree or packets are "silently dropped by the other" (internal/amneziawgnet/device.go:48-59), and it is the one field your ruled-out list does not mention. It was also isolated as the dominant factor in #6303 on this same code path. Do this after a disable/re-enable cycle, otherwise defect 1 above means your edit may not have reached the running device at all.

Please paste all of it as text — I cannot open images.


Verdict: Confirmed bug (the reconcile/header-protection defect; the TCP-only claim is unresolved — see "Not determined")
Severity: High
Confidence: High for the confirmed defect; Low for the reported TCP-only symptom
Root cause: buildUAPIConfig gates header_protection_key on a non-empty value (internal/amneziawgnet/device.go:216), and the same for content_padding_addition, the four timers and writeOptionalLine's h1-h4/i1-i5 (device.go:223-240, 265-274). An absent UAPI line means "unchanged", so a cleared field can never be applied to a running device. addressFingerprint (manager.go:258-260) covers only MTU and addresses, so an obfuscation-only edit always takes the in-place branch (manager.go:125) and never rebuilds; cur.uapiConfig is updated only after a successful IpcSet (manager.go:151-156), so a rejected config retries verbatim every 10s. Triggering condition: clear headerProtectionKey on a live inbound — silently ineffective if S1-S4 stay >= 12, and a permanent IPC error -22 loop if S3/S4 are also lowered, which ValidateObfuscation allows once the key is empty (internal/amneziawg/params.go:139-143, 156-160). Because replace_peers=true (device.go:201) is emitted before the failing line and before the peer blocks (device.go:244), the failed apply leaves the interface with no peers. Introduced with the feature itself: effcccce feat(amneziawg): add native AmneziaWG protocol support (#6105).
Already fixed: Still present on the default branch (f727d04f, v3.7.0). git log -- internal/amneziawgnet/ returns only effcccce; no follow-up commit touches buildUAPIConfig or addressFingerprint.
Duplicate of: None. Related: #6303 (AmneziaWG throughput collapse, same package, RandomTrailers isolated there as the dominant factor) — different symptom, root cause not shown to be shared, so not a duplicate.
Evidence: device.go:216 if opts.HeaderProtectionKey != "" {; device.go:241-242 fmt.Fprintf(&b, "random_trailers=%t\n", opts.RandomTrailers) emitted unconditionally; device_test.go:385-388 "Unlike HeaderProtectionKey/ContentPaddingAddition, these two lines must always be present ... would break the reconfigure-in-place diff for a true->false edit"; manager.go:98-101 "its own implementation of that op is device.RemoveAllPeers(), unconditionally"; manager.go:151-156; manager.go:258-260; params.go:66 o.HeaderProtectionKey = generateHeaderProtectionKey(); params.go:156-160; manager_test.go:250 and manager_test.go:310 cover only off->on and the low-S rejection, never on->off. For the TCP claim: relay.go:104-133 + relay.go:139 (UDP ASSOCIATE proves TCP connect + auth to the relay inbound already succeed), forwarder.go:31-35 and manager.go:178-196 (silent drops), xray.go:748-755 (relay inbound has no network restriction), relay_e2e_test.go:188 (DeviceOptions{} — the only TCP e2e proof never runs the default AWG 3.1 parameter set, and is gated on XRAY_E2E_BINARY).
Not determined: Whether TCP is genuinely never relayed, and where it dies. The single check that splits it: whether a amneziawgnet: RelayTCP: warning (relay.go:73 or relay.go:78) appears during a failing browsing attempt — absent means the connection died in forwarder.go:31-35 before the relay was ever called. Also not verifiable from this checkout: amneziawg-go's own ordering of config validation versus peer lines (it is not vendored here), so the "peers are wiped" consequence is reasoned from the emit order plus your log, not read from the library.

Suggested fix: Emit the AWG 3.x string fields unconditionally (empty value = clear) exactly as random_trailers/disable_cookies already are at device.go:241-242, or — if amneziawg-go has no UAPI spelling for "clear" — add the AWG 3.x fields that cannot be merged to addressFingerprint (manager.go:258) so clearing one forces the rebuild branch instead of a doomed in-place IpcSet. Either way manager.go:151-153 should not be able to leave a running interface with zero peers after a rejected apply.

@MHSanaei — confirmed High-severity defect above; leaving the issue open for the TCP half.

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:5411733928 --> @github-actions[bot] commented on GitHub (Aug 25, 2026): Your **secondary observation is a real, confirmed bug** and I can point at the exact line — clearing `headerProtectionKey` is impossible on a live interface, and the failed reconcile it causes leaves the device with **zero peers**, not just an unchanged setting. Your **primary claim (TCP never relayed) I could not confirm from the source**: I traced the whole TCP path and found no defect that would kill TCP while leaving UDP working, but I also found that every failure branch on that path logs nothing at all, so I need three specific things from you before I can call it. Details for both below. --- ## 1. Secondary defect — confirmed `buildUAPIConfig` emits the AWG 3.x device lines **only when they are non-empty**: ```go // internal/amneziawgnet/device.go:216-222 if opts.HeaderProtectionKey != "" { hpHex, err := wireguard.KeyToHex(opts.HeaderProtectionKey) ... fmt.Fprintf(&b, "header_protection_key=%s\n", hpHex) } ``` Same gate for `content_padding_addition` (`device.go:223`), the four timers, and `writeOptionalLine` for `h1`-`h4` / `i1`-`i5` (`device.go:265-274`). On a UAPI *set* operation an absent line means "leave unchanged" — so clearing the field in the panel emits **no line at all** and the running device keeps the old key forever. The project already knows this, for the two `bool` fields only: ```go // internal/amneziawgnet/device_test.go:385-388 // Unlike HeaderProtectionKey/ContentPaddingAddition, these two lines // must always be present -- see DeviceOptions.RandomTrailers's own doc // comment on why an absent line (instead of an explicit "false") would // break the reconfigure-in-place diff for a true->false edit. ``` `random_trailers` / `disable_cookies` are therefore emitted unconditionally (`device.go:241-242`). The string fields were not given the same treatment, and there is no test for the on→off direction: `TestEnsureHeaderProtectionKeyChangeReconfiguresInPlace` (`manager_test.go:250`) only covers off→on. Why it can never rebuild its way out: the rebuild-vs-reconfigure decision keys on MTU and addresses only — ```go // internal/amneziawgnet/manager.go:258-260 func addressFingerprint(inst amneziawg.Instance) string { return fmt.Sprintf("%d|%s", inst.MTU, strings.Join(inst.Address, ",")) } ``` so an obfuscation-only edit always takes the in-place branch (`manager.go:125`), and `cur.uapiConfig` is only updated *after* a successful `IpcSet` (`manager.go:151-156`) — a failing config is retried verbatim every 10s forever. That is exactly the repeat you saw. There are two variants, and the quiet one is worse: | what you change | what happens | |---|---| | clear `headerProtectionKey`, leave `S1`-`S4` ≥ 12 | `IpcSet` **succeeds**, header protection stays enabled on the live device, **nothing is logged** | | clear `headerProtectionKey` **and** drop `S3`/`S4` below 12 | `IpcSet` fails with `IPC error -22` every 10s — your case | The panel permits the second combination: `ValidateObfuscation` only enforces the ≥12 floor when the key is non-empty (`internal/amneziawg/params.go:156-160`), while `S3`/`S4` are otherwise allowed down to 0 (`params.go:139-143`). And the panel *always* generates a key for a new inbound (`params.go:66`), so every inbound starts in the state that cannot be undone. **The peer wipe.** `buildUAPIConfig` writes `replace_peers=true` at `device.go:201`, the `header_protection_key` line at `device.go:216`, and the peer blocks last at `device.go:244`. The panel's own comment states what `replace_peers` does: ```go // internal/amneziawgnet/manager.go:98-101 // amneziawg-go's IpcSet always includes replace_peers=true -- see // buildUAPIConfig -- and its own implementation of that op is // device.RemoveAllPeers(), unconditionally, even when the new peer list // is byte-identical to the old one ``` So a config that fails at the header-protection stage has already dropped every peer and never re-adds them. That matches your "peer stuck at connecting", and it is why disable/re-enable (which forces the rebuild branch, `manager.go:162-167`) is the only way out. *Inference, flagged as such:* I could not read `amneziawg-go`'s source from this checkout, so the exact point at which it validates the merged config — and therefore that the peer lines are never reached — is reasoned from the emit order above plus your log, not read from the library. Note also that your error text names `S2` while the panel's own guard names `S1`-`S4` (`params.go:159`); I can't see which value the library actually rejected, and I'm not going to invent a reason for the mismatch. **Workaround until this is fixed:** never edit obfuscation on a live AmneziaWG inbound expecting a field to be *cleared*. Disable the inbound, save, re-enable it — that rebuilds the device from scratch and is the only path that applies a cleared value. ## 2. Primary claim — not confirmed, and here is exactly what I ruled out What I could establish from the source: - **The SOCKS5 relay itself is proven working by your own UDP log.** The UDP path opens its association over a **TCP** control connection to the same inbound and does the same username/password handshake first (`internal/amneziawgnet/relay.go:104-133`, `socks5Handshake` at `relay.go:139`). Your `proxy/socks: client UDP connection from udp:127.0.0.1:56509` line means that TCP connect **and** the auth succeeded. `RelayTCP` (`relay.go:67-87`) dials the identical address with the identical credentials, so it cannot be failing for connectivity or auth reasons. Something upstream of it is. - **The relay inbound is not TCP-restricted.** `injectAmneziawgnetSocks` emits a stock socks inbound with no `network` limit and reuses the AmneziaWG inbound's own tag (`internal/web/service/xray.go:748-755`) — that is why your entries carry `in-40188-udp`; the tag name has nothing to do with the protocol. - **The TCP and UDP handlers do not collide.** They register on different protocol numbers (`forwarder.go:42`, `udp.go:34`) and nothing else in the package calls `SetTransportProtocolHandler`. - **Your MTU test does rule out the mechanism I'd otherwise reach for first** (the AWG 3.1 per-packet padding overflowing a 1500-byte path — see #6303): at MTU 1280 the wire size cannot overflow, and a TCP SYN/SYN-ACK is small anyway, so it would not explain a missing `accepted tcp:` line. What I could **not** establish, and why your report reads as "silent": the TCP path has **no logging on any failure branch**. If gVisor's forwarder cannot complete the handshake, the connection is dropped here with no message: ```go // internal/amneziawgnet/forwarder.go:31-35 ep, err := r.CreateEndpoint(&wq) if err != nil { r.Complete(true) return } ``` and the three peer-lookup bail-outs in `manager.go:178-196` are three bare `conn.Close()` calls. `RelayTCP` has exactly two log lines it can ever emit — `relay.go:73` and `relay.go:78`. So "no `accepted tcp:` and no warning" is consistent with several different failures and distinguishes none of them. One more gap worth recording for the maintainer: the only end-to-end proof of the TCP relay, `TestSocksRelayAgainstRealXray`, configures the device with `dev.Configure(inst, DeviceOptions{})` (`relay_e2e_test.go:188`) and a hand-written classic obfuscation set (`relay_e2e_test.go:90-93`) — no header protection, no content padding, no random trailers, no `I1`. It therefore never exercises the AWG 3.1 parameter set `GenerateObfuscation31` actually produces for every new inbound. It is also gated behind `XRAY_E2E_BINARY`, so it does not run in CI. ### What I need from you 1. **The panel log, filtered to `amneziawgnet:`, during one browsing attempt.** Specifically: does any `amneziawgnet: RelayTCP:` line appear? Present → the failure is on the SOCKS5 leg; absent → it died inside the gVisor forwarder and never reached the relay. That single bit splits the search space in half. 2. **A run with the device's own verbose log.** Restart the panel with `AMNEZIAWGNET_DEBUG=1` in the environment (`internal/amneziawgnet/manager.go:27-32` — any non-empty value) and paste what appears while a page fails to load. This is opt-in for exactly this kind of question. 3. **One controlled experiment:** set `RandomTrailers` to off on the inbound and retest TCP. The panel defaults it to **on** for every new inbound (`internal/amneziawg/params.go:94`), it is documented as needing both ends to agree or packets are "silently dropped by the other" (`internal/amneziawgnet/device.go:48-59`), and it is the one field your ruled-out list does not mention. It was also isolated as the dominant factor in #6303 on this same code path. Do this **after** a disable/re-enable cycle, otherwise defect 1 above means your edit may not have reached the running device at all. Please paste all of it as text — I cannot open images. --- Verdict: Confirmed bug (the reconcile/header-protection defect; the TCP-only claim is unresolved — see "Not determined") Severity: High Confidence: High for the confirmed defect; Low for the reported TCP-only symptom Root cause: `buildUAPIConfig` gates `header_protection_key` on a non-empty value (`internal/amneziawgnet/device.go:216`), and the same for `content_padding_addition`, the four timers and `writeOptionalLine`'s `h1`-`h4`/`i1`-`i5` (`device.go:223-240, 265-274`). An absent UAPI line means "unchanged", so a cleared field can never be applied to a running device. `addressFingerprint` (`manager.go:258-260`) covers only MTU and addresses, so an obfuscation-only edit always takes the in-place branch (`manager.go:125`) and never rebuilds; `cur.uapiConfig` is updated only after a successful `IpcSet` (`manager.go:151-156`), so a rejected config retries verbatim every 10s. Triggering condition: clear `headerProtectionKey` on a live inbound — silently ineffective if `S1`-`S4` stay >= 12, and a permanent `IPC error -22` loop if `S3`/`S4` are also lowered, which `ValidateObfuscation` allows once the key is empty (`internal/amneziawg/params.go:139-143, 156-160`). Because `replace_peers=true` (`device.go:201`) is emitted before the failing line and before the peer blocks (`device.go:244`), the failed apply leaves the interface with no peers. Introduced with the feature itself: effcccce `feat(amneziawg): add native AmneziaWG protocol support (#6105)`. Already fixed: Still present on the default branch (f727d04f, v3.7.0). `git log -- internal/amneziawgnet/` returns only effcccce; no follow-up commit touches `buildUAPIConfig` or `addressFingerprint`. Duplicate of: None. Related: #6303 (AmneziaWG throughput collapse, same package, `RandomTrailers` isolated there as the dominant factor) — different symptom, root cause not shown to be shared, so not a duplicate. Evidence: `device.go:216` `if opts.HeaderProtectionKey != "" {`; `device.go:241-242` `fmt.Fprintf(&b, "random_trailers=%t\n", opts.RandomTrailers)` emitted unconditionally; `device_test.go:385-388` "Unlike HeaderProtectionKey/ContentPaddingAddition, these two lines must always be present ... would break the reconfigure-in-place diff for a true->false edit"; `manager.go:98-101` "its own implementation of that op is device.RemoveAllPeers(), unconditionally"; `manager.go:151-156`; `manager.go:258-260`; `params.go:66` `o.HeaderProtectionKey = generateHeaderProtectionKey()`; `params.go:156-160`; `manager_test.go:250` and `manager_test.go:310` cover only off->on and the low-S rejection, never on->off. For the TCP claim: `relay.go:104-133` + `relay.go:139` (UDP ASSOCIATE proves TCP connect + auth to the relay inbound already succeed), `forwarder.go:31-35` and `manager.go:178-196` (silent drops), `xray.go:748-755` (relay inbound has no network restriction), `relay_e2e_test.go:188` (`DeviceOptions{}` — the only TCP e2e proof never runs the default AWG 3.1 parameter set, and is gated on `XRAY_E2E_BINARY`). Not determined: Whether TCP is genuinely never relayed, and where it dies. The single check that splits it: whether a `amneziawgnet: RelayTCP:` warning (`relay.go:73` or `relay.go:78`) appears during a failing browsing attempt — absent means the connection died in `forwarder.go:31-35` before the relay was ever called. Also not verifiable from this checkout: `amneziawg-go`'s own ordering of config validation versus peer lines (it is not vendored here), so the "peers are wiped" consequence is reasoned from the emit order plus your log, not read from the library. Suggested fix: Emit the AWG 3.x string fields unconditionally (empty value = clear) exactly as `random_trailers`/`disable_cookies` already are at `device.go:241-242`, or — if `amneziawg-go` has no UAPI spelling for "clear" — add the AWG 3.x fields that cannot be merged to `addressFingerprint` (`manager.go:258`) so clearing one forces the rebuild branch instead of a doomed in-place `IpcSet`. Either way `manager.go:151-153` should not be able to leave a running interface with zero peers after a rejected apply. @MHSanaei — confirmed High-severity defect above; leaving the issue open for the TCP half. *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Author
Owner

@bharmalej commented on GitHub (Aug 25, 2026):

Thanks — that analysis was extremely useful, and it turned out my original framing was wrong. AMNEZIAWGNET_DEBUG=1 shows this is not a TCP-specific defect at all. The session itself cannot be maintained; TCP is simply the first thing to die because it needs more than one round trip.

I ran two controlled tests on the same build, both with debug enabled. All three of your questions are answered below.

Answer to Q1 — no RelayTCP: lines, in either run

Zero across both runs. But the reason is upstream of the forwarder: there is no live session to deliver anything over, so nothing ever reaches RelayTCP.

Answer to Q2 — the device log, and what it shows

This is the actual signature (run B, trimmed):

17:49:45 Received message with unknown type          (x6)
17:49:45 peer(<redacted>) - Received handshake initiation
17:49:45 peer(<redacted>) - Sending handshake response
17:50:00 peer(<redacted>) - Retrying handshake because we stopped hearing back after 15 seconds
17:50:00 peer(<redacted>) - Sending handshake initiation
17:50:05 peer(<redacted>) - Handshake did not complete after 5 seconds, retrying (try 2)
17:50:05 peer(<redacted>) - Sending handshake initiation
17:50:10 peer(<redacted>) - Handshake did not complete after 5 seconds, retrying (try 3)
...continues until the client gives up

Exactly one handshake ever completes, and it is always the client-initiated one. Every subsequent handshake — all of them server-initiated rekeys — fails; the client never answers. The session dies ~15-20 s after it is established and can never be re-established from the server side.

That explains the UDP/TCP asymmetry I originally reported, and it is not a TCP bug:

  • UDP (DNS) is one packet out, one packet back. It fits inside the brief window while the session is alive. Every UDP entry in access.log is timestamped within the same second as the successful handshake — 10 of them at 17:44:19 in run A, 9 at 17:49:45 in run B, then nothing.
  • TCP needs SYN -> SYN-ACK -> ACK plus a sustained bidirectional session. By the time the SYN-ACK has to go back, the session is already gone, so the connection never completes and accepted tcp: is never logged.

Answer to Q3 — RandomTrailers off changes nothing

Tested, with the disable/re-enable cycle you specified so defect 1 could not mask the edit. Both runs on the same build, same client, same browsing steps:

device event run A — default AWG 3.1 run B — classic params
Received handshake initiation 1 1
Sending handshake response 1 1
Sending handshake initiation (server) 55 11
Handshake did not complete 53 10
Received message with unknown type 4 6
Retrying ... stopped hearing back 4 2
RelayTCP: lines 0 0
accepted tcp: 0 0
accepted udp: 10 9

Run A was the untouched parameter set the panel generates for a new inbound (GenerateObfuscation31): headerProtectionKey set, randomTrailers=true, contentPaddingAddition=14-44, i1=<r 231>, h1-h4 as ranges, s1=110 s2=34 s3=23 s4=14, no MTU override.

Run B: fixed h1-h4, randomTrailers / contentPaddingAddition / i1 removed, s3=s4=0, and the five AWG 3.1 timers pinned to classic WireGuard values (rekeyAfterTime=120, rejectAfterTime=180, rekeyTimeout=5, keepaliveTimeout=10, maxHandshakeAttempts=18). Client profile re-imported both times.

The signature is identical. So the obfuscation parameter set is not the cause — this rules out RandomTrailers, the h1-h4 ranges, header protection, content padding, I1, S3/S4, and the randomized timers, all at once.

Two more things worth recording

1. Header protection may be impossible to disable at all, not just impossible to clear on a live device. In run B the stored settings have no headerProtectionKey at all (the JSON key is absent, not empty), and content padding addition is correctly not emitted — yet the device still logs:

17:48:24 UAPI: Updating header protection key

on a freshly rebuilt device. Per your reading of device.go:216 that line is only written when the value is non-empty, which would mean the panel supplies a generated key even when storage has none — consistent with params.go:66. Flagged as inference: I cannot read amneziawg-go from here, so I cannot rule out that the library logs that line for a clear operation too.

2. The S2 in the error text is misleading — reproduced. Clearing the key with s2=34 (well above the 12 floor) and only s3/s4 at 0 still produces:

17:47:54 amneziawgnet: reconcile failed for inbound 5: ... IPC error -22:
failed to merge with device: S2 must be more then 12 to use headerProtection

So the message names S2 while the values actually below the floor are S3/S4. Whatever the fix, that string is going to misdirect anyone who hits it.

Environment

Unchanged from the original report: 3x-ui v3.7.0, Xray-core 26.7.28, Docker, Linux 5.15 x86_64. Client is iOS.

The inbound is still up on my node with AMNEZIAWGNET_DEBUG=1 enabled, so I can run further experiments on request — just say what to change and what to capture.

<!-- gh-comment-id:5412288135 --> @bharmalej commented on GitHub (Aug 25, 2026): Thanks — that analysis was extremely useful, and it turned out my original framing was wrong. `AMNEZIAWGNET_DEBUG=1` shows this is **not a TCP-specific defect at all**. The session itself cannot be maintained; TCP is simply the first thing to die because it needs more than one round trip. I ran two controlled tests on the same build, both with debug enabled. All three of your questions are answered below. ## Answer to Q1 — no `RelayTCP:` lines, in either run Zero across both runs. But the reason is upstream of the forwarder: there is no live session to deliver anything over, so nothing ever reaches `RelayTCP`. ## Answer to Q2 — the device log, and what it shows This is the actual signature (run B, trimmed): ``` 17:49:45 Received message with unknown type (x6) 17:49:45 peer(<redacted>) - Received handshake initiation 17:49:45 peer(<redacted>) - Sending handshake response 17:50:00 peer(<redacted>) - Retrying handshake because we stopped hearing back after 15 seconds 17:50:00 peer(<redacted>) - Sending handshake initiation 17:50:05 peer(<redacted>) - Handshake did not complete after 5 seconds, retrying (try 2) 17:50:05 peer(<redacted>) - Sending handshake initiation 17:50:10 peer(<redacted>) - Handshake did not complete after 5 seconds, retrying (try 3) ...continues until the client gives up ``` **Exactly one handshake ever completes, and it is always the client-initiated one.** Every subsequent handshake — all of them server-initiated rekeys — fails; the client never answers. The session dies ~15-20 s after it is established and can never be re-established from the server side. That explains the UDP/TCP asymmetry I originally reported, and it is not a TCP bug: - **UDP (DNS)** is one packet out, one packet back. It fits inside the brief window while the session is alive. Every UDP entry in `access.log` is timestamped within the *same second* as the successful handshake — 10 of them at `17:44:19` in run A, 9 at `17:49:45` in run B, then nothing. - **TCP** needs SYN -> SYN-ACK -> ACK plus a sustained bidirectional session. By the time the SYN-ACK has to go back, the session is already gone, so the connection never completes and `accepted tcp:` is never logged. ## Answer to Q3 — `RandomTrailers` off changes nothing Tested, with the disable/re-enable cycle you specified so defect 1 could not mask the edit. Both runs on the same build, same client, same browsing steps: | device event | run A — default AWG 3.1 | run B — classic params | |---|---|---| | `Received handshake initiation` | 1 | 1 | | `Sending handshake response` | 1 | 1 | | `Sending handshake initiation` (server) | 55 | 11 | | `Handshake did not complete` | 53 | 10 | | `Received message with unknown type` | 4 | 6 | | `Retrying ... stopped hearing back` | 4 | 2 | | `RelayTCP:` lines | 0 | 0 | | **`accepted tcp:`** | **0** | **0** | | `accepted udp:` | 10 | 9 | Run A was the untouched parameter set the panel generates for a new inbound (`GenerateObfuscation31`): `headerProtectionKey` set, `randomTrailers=true`, `contentPaddingAddition=14-44`, `i1=<r 231>`, `h1`-`h4` as ranges, `s1=110 s2=34 s3=23 s4=14`, no MTU override. Run B: fixed `h1`-`h4`, `randomTrailers` / `contentPaddingAddition` / `i1` removed, `s3=s4=0`, and the five AWG 3.1 timers pinned to classic WireGuard values (`rekeyAfterTime=120`, `rejectAfterTime=180`, `rekeyTimeout=5`, `keepaliveTimeout=10`, `maxHandshakeAttempts=18`). Client profile re-imported both times. **The signature is identical.** So the obfuscation parameter set is not the cause — this rules out `RandomTrailers`, the `h1`-`h4` ranges, header protection, content padding, `I1`, `S3`/`S4`, and the randomized timers, all at once. ## Two more things worth recording **1. Header protection may be impossible to disable at all, not just impossible to clear on a live device.** In run B the stored settings have no `headerProtectionKey` at all (the JSON key is absent, not empty), and `content padding addition` is correctly *not* emitted — yet the device still logs: ``` 17:48:24 UAPI: Updating header protection key ``` on a freshly rebuilt device. Per your reading of `device.go:216` that line is only written when the value is non-empty, which would mean the panel supplies a generated key even when storage has none — consistent with `params.go:66`. *Flagged as inference:* I cannot read `amneziawg-go` from here, so I cannot rule out that the library logs that line for a clear operation too. **2. The `S2` in the error text is misleading — reproduced.** Clearing the key with `s2=34` (well above the 12 floor) and only `s3`/`s4` at 0 still produces: ``` 17:47:54 amneziawgnet: reconcile failed for inbound 5: ... IPC error -22: failed to merge with device: S2 must be more then 12 to use headerProtection ``` So the message names `S2` while the values actually below the floor are `S3`/`S4`. Whatever the fix, that string is going to misdirect anyone who hits it. ## Environment Unchanged from the original report: 3x-ui v3.7.0, Xray-core 26.7.28, Docker, Linux 5.15 x86_64. Client is iOS. The inbound is still up on my node with `AMNEZIAWGNET_DEBUG=1` enabled, so I can run further experiments on request — just say what to change and what to capture.
Author
Owner

@github-actions[bot] commented on GitHub (Aug 25, 2026):

Your refined framing holds up against the source, and it does more than that: I can now confirm from the code that run B really did reach the device with the parameters you set, so ruling out the obfuscation set is a sound conclusion and not an artefact of defect 1. What your data also shows is something no code in internal/amneziawgnet can cause — the device stops receiving from the peer entirely, including stateless handshake initiations. Below: what is now settled, two corrections to your "worth recording" items, and the one measurement that splits the two remaining mechanisms.


1. What your data settles

The TCP-specific defect is off the table. Zero RelayTCP: lines plus zero accepted tcp: is exactly what a dead session produces, and nothing in the package has a TCP-only path — this matches what I could establish last time from forwarder.go:31-35 / xray.go:748-755. Your explanation of the UDP/TCP asymmetry is the one the code supports.

Run B's parameters genuinely reached the device. Every step from storage to the UAPI string is a verbatim copy, with nothing filled in:

  • ServerSettings.Obfuscation() is a pure field-for-field copy of the parsed JSON (internal/amneziawg/types.go:220-236), consumed by InstanceFromInbound at internal/amneziawg/instance.go:70.
  • All three Ensure call sites map those fields straight across — the reconcile job (internal/web/job/amneziawg_job.go:41-52) and both CRUD paths (internal/web/runtime/local.go:65-75 and :198-208) are byte-identical in what they set, so no two paths can fight each other.
  • normalizeAmneziaWGSettings only trims and canonicalizes on save; it never supplies a missing value:
    // internal/web/service/inbound_amneziawg.go:201-208
    parsed.Server.HeaderProtectionKey = strings.TrimSpace(parsed.Server.HeaderProtectionKey)
    for _, f := range []*string{
        &parsed.Server.ContentPaddingAddition, &parsed.Server.RekeyAfterTime,
        ...
    } {
        *f = amneziawg.CanonicalizeUintRange(*f)
    }
    

The 10s reconcile is not what kills your session — and your own log proves it. Retrying handshake because we stopped hearing back after 15 seconds at 17:50:00 is that peer object's own newHandshake timer, armed when the server sent data at 17:49:45. The reconcile job runs @every 10s (internal/web/web.go:295), and any re-apply goes through replace_peers=true (internal/amneziawgnet/device.go:201), whose implementation the package documents as device.RemoveAllPeers() (manager.go:96-101) — that would destroy the peer and its timers. A timer surviving 15s means at least one full tick passed with the peer intact, i.e. the byte-identical no-op branch (manager.go:137-149) is working as designed. So peers are not being wiped under you.

2. Two corrections

The panel is not supplying a header protection key in run B. params.go:66 lives inside GenerateObfuscation31, whose only server-side caller is defaultAmneziaWGServer (internal/web/service/inbound_amneziawg.go:114-115), and normalizeAmneziaWGSettings calls that only when the settings blob is empty / null / {} or has no server block at all (inbound_amneziawg.go:171-200). Your inbound has a server block, so that path cannot run; opts.HeaderProtectionKey is then "" and device.go:216 emits no line. So UAPI: Updating header protection key on a freshly rebuilt device is being written by amneziawg-go itself, not prompted by anything the panel sent. I cannot read that library from this checkout (not vendored), so I can neither confirm nor rule out that it logs the line for a clear/no-op — recording it as unresolved rather than guessing.

The S2 wording is upstream. S2 must be more then 12 to use headerProtection (including the "more then" typo) appears nowhere in this repository — grep returns nothing. It is amneziawg-go's own message, so that misdirection can only be corrected upstream. The panel's own guard does name the right index (internal/amneziawg/params.go:156-161).

3. The part that cannot come from this package

Three facts together:

  1. stopped hearing back after 15 seconds only fires when nothing authenticated arrives from the peer.
  2. A fresh handshake initiation is stateless — the server parses and logs it regardless of session state. You see exactly one in a whole run, while your capture shows the client still transmitting.
  3. The panel installs no packet filter or DNAT for AmneziaWG. The only external command in the entire package is ip -6 addr for per-peer IPv6 aliases (internal/amneziawgnet/v6alias.go:106), and port-forwarding is deliberately userspace listeners rather than DNAT — "this path's replacement for the retired kernel-module architecture's PostUp/PostDown iptables DNAT rules: there's no real OS network interface here for DNAT to rewrite packets on" (portfwd.go:6-8). The UDP socket is amneziawg-go's own awgconn.NewDefaultBind() (device.go:139), never rebound.

So the client's packets are either dropped before they reach the socket, or the device's own receive path stopped. Everything else you have measured is downstream of that one bit.

4. What to capture next

Please run these during one failing browsing attempt, on the same node:

  1. ss -uanp | grep <your UDP port> inside the container, sampled ~3 times a few seconds apart. A climbing Recv-Q means packets reach the socket and the device is not draining them (server-side, and squarely a bug). Recv-Q pinned at 0 while the client is transmitting means they never arrive at the socket at all. This is the bit that decides everything else.
  2. iptables -L -n -v inside the container, plus the two rules you saw in DOCKER-USER on the host, with their packet counters, taken during the failure. This matters more than it looks: the image's bundled fail2ban jail bans UDP on every port except SSH and the panel port —
    # DockerEntrypoint.sh:55-56
    actionban = <iptables> -I f2b-<name> 1 -s <ip> -p tcp -m multiport ! --dports <exemptports> -j <blocktype>
                <iptables> -I f2b-<name> 1 -s <ip> -p udp -m multiport ! --dports <exemptports> -j <blocktype>
    
    with maxretry=1, findtime=32, bantime=30m (DockerEntrypoint.sh:18-20), enabled by default in the shipped compose file (XUI_ENABLE_FAIL2BAN: "true"). A DROP there is invisible to tcpdump, which taps before the filter chains — which is exactly the shape of "packets on the wire, nothing in the device". Also please paste cat /var/log/x-ui/3xipl-banned.log and say whether your client's public IP appears there.
  3. nstat -az | grep -i Udp (or netstat -su) before and after the failure, so we can see whether receive buffer errors / packet receive errors move.
  4. One run from a second client on a different public IP (a desktop AmneziaWG client is fine), same inbound, same moment. Identical signature ⇒ server-side; that client working ⇒ per-source-IP filtering somewhere on the path.

Text only, please — I cannot open images.


Verdict: Confirmed bug (the reconcile/header-protection defect, unchanged from my previous comment; the session-death symptom is still unresolved — see "Not determined")
Severity: High
Confidence: High for the confirmed defect and for the rulings-out in §1-§2; Low for the cause of the session death
Root cause: Unchanged for the confirmed defect: buildUAPIConfig gates header_protection_key on a non-empty value (internal/amneziawgnet/device.go:216), an absent UAPI line means "unchanged", and addressFingerprint (manager.go:258-260) covers only MTU/addresses so an obfuscation-only edit never rebuilds. Introduced with the feature itself, effcccce. For the session death: no root cause in internal/amneziawgnet — the package installs no netfilter rule (only ip -6 addr, v6alias.go:106), does not rebind the device socket (device.go:139), and the reporter's own 15s newHandshake timer at 17:50:00 rules out a replace_peers peer wipe by the 10s job (web.go:295, manager.go:96-101, device.go:201).
Already fixed: Still present on the default branch (f727d04f, v3.7.0); git log -- internal/amneziawgnet/ still returns only effcccce.
Duplicate of: None. Related: #6303 (same package, throughput collapse) — this thread's run B now rules RandomTrailers out for this symptom, so still not a duplicate.
Evidence: internal/amneziawg/types.go:220-236 and instance.go:70 (pure copy, no defaults); internal/web/job/amneziawg_job.go:41-52, internal/web/runtime/local.go:65-75, :198-208 (all three call sites identical); internal/web/service/inbound_amneziawg.go:171-200 (defaultAmneziaWGServer/GenerateObfuscation31 unreachable once a server block exists) and :201-208 (trim/canonicalize only); internal/amneziawgnet/device.go:216 (if opts.HeaderProtectionKey != "" {); manager.go:96-101 ("its own implementation of that op is device.RemoveAllPeers(), unconditionally"); manager.go:137-149 (no-op branch); web.go:295 (cadenceAmneziaWG = "@every 10s"); portfwd.go:6-8 (userspace listeners, explicitly not DNAT); v6alias.go:106 (the package's only exec); DockerEntrypoint.sh:55-56 (ban action covers UDP on all non-exempt ports) and :18-20 (maxretry=1, findtime=32, bantime=30m); repo-wide grep for more then 12 returns nothing.
Not determined: Why the device stops receiving authenticated packets from the peer roughly a second after the handshake, while the client is still transmitting. The single check that splits it: Recv-Q on the device's UDP socket during the failure (item 1 above) — climbing means the receive path stalled server-side, zero means the packets are being dropped before the socket. Also still unverifiable here: amneziawg-go's own logging and validation behaviour, since the module is not vendored in this checkout.

Suggested fix: Unchanged and scoped to the confirmed defect only: emit the AWG 3.x string fields unconditionally (empty = clear) exactly as random_trailers/disable_cookies already are at device.go:241-242, or add the fields that cannot be merged to addressFingerprint (manager.go:258) so clearing one forces the rebuild branch instead of a doomed in-place IpcSet.

I have retitled the issue to match what you now describe; the old title was "[Bug]: AmneziaWG inbound relays UDP but never TCP — peers connect and resolve DNS, but no TCP session reaches Xray". Keeping "clarification needed" on until item 1 comes back.

@MHSanaei — no change to the confirmed defect above; this update only rules the AWG 3.1 parameter set out as the cause of the reporter's connection failure.

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:5412500333 --> @github-actions[bot] commented on GitHub (Aug 25, 2026): Your refined framing holds up against the source, and it does more than that: I can now confirm from the code that **run B really did reach the device with the parameters you set**, so ruling out the obfuscation set is a sound conclusion and not an artefact of defect 1. What your data also shows is something no code in `internal/amneziawgnet` can cause — the device stops *receiving* from the peer entirely, including stateless handshake initiations. Below: what is now settled, two corrections to your "worth recording" items, and the one measurement that splits the two remaining mechanisms. --- ## 1. What your data settles **The TCP-specific defect is off the table.** Zero `RelayTCP:` lines plus zero `accepted tcp:` is exactly what a dead session produces, and nothing in the package has a TCP-only path — this matches what I could establish last time from `forwarder.go:31-35` / `xray.go:748-755`. Your explanation of the UDP/TCP asymmetry is the one the code supports. **Run B's parameters genuinely reached the device.** Every step from storage to the UAPI string is a verbatim copy, with nothing filled in: - `ServerSettings.Obfuscation()` is a pure field-for-field copy of the parsed JSON (`internal/amneziawg/types.go:220-236`), consumed by `InstanceFromInbound` at `internal/amneziawg/instance.go:70`. - All three `Ensure` call sites map those fields straight across — the reconcile job (`internal/web/job/amneziawg_job.go:41-52`) and both CRUD paths (`internal/web/runtime/local.go:65-75` and `:198-208`) are byte-identical in what they set, so no two paths can fight each other. - `normalizeAmneziaWGSettings` only trims and canonicalizes on save; it never supplies a missing value: ```go // internal/web/service/inbound_amneziawg.go:201-208 parsed.Server.HeaderProtectionKey = strings.TrimSpace(parsed.Server.HeaderProtectionKey) for _, f := range []*string{ &parsed.Server.ContentPaddingAddition, &parsed.Server.RekeyAfterTime, ... } { *f = amneziawg.CanonicalizeUintRange(*f) } ``` **The 10s reconcile is not what kills your session** — and your own log proves it. `Retrying handshake because we stopped hearing back after 15 seconds` at `17:50:00` is that peer object's own `newHandshake` timer, armed when the server sent data at `17:49:45`. The reconcile job runs `@every 10s` (`internal/web/web.go:295`), and any re-apply goes through `replace_peers=true` (`internal/amneziawgnet/device.go:201`), whose implementation the package documents as `device.RemoveAllPeers()` (`manager.go:96-101`) — that would destroy the peer and its timers. A timer surviving 15s means at least one full tick passed with the peer intact, i.e. the byte-identical no-op branch (`manager.go:137-149`) is working as designed. So peers are *not* being wiped under you. ## 2. Two corrections **The panel is not supplying a header protection key in run B.** `params.go:66` lives inside `GenerateObfuscation31`, whose only server-side caller is `defaultAmneziaWGServer` (`internal/web/service/inbound_amneziawg.go:114-115`), and `normalizeAmneziaWGSettings` calls that only when the settings blob is empty / `null` / `{}` or has no `server` block at all (`inbound_amneziawg.go:171-200`). Your inbound has a server block, so that path cannot run; `opts.HeaderProtectionKey` is then `""` and `device.go:216` emits no line. So `UAPI: Updating header protection key` on a freshly rebuilt device is being written by amneziawg-go itself, not prompted by anything the panel sent. I cannot read that library from this checkout (not vendored), so I can neither confirm nor rule out that it logs the line for a clear/no-op — recording it as unresolved rather than guessing. **The `S2` wording is upstream.** `S2 must be more then 12 to use headerProtection` (including the "more then" typo) appears nowhere in this repository — grep returns nothing. It is amneziawg-go's own message, so that misdirection can only be corrected upstream. The panel's own guard does name the right index (`internal/amneziawg/params.go:156-161`). ## 3. The part that cannot come from this package Three facts together: 1. `stopped hearing back after 15 seconds` only fires when nothing *authenticated* arrives from the peer. 2. A fresh handshake initiation is stateless — the server parses and logs it regardless of session state. You see exactly **one** in a whole run, while your capture shows the client still transmitting. 3. The panel installs no packet filter or DNAT for AmneziaWG. The only external command in the entire package is `ip -6 addr` for per-peer IPv6 aliases (`internal/amneziawgnet/v6alias.go:106`), and port-forwarding is deliberately userspace listeners rather than DNAT — *"this path's replacement for the retired kernel-module architecture's PostUp/PostDown iptables DNAT rules: there's no real OS network interface here for DNAT to rewrite packets on"* (`portfwd.go:6-8`). The UDP socket is amneziawg-go's own `awgconn.NewDefaultBind()` (`device.go:139`), never rebound. So the client's packets are either **dropped before they reach the socket**, or **the device's own receive path stopped**. Everything else you have measured is downstream of that one bit. ## 4. What to capture next Please run these during one failing browsing attempt, on the same node: 1. **`ss -uanp | grep <your UDP port>` inside the container, sampled ~3 times a few seconds apart.** A climbing `Recv-Q` means packets reach the socket and the device is not draining them (server-side, and squarely a bug). `Recv-Q` pinned at 0 while the client is transmitting means they never arrive at the socket at all. **This is the bit that decides everything else.** 2. **`iptables -L -n -v` inside the container, plus the two rules you saw in `DOCKER-USER` on the host, with their packet counters, taken during the failure.** This matters more than it looks: the image's bundled fail2ban jail bans **UDP on every port** except SSH and the panel port — ``` # DockerEntrypoint.sh:55-56 actionban = <iptables> -I f2b-<name> 1 -s <ip> -p tcp -m multiport ! --dports <exemptports> -j <blocktype> <iptables> -I f2b-<name> 1 -s <ip> -p udp -m multiport ! --dports <exemptports> -j <blocktype> ``` with `maxretry=1`, `findtime=32`, `bantime=30m` (`DockerEntrypoint.sh:18-20`), enabled by default in the shipped compose file (`XUI_ENABLE_FAIL2BAN: "true"`). A DROP there is invisible to `tcpdump`, which taps before the filter chains — which is exactly the shape of "packets on the wire, nothing in the device". Also please paste `cat /var/log/x-ui/3xipl-banned.log` and say whether your client's public IP appears there. 3. **`nstat -az | grep -i Udp` (or `netstat -su`) before and after the failure**, so we can see whether `receive buffer errors` / `packet receive errors` move. 4. **One run from a second client on a different public IP** (a desktop AmneziaWG client is fine), same inbound, same moment. Identical signature ⇒ server-side; that client working ⇒ per-source-IP filtering somewhere on the path. Text only, please — I cannot open images. --- Verdict: Confirmed bug (the reconcile/header-protection defect, unchanged from my previous comment; the session-death symptom is still unresolved — see "Not determined") Severity: High Confidence: High for the confirmed defect and for the rulings-out in §1-§2; Low for the cause of the session death Root cause: Unchanged for the confirmed defect: `buildUAPIConfig` gates `header_protection_key` on a non-empty value (`internal/amneziawgnet/device.go:216`), an absent UAPI line means "unchanged", and `addressFingerprint` (`manager.go:258-260`) covers only MTU/addresses so an obfuscation-only edit never rebuilds. Introduced with the feature itself, effcccce. For the session death: no root cause in `internal/amneziawgnet` — the package installs no netfilter rule (only `ip -6 addr`, `v6alias.go:106`), does not rebind the device socket (`device.go:139`), and the reporter's own 15s `newHandshake` timer at 17:50:00 rules out a `replace_peers` peer wipe by the 10s job (`web.go:295`, `manager.go:96-101`, `device.go:201`). Already fixed: Still present on the default branch (f727d04f, v3.7.0); `git log -- internal/amneziawgnet/` still returns only effcccce. Duplicate of: None. Related: #6303 (same package, throughput collapse) — this thread's run B now rules `RandomTrailers` out for *this* symptom, so still not a duplicate. Evidence: `internal/amneziawg/types.go:220-236` and `instance.go:70` (pure copy, no defaults); `internal/web/job/amneziawg_job.go:41-52`, `internal/web/runtime/local.go:65-75`, `:198-208` (all three call sites identical); `internal/web/service/inbound_amneziawg.go:171-200` (`defaultAmneziaWGServer`/`GenerateObfuscation31` unreachable once a server block exists) and `:201-208` (trim/canonicalize only); `internal/amneziawgnet/device.go:216` (`if opts.HeaderProtectionKey != "" {`); `manager.go:96-101` ("its own implementation of that op is device.RemoveAllPeers(), unconditionally"); `manager.go:137-149` (no-op branch); `web.go:295` (`cadenceAmneziaWG = "@every 10s"`); `portfwd.go:6-8` (userspace listeners, explicitly not DNAT); `v6alias.go:106` (the package's only exec); `DockerEntrypoint.sh:55-56` (ban action covers UDP on all non-exempt ports) and `:18-20` (`maxretry=1`, `findtime=32`, `bantime=30m`); repo-wide grep for `more then 12` returns nothing. Not determined: Why the device stops receiving authenticated packets from the peer roughly a second after the handshake, while the client is still transmitting. The single check that splits it: `Recv-Q` on the device's UDP socket during the failure (item 1 above) — climbing means the receive path stalled server-side, zero means the packets are being dropped before the socket. Also still unverifiable here: amneziawg-go's own logging and validation behaviour, since the module is not vendored in this checkout. Suggested fix: Unchanged and scoped to the confirmed defect only: emit the AWG 3.x string fields unconditionally (empty = clear) exactly as `random_trailers`/`disable_cookies` already are at `device.go:241-242`, or add the fields that cannot be merged to `addressFingerprint` (`manager.go:258`) so clearing one forces the rebuild branch instead of a doomed in-place `IpcSet`. I have retitled the issue to match what you now describe; the old title was *"[Bug]: AmneziaWG inbound relays UDP but never TCP — peers connect and resolve DNS, but no TCP session reaches Xray"*. Keeping "clarification needed" on until item 1 comes back. @MHSanaei — no change to the confirmed defect above; this update only rules the AWG 3.1 parameter set out as the cause of the reporter's connection failure. *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Author
Owner

@bharmalej commented on GitHub (Aug 25, 2026):

All four items from your list, captured on the same node/build.

1. Recv-Q during a live failure — pinned at 0, and it tells us more than "not stalled"

Sampled netstat -uanp + /proc/net/snmp every 3s across two separate live sessions (iPhone, then macOS AmneziaWG client). Full window, not cherry-picked:

=== 18:13:19 ===
udp   0   0 0.0.0.0:40188   0.0.0.0:*   1/x-ui
Udp: InDatagrams 708  InErrors 0  RcvbufErrors 0

=== 18:13:22 ===   (handshake landed at 18:13:20-21, see below)
udp   0   0 0.0.0.0:40188   0.0.0.0:*   1/x-ui
Udp: InDatagrams 750  InErrors 0  RcvbufErrors 0

Recv-Q never left 0 across ~35 samples spanning both sessions. InErrors and RcvbufErrors never moved from 0, in either session. But InDatagrams jumps in clean steps every time a burst of packets lands — so packets are reaching the socket and being drained instantly, with zero backlog and zero kernel-level drops.

That's a third outcome, not quite either of the two you offered: not "stalled with a growing backlog," not "never arrives at the socket." Everything that arrives is read cleanly and immediately. Whatever is killing the session is entirely inside amneziawg-go's own state machine, above the socket.

2. iptables / fail2ban — checked from inside, ruled out two ways

You were right to flag this — the image does ship XUI_ENABLE_FAIL2BAN=true by default and I hadn't set that variable myself, so it's on:

fail2ban-server is running
Jail list: 3x-ipl

But:

$ fail2ban-client status 3x-ipl
Status for the jail: 3x-ipl
|- Filter
|  |- Currently failed: 0
|  `- Total failed:     0
`- Actions
   |- Currently banned:  0
   |- Total banned:      0
   `- Banned IP list:    (empty)

Zero across both test sessions (iPhone then Mac, different local devices). /var/log/x-ui/3xipl-banned.log is empty — 0 bytes.

And structurally it cannot ban here even if it wanted to:

$ docker inspect --format 'CapAdd:{{.HostConfig.CapAdd}} Privileged:{{.HostConfig.Privileged}}' 3x-ui
CapAdd:[] Privileged:false

$ iptables -L -n   (as root, inside the container)
iptables v1.8.13 (nf_tables): Could not fetch rule set generation id: Permission denied (you must be root)

No CAP_NET_ADMIN, so iptables can't even read the ruleset, let alone -I a ban rule. On the host, DOCKER-USER only carries two ipset rules from an unrelated haproxy-fail2ban setup (49 and 0 entries respectively) — neither references the AmneziaWG port. So fail2ban is running but inert for this path.

3. nstat / netstat errors — same data as item 1, both sessions clean

Covered above: InErrors=0, RcvbufErrors=0 for the full duration of both the iPhone session and the Mac session. No error counter moved at any sample point.

4. Second client, different device — done, with a caveat worth flagging myself

Installed AmneziaWG on macOS on a separate physical machine and reproduced. Caveat: same public IP as the iPhone — both devices are behind the same home NAT, so this does not control for per-source-IP filtering the way you intended. I don't have a second vantage point on a different network to test from right now.

For what it's worth, the failure signature is byte-for-byte identical to the iPhone run:

18:20:16  peer - Sending handshake initiation
18:20:22  peer - Handshake did not complete after 5 seconds, retrying (try 6)
18:20:22  peer - Sending handshake initiation
...
18:21:01  peer - Retrying handshake because we stopped hearing back after 15 seconds
18:21:03  peer - Handshake did not complete after 5 seconds, retrying (try 2)

Same ~15s session lifetime, same endless failed rekey loop, zero accepted tcp: for the whole session. Different OS, different WireGuard/AmneziaWG client implementation, same result. Whatever this is, it isn't specific to Apple's mobile WireGuard stack.

One more data point I wasn't asked for: the first TCP session of the entire investigation

During the iPhone run, exactly one TCP session finally appeared:

18:13:21.496794  udp:127.0.0.1:33917 accepted udp:17.248.176.9:443  [in-40188-udp >> direct]
18:13:21.496833  tcp:127.0.0.1:37914 accepted tcp:17.248.176.9:443  [in-40188-udp >> direct]

Same Apple IP, QUIC and TCP fired within the same millisecond — that pattern looks like an OS-level connectivity probe racing both protocols to one endpoint, not a Safari page load, so I'm not claiming "TCP works now." But the timing is exactly consistent with everything else here: it landed in the same ~300 ms burst as the handshake completion logged one second earlier (18:13:20 handshake response, first UDP/TCP traffic at 18:13:21.1-18:13:21.5), i.e. it snuck through inside the brief live window before the session died again. This is more evidence for, not against, the "session lives ~15-20s then can't be re-established" mechanism — TCP isn't structurally blocked, it just essentially never gets a wide enough window.

Summary

Nothing in this round points at anything outside internal/amneziawgnet's own session/handshake handling: the kernel path is clean (item 1/3), the only firewall in the picture is provably inert (item 2), and the failure reproduces identically on a second OS/client on the same node (item 4). I don't have the means to test from a genuinely different public IP right now — if that's still a live hypothesis for you, let me know what would distinguish it and I'll see what I can arrange.

<!-- gh-comment-id:5412731009 --> @bharmalej commented on GitHub (Aug 25, 2026): All four items from your list, captured on the same node/build. ## 1. `Recv-Q` during a live failure — pinned at 0, and it tells us more than "not stalled" Sampled `netstat -uanp` + `/proc/net/snmp` every 3s across two separate live sessions (iPhone, then macOS AmneziaWG client). Full window, not cherry-picked: ``` === 18:13:19 === udp 0 0 0.0.0.0:40188 0.0.0.0:* 1/x-ui Udp: InDatagrams 708 InErrors 0 RcvbufErrors 0 === 18:13:22 === (handshake landed at 18:13:20-21, see below) udp 0 0 0.0.0.0:40188 0.0.0.0:* 1/x-ui Udp: InDatagrams 750 InErrors 0 RcvbufErrors 0 ``` `Recv-Q` never left 0 across ~35 samples spanning both sessions. `InErrors` and `RcvbufErrors` never moved from 0, in either session. But `InDatagrams` jumps in clean steps every time a burst of packets lands — so packets *are* reaching the socket and being drained instantly, with zero backlog and zero kernel-level drops. That's a third outcome, not quite either of the two you offered: not "stalled with a growing backlog," not "never arrives at the socket." Everything that arrives is read cleanly and immediately. Whatever is killing the session is entirely inside `amneziawg-go`'s own state machine, above the socket. ## 2. iptables / fail2ban — checked from inside, ruled out two ways You were right to flag this — the image does ship `XUI_ENABLE_FAIL2BAN=true` by default and I hadn't set that variable myself, so it's on: ``` fail2ban-server is running Jail list: 3x-ipl ``` But: ``` $ fail2ban-client status 3x-ipl Status for the jail: 3x-ipl |- Filter | |- Currently failed: 0 | `- Total failed: 0 `- Actions |- Currently banned: 0 |- Total banned: 0 `- Banned IP list: (empty) ``` Zero across both test sessions (iPhone then Mac, different local devices). `/var/log/x-ui/3xipl-banned.log` is empty — 0 bytes. And structurally it cannot ban here even if it wanted to: ``` $ docker inspect --format 'CapAdd:{{.HostConfig.CapAdd}} Privileged:{{.HostConfig.Privileged}}' 3x-ui CapAdd:[] Privileged:false $ iptables -L -n (as root, inside the container) iptables v1.8.13 (nf_tables): Could not fetch rule set generation id: Permission denied (you must be root) ``` No `CAP_NET_ADMIN`, so `iptables` can't even read the ruleset, let alone `-I` a ban rule. On the host, `DOCKER-USER` only carries two ipset rules from an unrelated haproxy-fail2ban setup (49 and 0 entries respectively) — neither references the AmneziaWG port. So fail2ban is running but inert for this path. ## 3. nstat / netstat errors — same data as item 1, both sessions clean Covered above: `InErrors=0`, `RcvbufErrors=0` for the full duration of both the iPhone session and the Mac session. No error counter moved at any sample point. ## 4. Second client, different device — done, with a caveat worth flagging myself Installed AmneziaWG on macOS on a separate physical machine and reproduced. **Caveat: same public IP as the iPhone** — both devices are behind the same home NAT, so this does not control for per-source-IP filtering the way you intended. I don't have a second vantage point on a different network to test from right now. For what it's worth, the failure signature is byte-for-byte identical to the iPhone run: ``` 18:20:16 peer - Sending handshake initiation 18:20:22 peer - Handshake did not complete after 5 seconds, retrying (try 6) 18:20:22 peer - Sending handshake initiation ... 18:21:01 peer - Retrying handshake because we stopped hearing back after 15 seconds 18:21:03 peer - Handshake did not complete after 5 seconds, retrying (try 2) ``` Same ~15s session lifetime, same endless failed rekey loop, zero `accepted tcp:` for the whole session. Different OS, different WireGuard/AmneziaWG client implementation, same result. Whatever this is, it isn't specific to Apple's mobile WireGuard stack. ## One more data point I wasn't asked for: the first TCP session of the entire investigation During the iPhone run, exactly one TCP session finally appeared: ``` 18:13:21.496794 udp:127.0.0.1:33917 accepted udp:17.248.176.9:443 [in-40188-udp >> direct] 18:13:21.496833 tcp:127.0.0.1:37914 accepted tcp:17.248.176.9:443 [in-40188-udp >> direct] ``` Same Apple IP, QUIC and TCP fired within the same millisecond — that pattern looks like an OS-level connectivity probe racing both protocols to one endpoint, not a Safari page load, so I'm not claiming "TCP works now." But the timing is exactly consistent with everything else here: it landed in the same ~300 ms burst as the handshake completion logged one second earlier (`18:13:20` handshake response, first UDP/TCP traffic at `18:13:21.1`-`18:13:21.5`), i.e. it snuck through inside the brief live window before the session died again. This is more evidence for, not against, the "session lives ~15-20s then can't be re-established" mechanism — TCP isn't structurally blocked, it just essentially never gets a wide enough window. ## Summary Nothing in this round points at anything outside `internal/amneziawgnet`'s own session/handshake handling: the kernel path is clean (item 1/3), the only firewall in the picture is provably inert (item 2), and the failure reproduces identically on a second OS/client on the same node (item 4). I don't have the means to test from a genuinely different public IP right now — if that's still a live hypothesis for you, let me know what would distinguish it and I'll see what I can arrange.
Author
Owner

@github-actions[bot] commented on GitHub (Aug 25, 2026):

Your data pushed me to look at the one place I had not: the goroutine the decapsulated packets are delivered on. There is a real defect there — AttachUDPHandler runs the SOCKS5 relay synchronously on the tunnel's own per-peer packet-receive goroutine, with no read deadline, while AttachTCPForwarder deliberately does not. Anything that stalls that relay stalls every subsequent packet from that peer, TCP and UDP alike, and stops amneziawg-go from ever registering "I heard from this peer". That is exactly the shape of your failure. I also have one correction to item 1: Udp: InDatagrams does not show what you concluded.


1. The defect

AttachTCPForwarder runs its handler on a fresh goroutine, on purpose:

// internal/amneziawgnet/forwarder.go:26-28
fwd := tcp.NewForwarder(gstack, 0, 65535, func(r *tcp.ForwarderRequest) {
	go func(r *tcp.ForwarderRequest) {

and RelayTCP's own doc says why: "Blocks until the relay ends; meant to be called from (or as) an AttachTCPForwarder handler, which already runs each connection on its own goroutine" (relay.go:64-66).

AttachUDPHandler has no such goroutine:

// internal/amneziawgnet/udp.go:34-40
gstack.SetTransportProtocolHandler(udp.ProtocolNumber, func(id stack.TransportEndpointID, pkt *stack.PacketBuffer) bool {
	data := pkt.Clone().Data().AsRange().ToSlice()
	src := netip.AddrPortFrom(addrFromTcpip(id.RemoteAddress), id.RemotePort)
	dst := netip.AddrPortFrom(addrFromTcpip(id.LocalAddress), id.LocalPort)
	handler(src, dst, data)
	return true
})

Which goroutine is that? The package states it itself, in newUnconfiguredDevice's doc comment:

// internal/amneziawgnet/device.go:113-116
// A -race CI run caught exactly this as a real
// WARNING: DATA RACE between stack.(*nic).DeliverTransportPacket (the
// peer's receive goroutine, reading the handler table) and
// stack.(*Stack).SetTransportProtocolHandler (the attaching goroutine,

So the chain for every client→server packet is: amneziawg-go's per-peer receive routine → stackTun.Write → t.ep.InjectInbound (netstack.go:180-197) → gVisor DeliverNetworkPacket/DeliverTransportPacket → the callback above, inline. The package's own comment records the assumption that this returns fast:

// internal/amneziawgnet/netstack.go:78-82
// upload/client->server direction has no equivalent stall:
// Write->InjectInbound->DeliverNetworkPacket hands off into
// gVisor's own ~1MB per-connection TCP receive buffer and returns
// immediately.

That holds for TCP. It does not hold for UDP, because the handler Manager attaches (manager.go:199-209) calls m.Lookup (which takes the Manager mutex, manager.go:336-343) and then udpRelay.Handle, and Handle opens the SOCKS5 association before it spawns any goroutine:

// internal/amneziawgnet/relay.go:340-351
if !ok {
	var err error
	sess, err = newSocks5UDPSession(u.relay.Addr, email, u.relay.Password)
	...
	go u.pump(src, sess)
}

newSocks5UDPSession is a TCP connect plus two full request/response exchanges (relay.go:104-133): greeting + username/password (socks5Handshake, relay.go:139-173), then UDP ASSOCIATE + reply (relay.go:117-125). Only the dial is bounded:

// internal/amneziawgnet/relay.go:105
dialer := net.Dialer{Timeout: 5 * time.Second}

Every read after it is a bare io.ReadFull on ctrl with no deadline (relay.go:144, relay.go:163, relay.go:179, relay.go:193); grep -n SetDeadline internal/amneziawgnet/relay.go returns only the pump's 2-minute one at relay.go:369. A SOCKS5 peer that accepts the TCP connection and then does not answer parks that goroutine forever.

And it happens per source port, not per client. Sessions are keyed by u.sessions[src.String()] (relay.go:337) — IP and port. A resolver that uses a fresh ephemeral port per query, or a browser opening QUIC connections, opens a brand-new TCP control connection + 3 round trips for each one, all serialized on the tunnel's receive path. Your 10 accepted udp: entries inside one second are 10 sequential associations, with every other packet from that peer — including TCP SYNs — queued behind them.

2. What this explains, and what it does not

Explains, without needing anything outside the panel:

  • Zero RelayTCP: lines and zero accepted tcp:. Delivery is strictly serialized on one goroutine; a TCP SYN behind a stalled UDP association is never delivered to fwd.HandlePacket at all, so the forwarder is never entered and nothing can log.
  • Recv-Q pinned at 0. The socket reader is a different goroutine from the per-peer delivery routine, and your sessions are far too short to fill the per-peer queue between them. Backlog on the socket is exactly what you would not expect here.
  • "stopped hearing back after 15 seconds" while the client transmits. In wireguard-go the "authenticated packet received" timer bookkeeping lives on the same per-peer routine that calls tun.Write; stall it and the timer fires on schedule. Flagged as inference: amneziawg-go is not vendored in this checkout (go.mod:6, github.com/amnezia-vpn/amneziawg-go/v3 v3.1.20260814, not in the module cache here), so I am reasoning about its routine layout, not reading it.
  • Identical on iOS and macOS, identical across run A and run B. Nothing on this path reads an obfuscation parameter.
  • The single TCP session at 18:13:21.496833 landing in the same burst as the handshake: before anything stalled.

Does not explain, and I am not going to pretend otherwise: why your server-initiated rekeys get no answer. Handshake messages are processed on a device-wide routine, not the per-peer one, so a stalled delivery path should still let a client's handshake response through. Either something else is also dropping packets on the path, or my reading of the routine split is wrong. Item 1 below settles which.

3. Correction to item 1

Udp: InDatagrams in /proc/net/snmp is a network-namespace-wide counter, not a per-socket one. Inside this container it also counts the loopback SOCKS5 UDP relay traffic between the panel and Xray (127.0.0.1:65104 for inbound 4 — SOCKSBasePort = 65100 + inbound id, socks_config.go:12-18) and Xray's own DNS. Your own log line proxy/socks: client UDP connection from udp:127.0.0.1:56509 is one of the things incrementing it. So "InDatagrams jumps in clean steps" is consistent with your client's packets arriving — and equally consistent with them not arriving while the panel↔Xray loopback path keeps ticking. It does not distinguish the two. Recv-Q at 0 and InErrors/RcvbufErrors at 0 remain valid and useful; that one inference does not.

4. Two things that would close this

You have pprof available in this build — it is off by default and env-gated:

// main.go:93-96
if os.Getenv("XUI_PPROF") == "true" {
	go func() {
		logger.Info("pprof profiling server listening on 127.0.0.1:6060")
  1. A goroutine dump taken during the dead window. Add XUI_PPROF=true to the container environment, restart, reproduce, and while the session is silent run inside the container:
    wget -qO- 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' > /tmp/goroutines.txt
    grep -c amneziawgnet /tmp/goroutines.txt
    
    Paste every stack containing amneziawgnet. This is decisive. A goroutine parked in amneziawgnet.(*UDPRelay).Handle / socks5Handshake / readSocks5Reply with stackTun.Write or DeliverTransportPacket below it proves the defect above is your cause. None parked there means the delivery path is idle — i.e. nothing is arriving for it to deliver — and the answer is on the network path, not in this package. While you are there, netstat -tan | grep -c 65104 tells us how many SOCKS5 control connections have piled up.
  2. A capture taken inside the container's network namespace, not on the host NIC, during the same failure. From the host as root: nsenter -t $(docker inspect -f '{{.State.Pid}}' 3x-ui) -n tcpdump -ni any -tttt udp port 40188. Your earlier capture was upstream of Docker's DNAT; this one is the only place that shows what actually reached the panel's socket, which is the question item 1 turned out not to answer.

The header-protection defect from my first comment is unchanged and unaffected by any of this.


Verdict: Confirmed bug
Severity: High
Confidence: High that the defect below exists and is reachable on every AmneziaWG inbound; Medium that it is the cause of this reporter's session death (see "Not determined")
Root cause: AttachUDPHandler invokes its handler inline inside gVisor's transport-protocol callback (internal/amneziawgnet/udp.go:34-40, handler(src, dst, data) at :38), which the package itself documents as running on "the peer's receive goroutine" (device.go:113-116), reached via stackTun.Write -> ep.InjectInbound (netstack.go:180-197). The handler Manager attaches there (manager.go:199-209) calls UDPRelay.Handle, which performs a full SOCKS5 UDP ASSOCIATE — TCP connect plus greeting/auth plus associate — before spawning any goroutine (relay.go:340-351, go u.pump only at :350). Only the dial is bounded (relay.go:105, 5s); every subsequent io.ReadFull on the control connection has no deadline (relay.go:144, :163, :179, :193), so a SOCKS5 peer that accepts and does not answer parks the tunnel's delivery path indefinitely. Amplified by u.sessions being keyed on src.String() (relay.go:337) — IP and port — so every new client source port pays a fresh connect + 3 round trips on that same path. Triggering condition: any UDP flow from a peer whose association is slow or hung; everything behind it, TCP included, is never delivered. Introduced with the feature itself: effcccce feat(amneziawg): add native AmneziaWG protocol support (#6105).
Already fixed: Still present on the default branch (f727d04f, v3.7.0). git log --oneline -- internal/amneziawgnet/ returns only effcccce.
Duplicate of: None. Related: #6303 (AmneziaWG throughput collapse) — a per-source-port blocking associate on the receive path is a plausible contributor there too, but I have not shown it, so not a duplicate.
Evidence: udp.go:38 handler(src, dst, data) with no goroutine, against forwarder.go:27 go func(r *tcp.ForwarderRequest) {; relay.go:64-66 "Blocks until the relay ends; meant to be called from (or as) an AttachTCPForwarder handler, which already runs each connection on its own goroutine"; device.go:114-115 "DATA RACE between stack.(*nic).DeliverTransportPacket (the peer's receive goroutine, reading the handler table)"; netstack.go:78-82 "upload/client->server direction has no equivalent stall ... returns immediately" — the assumption this breaks; netstack.go:180-197 (Write -> InjectInbound); relay.go:342 newSocks5UDPSession(...) ahead of relay.go:350 go u.pump(src, sess); relay.go:105 sole timeout; relay.go:144/163/179/193 deadline-less io.ReadFull; relay.go:337 session key src.String(); manager.go:199-209 + manager.go:336-343 (the handler also takes the Manager mutex). Secondary hazard, flagged as inference since amneziawg-go is not readable here: ensureLocked holds m.mu across cur.dev.IpcSet (manager.go:151) and cur.dev.Close() (manager.go:165); if either waits for a peer's receive routine to drain while that routine is parked in m.Lookup, that is a lock inversion that would freeze the whole Manager. No test covers a slow or unresponsive SOCKS5 server — relay_e2e_test.go has only TestSocksRelayAgainstRealXray and TestManagerEnsureAutomaticallyWiresRelay, both gated behind XRAY_E2E_BINARY and neither running in CI.
Not determined: Whether this defect is what stalled your device, and separately why your server-initiated rekeys go unanswered when handshake processing should not sit on the stalled routine. The single check that settles the first: the goroutine dump in item 1 — a stack parked in UDPRelay.Handle/socks5Handshake under stackTun.Write confirms it, its absence rules it out. Still unreadable from this checkout: amneziawg-go itself (go.mod:6, not vendored and not in the module cache), so every claim about its internal routine layout above is inference, not source.

Suggested fix: Take the SOCKS5 association off gVisor's delivery callback the way AttachTCPForwarder already does at forwarder.go:27 — either spawn the handler, or at minimum have UDPRelay.Handle create the session on its own goroutine and queue the first datagram. Independently, newSocks5UDPSession should set a deadline on ctrl around the greeting/auth/associate exchange rather than relying on the dial timeout alone.

@MHSanaei — confirmed High-severity defect on the embedded AmneziaWG receive path; the header-protection defect from earlier in this thread stands as well. Leaving the issue open pending the goroutine dump.

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:5412935459 --> @github-actions[bot] commented on GitHub (Aug 25, 2026): Your data pushed me to look at the one place I had not: **the goroutine the decapsulated packets are delivered on**. There is a real defect there — `AttachUDPHandler` runs the SOCKS5 relay **synchronously on the tunnel's own per-peer packet-receive goroutine**, with no read deadline, while `AttachTCPForwarder` deliberately does not. Anything that stalls that relay stalls every subsequent packet from that peer, TCP and UDP alike, and stops amneziawg-go from ever registering "I heard from this peer". That is exactly the shape of your failure. I also have one correction to item 1: `Udp: InDatagrams` does **not** show what you concluded. --- ## 1. The defect `AttachTCPForwarder` runs its handler on a fresh goroutine, on purpose: ```go // internal/amneziawgnet/forwarder.go:26-28 fwd := tcp.NewForwarder(gstack, 0, 65535, func(r *tcp.ForwarderRequest) { go func(r *tcp.ForwarderRequest) { ``` and `RelayTCP`'s own doc says why: *"Blocks until the relay ends; meant to be called from (or as) an AttachTCPForwarder handler, which already runs each connection on its own goroutine"* (`relay.go:64-66`). `AttachUDPHandler` has no such goroutine: ```go // internal/amneziawgnet/udp.go:34-40 gstack.SetTransportProtocolHandler(udp.ProtocolNumber, func(id stack.TransportEndpointID, pkt *stack.PacketBuffer) bool { data := pkt.Clone().Data().AsRange().ToSlice() src := netip.AddrPortFrom(addrFromTcpip(id.RemoteAddress), id.RemotePort) dst := netip.AddrPortFrom(addrFromTcpip(id.LocalAddress), id.LocalPort) handler(src, dst, data) return true }) ``` Which goroutine is that? The package states it itself, in `newUnconfiguredDevice`'s doc comment: ```go // internal/amneziawgnet/device.go:113-116 // A -race CI run caught exactly this as a real // WARNING: DATA RACE between stack.(*nic).DeliverTransportPacket (the // peer's receive goroutine, reading the handler table) and // stack.(*Stack).SetTransportProtocolHandler (the attaching goroutine, ``` So the chain for every client→server packet is: amneziawg-go's per-peer receive routine → `stackTun.Write` → `t.ep.InjectInbound` (`netstack.go:180-197`) → gVisor `DeliverNetworkPacket`/`DeliverTransportPacket` → **the callback above, inline**. The package's own comment records the assumption that this returns fast: ```go // internal/amneziawgnet/netstack.go:78-82 // upload/client->server direction has no equivalent stall: // Write->InjectInbound->DeliverNetworkPacket hands off into // gVisor's own ~1MB per-connection TCP receive buffer and returns // immediately. ``` That holds for TCP. It does **not** hold for UDP, because the handler `Manager` attaches (`manager.go:199-209`) calls `m.Lookup` (which takes the Manager mutex, `manager.go:336-343`) and then `udpRelay.Handle`, and `Handle` opens the SOCKS5 association **before** it spawns any goroutine: ```go // internal/amneziawgnet/relay.go:340-351 if !ok { var err error sess, err = newSocks5UDPSession(u.relay.Addr, email, u.relay.Password) ... go u.pump(src, sess) } ``` `newSocks5UDPSession` is a TCP connect plus two full request/response exchanges (`relay.go:104-133`): greeting + username/password (`socks5Handshake`, `relay.go:139-173`), then UDP ASSOCIATE + reply (`relay.go:117-125`). Only the **dial** is bounded: ```go // internal/amneziawgnet/relay.go:105 dialer := net.Dialer{Timeout: 5 * time.Second} ``` Every read after it is a bare `io.ReadFull` on `ctrl` with **no deadline** (`relay.go:144`, `relay.go:163`, `relay.go:179`, `relay.go:193`); `grep -n SetDeadline internal/amneziawgnet/relay.go` returns only the pump's 2-minute one at `relay.go:369`. A SOCKS5 peer that accepts the TCP connection and then does not answer parks that goroutine forever. **And it happens per source port, not per client.** Sessions are keyed by `u.sessions[src.String()]` (`relay.go:337`) — IP **and** port. A resolver that uses a fresh ephemeral port per query, or a browser opening QUIC connections, opens a brand-new TCP control connection + 3 round trips **for each one**, all serialized on the tunnel's receive path. Your 10 `accepted udp:` entries inside one second are 10 sequential associations, with every other packet from that peer — including TCP SYNs — queued behind them. ## 2. What this explains, and what it does not Explains, without needing anything outside the panel: - **Zero `RelayTCP:` lines and zero `accepted tcp:`.** Delivery is strictly serialized on one goroutine; a TCP SYN behind a stalled UDP association is never delivered to `fwd.HandlePacket` at all, so the forwarder is never entered and nothing can log. - **`Recv-Q` pinned at 0.** The socket reader is a different goroutine from the per-peer delivery routine, and your sessions are far too short to fill the per-peer queue between them. Backlog on the socket is exactly what you would *not* expect here. - **"stopped hearing back after 15 seconds" while the client transmits.** In wireguard-go the "authenticated packet received" timer bookkeeping lives on the same per-peer routine that calls `tun.Write`; stall it and the timer fires on schedule. *Flagged as inference:* amneziawg-go is not vendored in this checkout (`go.mod:6`, `github.com/amnezia-vpn/amneziawg-go/v3 v3.1.20260814`, not in the module cache here), so I am reasoning about its routine layout, not reading it. - **Identical on iOS and macOS, identical across run A and run B.** Nothing on this path reads an obfuscation parameter. - **The single TCP session at `18:13:21.496833`** landing in the same burst as the handshake: before anything stalled. Does **not** explain, and I am not going to pretend otherwise: why your server-initiated rekeys get no answer. Handshake messages are processed on a device-wide routine, not the per-peer one, so a stalled delivery path should still let a client's handshake response through. Either something else is also dropping packets on the path, or my reading of the routine split is wrong. Item 1 below settles which. ## 3. Correction to item 1 `Udp: InDatagrams` in `/proc/net/snmp` is a **network-namespace-wide** counter, not a per-socket one. Inside this container it also counts the loopback SOCKS5 UDP relay traffic between the panel and Xray (`127.0.0.1:65104` for inbound 4 — `SOCKSBasePort = 65100` + inbound id, `socks_config.go:12-18`) and Xray's own DNS. Your own log line `proxy/socks: client UDP connection from udp:127.0.0.1:56509` is one of the things incrementing it. So "InDatagrams jumps in clean steps" is consistent with your client's packets arriving — and equally consistent with them not arriving while the panel↔Xray loopback path keeps ticking. It does not distinguish the two. `Recv-Q` at 0 and `InErrors`/`RcvbufErrors` at 0 remain valid and useful; that one inference does not. ## 4. Two things that would close this You have pprof available in this build — it is off by default and env-gated: ```go // main.go:93-96 if os.Getenv("XUI_PPROF") == "true" { go func() { logger.Info("pprof profiling server listening on 127.0.0.1:6060") ``` 1. **A goroutine dump taken during the dead window.** Add `XUI_PPROF=true` to the container environment, restart, reproduce, and while the session is silent run inside the container: ``` wget -qO- 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' > /tmp/goroutines.txt grep -c amneziawgnet /tmp/goroutines.txt ``` Paste every stack containing `amneziawgnet`. **This is decisive.** A goroutine parked in `amneziawgnet.(*UDPRelay).Handle` / `socks5Handshake` / `readSocks5Reply` with `stackTun.Write` or `DeliverTransportPacket` below it proves the defect above is your cause. None parked there means the delivery path is idle — i.e. nothing is arriving for it to deliver — and the answer is on the network path, not in this package. While you are there, `netstat -tan | grep -c 65104` tells us how many SOCKS5 control connections have piled up. 2. **A capture taken inside the container's network namespace**, not on the host NIC, during the same failure. From the host as root: `nsenter -t $(docker inspect -f '{{.State.Pid}}' 3x-ui) -n tcpdump -ni any -tttt udp port 40188`. Your earlier capture was upstream of Docker's DNAT; this one is the only place that shows what actually reached the panel's socket, which is the question item 1 turned out not to answer. The header-protection defect from my first comment is unchanged and unaffected by any of this. --- Verdict: Confirmed bug Severity: High Confidence: High that the defect below exists and is reachable on every AmneziaWG inbound; Medium that it is the cause of this reporter's session death (see "Not determined") Root cause: `AttachUDPHandler` invokes its handler inline inside gVisor's transport-protocol callback (`internal/amneziawgnet/udp.go:34-40`, `handler(src, dst, data)` at :38), which the package itself documents as running on "the peer's receive goroutine" (`device.go:113-116`), reached via `stackTun.Write` -> `ep.InjectInbound` (`netstack.go:180-197`). The handler `Manager` attaches there (`manager.go:199-209`) calls `UDPRelay.Handle`, which performs a full SOCKS5 UDP ASSOCIATE — TCP connect plus greeting/auth plus associate — before spawning any goroutine (`relay.go:340-351`, `go u.pump` only at :350). Only the dial is bounded (`relay.go:105`, 5s); every subsequent `io.ReadFull` on the control connection has no deadline (`relay.go:144`, `:163`, `:179`, `:193`), so a SOCKS5 peer that accepts and does not answer parks the tunnel's delivery path indefinitely. Amplified by `u.sessions` being keyed on `src.String()` (`relay.go:337`) — IP *and* port — so every new client source port pays a fresh connect + 3 round trips on that same path. Triggering condition: any UDP flow from a peer whose association is slow or hung; everything behind it, TCP included, is never delivered. Introduced with the feature itself: effcccce `feat(amneziawg): add native AmneziaWG protocol support (#6105)`. Already fixed: Still present on the default branch (f727d04f, v3.7.0). `git log --oneline -- internal/amneziawgnet/` returns only effcccce. Duplicate of: None. Related: #6303 (AmneziaWG throughput collapse) — a per-source-port blocking associate on the receive path is a plausible contributor there too, but I have not shown it, so not a duplicate. Evidence: `udp.go:38` `handler(src, dst, data)` with no goroutine, against `forwarder.go:27` `go func(r *tcp.ForwarderRequest) {`; `relay.go:64-66` "Blocks until the relay ends; meant to be called from (or as) an AttachTCPForwarder handler, which already runs each connection on its own goroutine"; `device.go:114-115` "DATA RACE between stack.(*nic).DeliverTransportPacket (the peer's receive goroutine, reading the handler table)"; `netstack.go:78-82` "upload/client->server direction has no equivalent stall ... returns immediately" — the assumption this breaks; `netstack.go:180-197` (`Write` -> `InjectInbound`); `relay.go:342` `newSocks5UDPSession(...)` ahead of `relay.go:350` `go u.pump(src, sess)`; `relay.go:105` sole timeout; `relay.go:144/163/179/193` deadline-less `io.ReadFull`; `relay.go:337` session key `src.String()`; `manager.go:199-209` + `manager.go:336-343` (the handler also takes the Manager mutex). Secondary hazard, *flagged as inference* since amneziawg-go is not readable here: `ensureLocked` holds `m.mu` across `cur.dev.IpcSet` (`manager.go:151`) and `cur.dev.Close()` (`manager.go:165`); if either waits for a peer's receive routine to drain while that routine is parked in `m.Lookup`, that is a lock inversion that would freeze the whole Manager. No test covers a slow or unresponsive SOCKS5 server — `relay_e2e_test.go` has only `TestSocksRelayAgainstRealXray` and `TestManagerEnsureAutomaticallyWiresRelay`, both gated behind `XRAY_E2E_BINARY` and neither running in CI. Not determined: Whether this defect is what stalled *your* device, and separately why your server-initiated rekeys go unanswered when handshake processing should not sit on the stalled routine. The single check that settles the first: the goroutine dump in item 1 — a stack parked in `UDPRelay.Handle`/`socks5Handshake` under `stackTun.Write` confirms it, its absence rules it out. Still unreadable from this checkout: amneziawg-go itself (`go.mod:6`, not vendored and not in the module cache), so every claim about its internal routine layout above is inference, not source. Suggested fix: Take the SOCKS5 association off gVisor's delivery callback the way `AttachTCPForwarder` already does at `forwarder.go:27` — either spawn the handler, or at minimum have `UDPRelay.Handle` create the session on its own goroutine and queue the first datagram. Independently, `newSocks5UDPSession` should set a deadline on `ctrl` around the greeting/auth/associate exchange rather than relying on the dial timeout alone. @MHSanaei — confirmed High-severity defect on the embedded AmneziaWG receive path; the header-protection defect from earlier in this thread stands as well. Leaving the issue open pending the goroutine dump. *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Author
Owner

@bharmalej commented on GitHub (Aug 25, 2026):

Ran both. Your own stated criterion for item 1 resolves this cleanly, and item 2 independently agrees.

Item 1 — goroutine dump: zero matches for the predicted stack

Two snapshots via XUI_PPROF=true, both timestamped solidly inside a dead window (handshake response logged at 18:45:58, session went silent at 18:46:14; snapshots taken at 18:46:34 and 18:46:56):

grep -c "DeliverTransportPacket\|InjectInbound" both snapshots:        0
grep -c "socks5Handshake\|newSocks5UDPSession" (outside pump) both:    0

There are pump goroutines parked in (*socks5UDPSession).receive, [IO wait] — but that's the expected steady state; pump already runs on its own goroutine per your own read of relay.go:350. Neither snapshot has a goroutine parked inline inside the delivery callback with a SOCKS5 handshake underneath it. 60 total goroutines in the second snapshot, none matching.

Per your own stated test: "A goroutine parked in UDPRelay.Handle/socks5Handshake/readSocks5Reply under stackTun.Write or DeliverTransportPacket confirms it. Its absence rules it out." It's absent, in both snapshots.

Item 2 — capture inside the container's network namespace: also zero

Couldn't get root for nsenter on this host, so I joined the same netns a different way — docker run --rm --net=container:3x-ui --cap-add=NET_ADMIN --cap-add=NET_RAW alpine tcpdump — same effect, past Docker's DNAT, at the actual delivery point.

20 seconds, entirely inside the same dead window (18:47:11–18:47:26):

28 packets captured, all IP 172.7.2.7.40188 > 95.31.222.160.<port>  (server -> client, 5s apart)
0 packets in the other direction

Server dutifully retries its own rekey every ~5s. Nothing arrives from the client, at the actual socket, for the entire window.

What this settles, and what it leaves open

Both checks agree independently: there is nothing for the delivery path to be stuck on, because nothing is arriving. That's a clean negative for the synchronous-SOCKS5-relay theory as the cause of this session death specifically — the defect you found in AttachUDPHandler is real (I'm not disputing the code reading), but it can't be what's blocking this particular failure if the goroutine dump shows no delivery-path goroutine ever gets far enough to hang on it.

That pushes this back to where your comment #2 already flagged it: something stops the client from transmitting anything — not even a bare handshake retry — for the ~15-20s the session is dead, then it resumes. I don't have visibility into the client's own internal state (iOS/macOS AmneziaWG app), and that's genuinely outside what server-side logs or goroutine dumps can show. If there's a client-side log or debug flag worth checking, I'm open to it, but I think this may be past what this issue's server-side evidence can settle further.

The header-protection defect stands unaffected by any of this.

<!-- gh-comment-id:5413025878 --> @bharmalej commented on GitHub (Aug 25, 2026): Ran both. Your own stated criterion for item 1 resolves this cleanly, and item 2 independently agrees. ## Item 1 — goroutine dump: zero matches for the predicted stack Two snapshots via `XUI_PPROF=true`, both timestamped solidly inside a dead window (handshake response logged at `18:45:58`, session went silent at `18:46:14`; snapshots taken at `18:46:34` and `18:46:56`): ``` grep -c "DeliverTransportPacket\|InjectInbound" both snapshots: 0 grep -c "socks5Handshake\|newSocks5UDPSession" (outside pump) both: 0 ``` There are `pump` goroutines parked in `(*socks5UDPSession).receive`, `[IO wait]` — but that's the expected steady state; `pump` already runs on its own goroutine per your own read of `relay.go:350`. Neither snapshot has a goroutine parked inline inside the delivery callback with a SOCKS5 handshake underneath it. 60 total goroutines in the second snapshot, none matching. Per your own stated test: *"A goroutine parked in `UDPRelay.Handle`/`socks5Handshake`/`readSocks5Reply` under `stackTun.Write` or `DeliverTransportPacket` confirms it. Its absence rules it out."* It's absent, in both snapshots. ## Item 2 — capture inside the container's network namespace: also zero Couldn't get root for `nsenter` on this host, so I joined the same netns a different way — `docker run --rm --net=container:3x-ui --cap-add=NET_ADMIN --cap-add=NET_RAW alpine tcpdump` — same effect, past Docker's DNAT, at the actual delivery point. 20 seconds, entirely inside the same dead window (`18:47:11`–`18:47:26`): ``` 28 packets captured, all IP 172.7.2.7.40188 > 95.31.222.160.<port> (server -> client, 5s apart) 0 packets in the other direction ``` Server dutifully retries its own rekey every ~5s. Nothing arrives from the client, at the actual socket, for the entire window. ## What this settles, and what it leaves open Both checks agree independently: **there is nothing for the delivery path to be stuck on, because nothing is arriving.** That's a clean negative for the synchronous-SOCKS5-relay theory as the cause of *this* session death specifically — the defect you found in `AttachUDPHandler` is real (I'm not disputing the code reading), but it can't be what's blocking this particular failure if the goroutine dump shows no delivery-path goroutine ever gets far enough to hang on it. That pushes this back to where your comment #2 already flagged it: something stops the *client* from transmitting anything — not even a bare handshake retry — for the ~15-20s the session is dead, then it resumes. I don't have visibility into the client's own internal state (iOS/macOS AmneziaWG app), and that's genuinely outside what server-side logs or goroutine dumps can show. If there's a client-side log or debug flag worth checking, I'm open to it, but I think this may be past what this issue's server-side evidence can settle further. The header-protection defect stands unaffected by any of this.
Author
Owner

@github-actions[bot] commented on GitHub (Aug 25, 2026):

Your dump meets the criterion I set, so I withdraw the AttachUDPHandler stall as the cause of your session death — it stays a real defect on its own, but it is not what is killing this session. What that leaves is one panel-controlled thing I had not checked, and it is missing: the panel can never emit PersistentKeepalive for an AmneziaWG client, because nothing anywhere sets keepAlive — there is no UI field for it, and the API is documented as never generating one. A peer with no keepalive is only reachable from the server while the mapping its own last packet opened is still alive, which is exactly the shape of "every server-initiated rekey fails".


1. Accepting the ruling-out

No goroutine parked under DeliverTransportPacket/InjectInbound in either snapshot is the negative I asked for, and your netns capture agrees independently. I am not going to re-argue it. The defect at internal/amneziawgnet/udp.go:38 (handler(src, dst, data) inline, against forwarder.go:27 go func(r *tcp.ForwarderRequest) {) and the header-protection defect from my first comment both stand as confirmed and are actionable now — nothing below is a precondition for either.

2. What the panel hands your client

All three independent emitters gate the line on a non-zero value:

// internal/sub/service.go:782-783
if client.KeepAlive > 0 {
	fmt.Fprintf(&b, "\nPersistentKeepalive = %d", client.KeepAlive)
}
// frontend/src/pages/clients/amneziawgConfig.ts:107-108
if (client.keepAlive && client.keepAlive > 0)
  lines.push(`PersistentKeepalive = ${client.keepAlive}`);

and the same at frontend/src/lib/xray/inbound-link.ts:1024-1025. The value defaults to zero and is never filled in:

  • KeepAlive int \json:"keepAlive" gorm:"column:wg_keep_alive;default:0"`—internal/database/model/model.go:930`
  • "Accepted on the same body but never generated: preSharedKey and keepAlive (WireGuard)" — frontend/src/pages/api-docs/endpoints.ts:871
  • No input renders it. The only keepAlive form control in the whole frontend is the outbound WireGuard peer editor (frontend/src/pages/xray/outbounds/protocols/wireguard.tsx:155-156); the client editor sets wgPreSharedKey and the allowed-IPs fields only (ClientFormModal.tsx:377-379, :698). The field exists in the inbound schema (frontend/src/schemas/protocols/inbound/amneziawg.ts:26) with nothing bound to it.

So every .conf, QR and vpn:// link the panel produces for an AmneziaWG client is a peer with no keepalive. Note the panel does use 25 where it is the WireGuard client rather than the server (frontend/src/pages/xray/overrides/PiaModal.tsx:114, keepAlive: 25), and the AmneziaWG documentation page shows the line in its example client config:

# docs/content/docs/en/config/amneziawg.mdx:160-164
[Peer]
PublicKey = <server public key>
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = your-server:443
PersistentKeepalive = 25

That example cannot currently be produced by the panel.

Flagged as inference, and it is the weak point: your silence starts ~1 s after the handshake, far sooner than any ordinary UDP NAT/conntrack idle timeout (Linux nf_conntrack_udp_timeout defaults to 30 s). So a missing keepalive fits "server-initiated rekeys are never answered while the client is idle" well and fits "the return path dies one second in" badly. I can read the emitters, not your path — which is why the next item is one edit and not another capture.

3. The cheap test — client side only, no root, no panel change

Open the imported profile on the iOS/macOS client, add one line to the [Peer] block, save, reconnect:

PersistentKeepalive = 25
  • Session survives past the 15 s mark and TCP starts completing ⇒ the return path was the mechanism, and the panel gap in §2 is the fix.
  • Nothing changes ⇒ the NAT return path is out, cheaply, and I would agree with you that server-side evidence is close to exhausted.

To make it survive a re-download rather than a hand edit, the client's keepAlive has to go in through the API — POST /panel/api/clients/update/:email accepts it (endpoints.ts:877), but that endpoint "replaces the row, it does not patch" (endpoints.ts:893), so send the full client payload.

4. The one gap in what you captured, for completeness

Your netns capture was taken at 18:47:11–18:47:26, inside a dead window — i.e. after the client had already given up. Zero inbound there is what both remaining hypotheses predict, so it distinguishes nothing. The capture that would split them is the same command run during an active browsing attempt — the moment your very first host-side capture showed 7 × 1264-byte data packets going client → server:

  • those data packets appear inside the container netns and the device still logs stopped hearing back after 15 seconds ⇒ they arrive and fail to authenticate, which is inside amneziawg-go;
  • they do not appear ⇒ they are lost on the host → container path, outside the panel.

Optional — I am not holding the issue open for it.


Verdict: Confirmed bug
Severity: High
Confidence: High for the two confirmed defects and for the keepAlive gap in §2 (all read as file:line); Low for the cause of your session death
Root cause: Two confirmed, unchanged from earlier in this thread. (a) buildUAPIConfig gates header_protection_key on a non-empty value (internal/amneziawgnet/device.go:216); an absent UAPI line means "unchanged", and addressFingerprint (manager.go:258-260) keys only on MTU/addresses, so an obfuscation-only edit never rebuilds and a cleared field can never be applied. (b) AttachUDPHandler runs the SOCKS5 associate inline on gVisor's transport callback (udp.go:34-40) with no deadline on the control reads (relay.go:144/163/179/193), unlike AttachTCPForwarder (forwarder.go:27). Both introduced with the feature itself, effcccce. New this round, and not a cause of the session death but a real gap: no code path ever sets model.Client.KeepAlive (model.go:930, default 0) and no UI control binds it, so PersistentKeepalive is never emitted (internal/sub/service.go:782-783, frontend/src/pages/clients/amneziawgConfig.ts:107-108, frontend/src/lib/xray/inbound-link.ts:1024-1025). For the reporter's session death: no root cause established in this repository — the reporter's goroutine dump rules out (b) as its cause by the criterion I stated, and the delivery path cannot stall on packets that never arrive.
Already fixed: Still present on the default branch (f727d04f, v3.7.0). git log --oneline -- internal/amneziawgnet/ internal/amneziawg/ still returns only effcccce.
Duplicate of: None. Related: #6303 (same package, throughput collapse).
Evidence: internal/sub/service.go:782-783 if client.KeepAlive > 0 {; frontend/src/pages/clients/amneziawgConfig.ts:107-108; frontend/src/lib/xray/inbound-link.ts:1024-1025; internal/database/model/model.go:930 gorm:"column:wg_keep_alive;default:0"; frontend/src/pages/api-docs/endpoints.ts:871 "Accepted on the same body but never generated: preSharedKey and keepAlive (WireGuard)"; frontend/src/pages/xray/outbounds/protocols/wireguard.tsx:155-156 (the only keepAlive control in the frontend, and it is on outbounds); frontend/src/pages/clients/ClientFormModal.tsx:377-379, :698 (client editor covers preSharedKey/allowedIPs only); frontend/src/schemas/protocols/inbound/amneziawg.ts:26 (field present, unbound); frontend/src/pages/xray/overrides/PiaModal.tsx:114 keepAlive: 25; docs/content/docs/en/config/amneziawg.mdx:164 PersistentKeepalive = 25 in the documented example. Carried forward: internal/amneziawgnet/device.go:216, manager.go:258-260, udp.go:38 vs forwarder.go:27, relay.go:64-66, relay.go:105 (sole timeout), relay.go:337 (session keyed on IP+port).
Not determined: Why the peer stops being heard ~1 s after the handshake. The two checks that would split it are in §3 and §4 above; the ~1 s onset is the part a missing keepalive does not explain, and I have flagged that rather than reasoned around it. Still unreadable from this checkout: amneziawg-go itself (go.mod:6, not vendored), so nothing about its internal receive, decrypt or logging behaviour is source-confirmed here.

Suggested fix: Scoped to the confirmed defects only, and unchanged: emit the AWG 3.x string fields unconditionally (empty = clear) as random_trailers/disable_cookies already are at device.go:241-242, or add the unmergeable fields to addressFingerprint so clearing one forces the rebuild branch; and take the SOCKS5 associate off gVisor's delivery callback the way forwarder.go:27 already does. The keepAlive gap is separate and smaller — a bound input on the client editor plus a sensible default for AmneziaWG peers.

@MHSanaei — no change to the two confirmed defects; new this round is that PersistentKeepalive can never appear in a panel-generated AmneziaWG client config, which the documentation example at docs/content/docs/en/config/amneziawg.mdx:164 already shows.

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:5413141673 --> @github-actions[bot] commented on GitHub (Aug 25, 2026): Your dump meets the criterion I set, so I withdraw the `AttachUDPHandler` stall as the cause of **your** session death — it stays a real defect on its own, but it is not what is killing this session. What that leaves is one panel-controlled thing I had not checked, and it is missing: **the panel can never emit `PersistentKeepalive` for an AmneziaWG client, because nothing anywhere sets `keepAlive`** — there is no UI field for it, and the API is documented as never generating one. A peer with no keepalive is only reachable from the server while the mapping its own last packet opened is still alive, which is exactly the shape of "every server-initiated rekey fails". --- ## 1. Accepting the ruling-out No goroutine parked under `DeliverTransportPacket`/`InjectInbound` in either snapshot is the negative I asked for, and your netns capture agrees independently. I am not going to re-argue it. The defect at `internal/amneziawgnet/udp.go:38` (`handler(src, dst, data)` inline, against `forwarder.go:27` `go func(r *tcp.ForwarderRequest) {`) and the header-protection defect from my first comment both stand as confirmed and are actionable now — nothing below is a precondition for either. ## 2. What the panel hands your client All three independent emitters gate the line on a non-zero value: ```go // internal/sub/service.go:782-783 if client.KeepAlive > 0 { fmt.Fprintf(&b, "\nPersistentKeepalive = %d", client.KeepAlive) } ``` ```ts // frontend/src/pages/clients/amneziawgConfig.ts:107-108 if (client.keepAlive && client.keepAlive > 0) lines.push(`PersistentKeepalive = ${client.keepAlive}`); ``` and the same at `frontend/src/lib/xray/inbound-link.ts:1024-1025`. The value defaults to zero and is never filled in: - `KeepAlive int \`json:"keepAlive" gorm:"column:wg_keep_alive;default:0"\`` — `internal/database/model/model.go:930` - *"Accepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard)"* — `frontend/src/pages/api-docs/endpoints.ts:871` - **No input renders it.** The only `keepAlive` form control in the whole frontend is the *outbound* WireGuard peer editor (`frontend/src/pages/xray/outbounds/protocols/wireguard.tsx:155-156`); the client editor sets `wgPreSharedKey` and the allowed-IPs fields only (`ClientFormModal.tsx:377-379`, `:698`). The field exists in the inbound schema (`frontend/src/schemas/protocols/inbound/amneziawg.ts:26`) with nothing bound to it. So every `.conf`, QR and `vpn://` link the panel produces for an AmneziaWG client is a peer with no keepalive. Note the panel *does* use 25 where it is the WireGuard client rather than the server (`frontend/src/pages/xray/overrides/PiaModal.tsx:114`, `keepAlive: 25`), and the AmneziaWG documentation page shows the line in its example client config: ```ini # docs/content/docs/en/config/amneziawg.mdx:160-164 [Peer] PublicKey = <server public key> AllowedIPs = 0.0.0.0/0, ::/0 Endpoint = your-server:443 PersistentKeepalive = 25 ``` That example cannot currently be produced by the panel. **Flagged as inference, and it is the weak point:** your silence starts ~1 s after the handshake, far sooner than any ordinary UDP NAT/conntrack idle timeout (Linux `nf_conntrack_udp_timeout` defaults to 30 s). So a missing keepalive fits *"server-initiated rekeys are never answered while the client is idle"* well and fits *"the return path dies one second in"* badly. I can read the emitters, not your path — which is why the next item is one edit and not another capture. ## 3. The cheap test — client side only, no root, no panel change Open the imported profile on the iOS/macOS client, add one line to the `[Peer]` block, save, reconnect: ```ini PersistentKeepalive = 25 ``` - Session survives past the 15 s mark and TCP starts completing ⇒ the return path was the mechanism, and the panel gap in §2 is the fix. - Nothing changes ⇒ the NAT return path is out, cheaply, and I would agree with you that server-side evidence is close to exhausted. To make it survive a re-download rather than a hand edit, the client's `keepAlive` has to go in through the API — `POST /panel/api/clients/update/:email` accepts it (`endpoints.ts:877`), but that endpoint *"replaces the row, it does not patch"* (`endpoints.ts:893`), so send the full client payload. ## 4. The one gap in what you captured, for completeness Your netns capture was taken at `18:47:11`–`18:47:26`, inside a dead window — i.e. after the client had already given up. Zero inbound there is what **both** remaining hypotheses predict, so it distinguishes nothing. The capture that would split them is the same command run during an **active** browsing attempt — the moment your very first host-side capture showed 7 × 1264-byte data packets going client → server: - those data packets appear inside the container netns and the device still logs `stopped hearing back after 15 seconds` ⇒ they arrive and fail to authenticate, which is inside amneziawg-go; - they do not appear ⇒ they are lost on the host → container path, outside the panel. Optional — I am not holding the issue open for it. --- Verdict: Confirmed bug Severity: High Confidence: High for the two confirmed defects and for the `keepAlive` gap in §2 (all read as file:line); Low for the cause of your session death Root cause: Two confirmed, unchanged from earlier in this thread. (a) `buildUAPIConfig` gates `header_protection_key` on a non-empty value (`internal/amneziawgnet/device.go:216`); an absent UAPI line means "unchanged", and `addressFingerprint` (`manager.go:258-260`) keys only on MTU/addresses, so an obfuscation-only edit never rebuilds and a cleared field can never be applied. (b) `AttachUDPHandler` runs the SOCKS5 associate inline on gVisor's transport callback (`udp.go:34-40`) with no deadline on the control reads (`relay.go:144/163/179/193`), unlike `AttachTCPForwarder` (`forwarder.go:27`). Both introduced with the feature itself, effcccce. New this round, and not a cause of the session death but a real gap: no code path ever sets `model.Client.KeepAlive` (`model.go:930`, default 0) and no UI control binds it, so `PersistentKeepalive` is never emitted (`internal/sub/service.go:782-783`, `frontend/src/pages/clients/amneziawgConfig.ts:107-108`, `frontend/src/lib/xray/inbound-link.ts:1024-1025`). For the reporter's session death: no root cause established in this repository — the reporter's goroutine dump rules out (b) as its cause by the criterion I stated, and the delivery path cannot stall on packets that never arrive. Already fixed: Still present on the default branch (f727d04f, v3.7.0). `git log --oneline -- internal/amneziawgnet/ internal/amneziawg/` still returns only effcccce. Duplicate of: None. Related: #6303 (same package, throughput collapse). Evidence: `internal/sub/service.go:782-783` `if client.KeepAlive > 0 {`; `frontend/src/pages/clients/amneziawgConfig.ts:107-108`; `frontend/src/lib/xray/inbound-link.ts:1024-1025`; `internal/database/model/model.go:930` `gorm:"column:wg_keep_alive;default:0"`; `frontend/src/pages/api-docs/endpoints.ts:871` "Accepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard)"; `frontend/src/pages/xray/outbounds/protocols/wireguard.tsx:155-156` (the only `keepAlive` control in the frontend, and it is on outbounds); `frontend/src/pages/clients/ClientFormModal.tsx:377-379`, `:698` (client editor covers preSharedKey/allowedIPs only); `frontend/src/schemas/protocols/inbound/amneziawg.ts:26` (field present, unbound); `frontend/src/pages/xray/overrides/PiaModal.tsx:114` `keepAlive: 25`; `docs/content/docs/en/config/amneziawg.mdx:164` `PersistentKeepalive = 25` in the documented example. Carried forward: `internal/amneziawgnet/device.go:216`, `manager.go:258-260`, `udp.go:38` vs `forwarder.go:27`, `relay.go:64-66`, `relay.go:105` (sole timeout), `relay.go:337` (session keyed on IP+port). Not determined: Why the peer stops being heard ~1 s after the handshake. The two checks that would split it are in §3 and §4 above; the ~1 s onset is the part a missing keepalive does not explain, and I have flagged that rather than reasoned around it. Still unreadable from this checkout: amneziawg-go itself (`go.mod:6`, not vendored), so nothing about its internal receive, decrypt or logging behaviour is source-confirmed here. Suggested fix: Scoped to the confirmed defects only, and unchanged: emit the AWG 3.x string fields unconditionally (empty = clear) as `random_trailers`/`disable_cookies` already are at `device.go:241-242`, or add the unmergeable fields to `addressFingerprint` so clearing one forces the rebuild branch; and take the SOCKS5 associate off gVisor's delivery callback the way `forwarder.go:27` already does. The `keepAlive` gap is separate and smaller — a bound input on the client editor plus a sensible default for AmneziaWG peers. @MHSanaei — no change to the two confirmed defects; new this round is that `PersistentKeepalive` can never appear in a panel-generated AmneziaWG client config, which the documentation example at `docs/content/docs/en/config/amneziawg.mdx:164` already shows. *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Author
Owner

@bharmalej commented on GitHub (Aug 25, 2026):

Ran the §3 test. Clean negative, same as you predicted for that outcome.

Hand-edited the same client's .conf (same server keys, same obfuscation params, only addition: PersistentKeepalive = 25), reimported, reconnected on WiFi:

19:02:33  peer - Received handshake initiation
19:02:33  peer - Sending handshake response
19:02:33  peer - Receiving keepalive packet          <- the added line was honored
19:02:48  peer - Retrying handshake because we stopped hearing back after 15 seconds
19:02:48  peer - Sending handshake initiation
19:02:54  peer - Handshake did not complete after 5 seconds, retrying (try 2)
...

One keepalive arrived right after the handshake, exactly as PersistentKeepalive = 25 should produce. Session still died at the same ~15s mark as every prior run, with accepted tcp: still at zero. That's expected given your own math on this: the death happens before the next scheduled keepalive (at the 25s mark) would even fire, so this test couldn't have looked any different even if a longer-interval NAT/conntrack expiry were the real mechanism — the configured interval never gets a chance to matter before the first death.

So per your own framing: nothing changed, and I agree the server-side evidence is close to exhausted. I don't have a next experiment to propose from this side. Client identity is confirmed unchanged for this run — same AmneziaWG app that's been used throughout this thread, hand-edited config, not a different implementation.

I'll leave the node in its current diagnostic state (XUI_PPROF=true, AMNEZIAWGNET_DEBUG=1, the two test inbounds) for now in case there's a next round, but I'm pausing active testing here. The header-protection defect and the AttachUDPHandler inline-relay defect both remain confirmed and actionable independent of whatever is causing this specific session's death.

<!-- gh-comment-id:5413253397 --> @bharmalej commented on GitHub (Aug 25, 2026): Ran the §3 test. Clean negative, same as you predicted for that outcome. Hand-edited the same client's `.conf` (same server keys, same obfuscation params, only addition: `PersistentKeepalive = 25`), reimported, reconnected on WiFi: ``` 19:02:33 peer - Received handshake initiation 19:02:33 peer - Sending handshake response 19:02:33 peer - Receiving keepalive packet <- the added line was honored 19:02:48 peer - Retrying handshake because we stopped hearing back after 15 seconds 19:02:48 peer - Sending handshake initiation 19:02:54 peer - Handshake did not complete after 5 seconds, retrying (try 2) ... ``` One keepalive arrived right after the handshake, exactly as `PersistentKeepalive = 25` should produce. Session still died at the same ~15s mark as every prior run, with `accepted tcp:` still at zero. That's expected given your own math on this: the death happens before the *next* scheduled keepalive (at the 25s mark) would even fire, so this test couldn't have looked any different even if a longer-interval NAT/conntrack expiry were the real mechanism — the configured interval never gets a chance to matter before the first death. So per your own framing: nothing changed, and I agree the server-side evidence is close to exhausted. I don't have a next experiment to propose from this side. Client identity is confirmed unchanged for this run — same AmneziaWG app that's been used throughout this thread, hand-edited config, not a different implementation. I'll leave the node in its current diagnostic state (`XUI_PPROF=true`, `AMNEZIAWGNET_DEBUG=1`, the two test inbounds) for now in case there's a next round, but I'm pausing active testing here. The header-protection defect and the `AttachUDPHandler` inline-relay defect both remain confirmed and actionable independent of whatever is causing this specific session's death.
Author
Owner

@github-actions[bot] commented on GitHub (Aug 25, 2026):

Your conclusion is probably right, but the test I asked for could not have shown it — PersistentKeepalive = 25 was the wrong number for this symptom's timescale, and the log line you read as proof it was applied does not prove that either. You spotted the first half yourself; the second half is mine to correct. I agree the server-side evidence is exhausted, so I am settling this issue on what is established and dropping the clarification hold.


1. Why §3 was under-powered — two reasons, not one

(a) 25 s is above the server's own death threshold. The panel's generator caps the server's KeepaliveTimeout deliberately, and its comment names your exact number:

// internal/amneziawg/params.go:86-89
// Max 20s: under clients' typical 25s PersistentKeepalive and ~30s NAT UDP
// timeouts, or idle links lose their NAT mapping.
kaLo := randInt(8, 12)
o.KeepaliveTimeout = fmt.Sprintf("%d-%d", kaLo, kaLo+randInt(2, 8))

randInt is inclusive on both ends (params.go:27-36), so a sampled KeepaliveTimeout lands in [8, 20] and RekeyTimeout (params.go:83-84, rtLo := randInt(3, 6), high = rtLo + randInt(1, 4)) in [3, 10]. Your run pinned them to the classic pair, and 10 + 5 = 15 — exactly the interval your log prints. Flagged as inference: that the newHandshake timer equals KeepaliveTimeout + RekeyTimeout is wireguard-go's own constant, not readable here (go.mod:6, not vendored); your pinned values matching the printed 15 s is the corroboration I have, not a source read.

So the server gives up at 15 s and the client's next scheduled keepalive is at 25 s — 10 s late, every time. Your reasoning is correct and I should have specified a value below the threshold in the first place.

Note the direction of the design here, because it cuts against the hypothesis anyway: params.go:86-87 puts the mapping-refresh duty on the server (keep its timeout under the client's 25 s), not on the client. That is the opposite of what my §2 assumed.

(b) The keepalive you saw is not evidence the edit took effect. Receiving keepalive packet immediately after Sending handshake response is the session-confirmation packet the initiator is required to send on receiving a handshake response — WireGuard emits it with PersistentKeepalive unset. Flagged as inference for the same reason as above: amneziawg-go is not in this checkout, so this is protocol behaviour I cannot cite to a line. It means run §3 has no positive control at all — nothing in that log distinguishes "the setting was applied" from "the setting was ignored".

If you ever resume, the discriminating value is one comfortably under the server's threshold — PersistentKeepalive = 5. But I would expect that to come back negative too, and for the reason I flagged last time rather than the one the test gave: your silence starts ~1 s after the handshake, and no keepalive interval addresses a return path that dies inside the first second. So I think your overall read ("obfuscation, NAT and the relay path are all out") stands — just not on the strength of this particular run.

2. The one measurement still unrun

For the record, not as a request: your netns capture was taken at 18:47:11–18:47:26, a dead window after the client had given up, so zero inbound there is what both remaining hypotheses predict. The variant that splits them is the same command during an active browsing attempt — the moment your very first host capture showed 7 × 1264-byte data packets going client → server:

nsenter -t $(docker inspect -f '{{.State.Pid}}' 3x-ui) -n tcpdump -ni any -tttt udp port 40188

Those full-size packets present inside the netns while the device still logs stopped hearing back ⇒ they arrive and fail to authenticate, which is inside amneziawg-go and belongs upstream. Absent ⇒ they are lost on the host → container path, outside the panel. Small packets (handshake init, keepalive) getting through while 1264-byte ones do not is the asymmetry that check would resolve.

3. What this issue leaves behind — all of it actionable now

Both defects confirmed earlier in this thread stand at the tip (f727d04f, v3.7.0); git log --oneline -- internal/amneziawgnet/ internal/amneziawg/ still returns only effcccce, and gh release list shows nothing newer than v3.7.0.

  1. Header protection cannot be cleared on a live device. if opts.HeaderProtectionKey != "" { (internal/amneziawgnet/device.go:216) — an absent UAPI line means "unchanged", and addressFingerprint (manager.go:258-260) keys only on MTU/addresses so an obfuscation-only edit never rebuilds. Silent when S1-S4 stay ≥ 12; a permanent IPC error -22 loop, with the peers already dropped by replace_peers=true, when S3/S4 are also lowered.
  2. AttachUDPHandler runs the SOCKS5 associate inline on gVisor's delivery callback. handler(src, dst, data) with no goroutine (udp.go:38) against go func(r *tcp.ForwarderRequest) { (forwarder.go:27), and no deadline on the control reads (relay.go:144/163/179/193). Your goroutine dump ruled it out as the cause of your session death; it remains reachable on every AmneziaWG inbound.
  3. PersistentKeepalive can never appear in a panel-generated client config — internal/sub/service.go:782-783 gates on client.KeepAlive > 0, model.go:930 defaults it to 0, and no UI control binds it. §1(a) gives this more weight than I gave it last time: the generator at params.go:86-87 is written on the assumption that clients carry a 25 s keepalive, and the panel is the thing that cannot produce one.

Thank you for the diagnostics — the goroutine dump, the netns capture and the two-client control were what let me retract a wrong theory instead of leaving it standing. Leaving this open on the confirmed defects; no further input is needed from you.


Verdict: Confirmed bug
Severity: High
Confidence: High for the three defects/gaps in §3 and for the §1(a) arithmetic (all file:line); Low for the cause of the session death, which is unchanged
Root cause: Unchanged, two confirmed. (a) buildUAPIConfig gates header_protection_key on a non-empty value (internal/amneziawgnet/device.go:216); an absent UAPI line means "unchanged" and addressFingerprint (manager.go:258-260) keys only on MTU/addresses, so a cleared field can never reach a running device. (b) AttachUDPHandler invokes its handler inline on gVisor's transport callback (udp.go:34-40, handler(...) at :38), unlike AttachTCPForwarder (forwarder.go:27), with only the dial bounded (relay.go:105) and no deadline on the SOCKS5 control reads. Both introduced with the feature itself, effcccce. Gap, not a cause: no code path sets model.Client.KeepAlive (model.go:930, default 0) and no UI control binds it, so PersistentKeepalive is never emitted. For the reporter's session death: still no root cause established in this repository — the goroutine dump ruled out (b) by the criterion I set, and the delivery path cannot stall on packets that never arrive.
Already fixed: Still present on the default branch (f727d04f, v3.7.0). git log --oneline -- internal/amneziawgnet/ internal/amneziawg/ returns only effcccce; latest release is v3.7.0.
Duplicate of: None. Related: #6303 (same package, throughput collapse); #6306, #6310 also AmneziaWG but different subsystems.
Evidence: internal/amneziawg/params.go:86-89 "Max 20s: under clients' typical 25s PersistentKeepalive and ~30s NAT UDP timeouts"; params.go:27-36 (randInt inclusive on both bounds); params.go:83-84 (RekeyTimeout range [3,10]); internal/sub/service.go:782-783 if client.KeepAlive > 0 {; internal/database/model/model.go:930 gorm:"column:wg_keep_alive;default:0"; frontend/src/schemas/protocols/inbound/amneziawg.ts:26 (field present, unbound). Carried forward and re-verified at tip: internal/amneziawgnet/device.go:216 if opts.HeaderProtectionKey != "" {; manager.go:258-260; udp.go:38 handler(src, dst, data) vs forwarder.go:27 go func(r *tcp.ForwarderRequest) {; relay.go:105 (sole timeout).
Not determined: Why the peer stops being heard ~1 s after the handshake. The single check that would split it is §2 above — a netns capture during an active attempt, not a dead window. The §3 keepalive test did not settle it either way: 25 s exceeds the server's own 15 s threshold, and the post-handshake keepalive is not a positive control. Still unreadable from this checkout: amneziawg-go itself (go.mod:6, not vendored), so its timer identities, receive path and logging are inference throughout this thread, never source.

Suggested fix: Unchanged and scoped to the confirmed defects: emit the AWG 3.x string fields unconditionally (empty = clear) as random_trailers/disable_cookies already are at device.go:241-242, or add the unmergeable fields to addressFingerprint so clearing one forces the rebuild branch; and take the SOCKS5 associate off gVisor's delivery callback the way forwarder.go:27 already does. The keepAlive gap is separate and smaller — a bound input on the client editor plus a sensible default for AmneziaWG peers.

@MHSanaei — no change to the two confirmed defects; this round only retracts the keepalive theory as a diagnostic and records that the panel cannot emit PersistentKeepalive at all, which internal/amneziawg/params.go:86-87 assumes clients have. Removing "clarification needed" — nothing further is blocked on the reporter.

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:5413336163 --> @github-actions[bot] commented on GitHub (Aug 25, 2026): Your conclusion is probably right, but the test I asked for could not have shown it — **`PersistentKeepalive = 25` was the wrong number for this symptom's timescale, and the log line you read as proof it was applied does not prove that either.** You spotted the first half yourself; the second half is mine to correct. I agree the server-side evidence is exhausted, so I am settling this issue on what is established and dropping the clarification hold. --- ## 1. Why §3 was under-powered — two reasons, not one **(a) 25 s is above the server's own death threshold.** The panel's generator caps the server's `KeepaliveTimeout` deliberately, and its comment names your exact number: ```go // internal/amneziawg/params.go:86-89 // Max 20s: under clients' typical 25s PersistentKeepalive and ~30s NAT UDP // timeouts, or idle links lose their NAT mapping. kaLo := randInt(8, 12) o.KeepaliveTimeout = fmt.Sprintf("%d-%d", kaLo, kaLo+randInt(2, 8)) ``` `randInt` is inclusive on both ends (`params.go:27-36`), so a sampled `KeepaliveTimeout` lands in **[8, 20]** and `RekeyTimeout` (`params.go:83-84`, `rtLo := randInt(3, 6)`, high `= rtLo + randInt(1, 4)`) in **[3, 10]**. Your run pinned them to the classic pair, and 10 + 5 = **15** — exactly the interval your log prints. *Flagged as inference:* that the `newHandshake` timer equals `KeepaliveTimeout + RekeyTimeout` is wireguard-go's own constant, not readable here (`go.mod:6`, not vendored); your pinned values matching the printed 15 s is the corroboration I have, not a source read. So the server gives up at 15 s and the client's next scheduled keepalive is at 25 s — 10 s late, every time. Your reasoning is correct and I should have specified a value below the threshold in the first place. Note the direction of the design here, because it cuts against the hypothesis anyway: `params.go:86-87` puts the mapping-refresh duty on the **server** (keep its timeout under the client's 25 s), not on the client. That is the opposite of what my §2 assumed. **(b) The keepalive you saw is not evidence the edit took effect.** `Receiving keepalive packet` immediately after `Sending handshake response` is the session-confirmation packet the *initiator* is required to send on receiving a handshake response — WireGuard emits it with `PersistentKeepalive` unset. *Flagged as inference for the same reason as above:* amneziawg-go is not in this checkout, so this is protocol behaviour I cannot cite to a line. It means run §3 has no positive control at all — nothing in that log distinguishes "the setting was applied" from "the setting was ignored". **If you ever resume**, the discriminating value is one comfortably under the server's threshold — `PersistentKeepalive = 5`. But I would expect that to come back negative too, and for the reason I flagged last time rather than the one the test gave: your silence starts **~1 s** after the handshake, and no keepalive interval addresses a return path that dies inside the first second. So I think your overall read ("obfuscation, NAT and the relay path are all out") stands — just not on the strength of this particular run. ## 2. The one measurement still unrun For the record, not as a request: your netns capture was taken at `18:47:11`–`18:47:26`, a dead window after the client had given up, so zero inbound there is what *both* remaining hypotheses predict. The variant that splits them is the same command during an **active** browsing attempt — the moment your very first host capture showed 7 × 1264-byte data packets going client → server: ``` nsenter -t $(docker inspect -f '{{.State.Pid}}' 3x-ui) -n tcpdump -ni any -tttt udp port 40188 ``` Those full-size packets present inside the netns while the device still logs `stopped hearing back` ⇒ they arrive and fail to authenticate, which is inside amneziawg-go and belongs upstream. Absent ⇒ they are lost on the host → container path, outside the panel. Small packets (handshake init, keepalive) getting through while 1264-byte ones do not is the asymmetry that check would resolve. ## 3. What this issue leaves behind — all of it actionable now Both defects confirmed earlier in this thread stand at the tip (`f727d04f`, v3.7.0); `git log --oneline -- internal/amneziawgnet/ internal/amneziawg/` still returns only `effcccce`, and `gh release list` shows nothing newer than v3.7.0. 1. **Header protection cannot be cleared on a live device.** `if opts.HeaderProtectionKey != "" {` (`internal/amneziawgnet/device.go:216`) — an absent UAPI line means "unchanged", and `addressFingerprint` (`manager.go:258-260`) keys only on MTU/addresses so an obfuscation-only edit never rebuilds. Silent when `S1`-`S4` stay ≥ 12; a permanent `IPC error -22` loop, with the peers already dropped by `replace_peers=true`, when `S3`/`S4` are also lowered. 2. **`AttachUDPHandler` runs the SOCKS5 associate inline on gVisor's delivery callback.** `handler(src, dst, data)` with no goroutine (`udp.go:38`) against `go func(r *tcp.ForwarderRequest) {` (`forwarder.go:27`), and no deadline on the control reads (`relay.go:144/163/179/193`). Your goroutine dump ruled it out as the cause of *your* session death; it remains reachable on every AmneziaWG inbound. 3. **`PersistentKeepalive` can never appear in a panel-generated client config** — `internal/sub/service.go:782-783` gates on `client.KeepAlive > 0`, `model.go:930` defaults it to 0, and no UI control binds it. §1(a) gives this more weight than I gave it last time: the generator at `params.go:86-87` is written on the assumption that clients carry a 25 s keepalive, and the panel is the thing that cannot produce one. Thank you for the diagnostics — the goroutine dump, the netns capture and the two-client control were what let me retract a wrong theory instead of leaving it standing. Leaving this open on the confirmed defects; no further input is needed from you. --- Verdict: Confirmed bug Severity: High Confidence: High for the three defects/gaps in §3 and for the §1(a) arithmetic (all file:line); Low for the cause of the session death, which is unchanged Root cause: Unchanged, two confirmed. (a) `buildUAPIConfig` gates `header_protection_key` on a non-empty value (`internal/amneziawgnet/device.go:216`); an absent UAPI line means "unchanged" and `addressFingerprint` (`manager.go:258-260`) keys only on MTU/addresses, so a cleared field can never reach a running device. (b) `AttachUDPHandler` invokes its handler inline on gVisor's transport callback (`udp.go:34-40`, `handler(...)` at :38), unlike `AttachTCPForwarder` (`forwarder.go:27`), with only the dial bounded (`relay.go:105`) and no deadline on the SOCKS5 control reads. Both introduced with the feature itself, `effcccce`. Gap, not a cause: no code path sets `model.Client.KeepAlive` (`model.go:930`, default 0) and no UI control binds it, so `PersistentKeepalive` is never emitted. For the reporter's session death: still no root cause established in this repository — the goroutine dump ruled out (b) by the criterion I set, and the delivery path cannot stall on packets that never arrive. Already fixed: Still present on the default branch (`f727d04f`, v3.7.0). `git log --oneline -- internal/amneziawgnet/ internal/amneziawg/` returns only `effcccce`; latest release is v3.7.0. Duplicate of: None. Related: #6303 (same package, throughput collapse); #6306, #6310 also AmneziaWG but different subsystems. Evidence: `internal/amneziawg/params.go:86-89` "Max 20s: under clients' typical 25s PersistentKeepalive and ~30s NAT UDP timeouts"; `params.go:27-36` (`randInt` inclusive on both bounds); `params.go:83-84` (`RekeyTimeout` range [3,10]); `internal/sub/service.go:782-783` `if client.KeepAlive > 0 {`; `internal/database/model/model.go:930` `gorm:"column:wg_keep_alive;default:0"`; `frontend/src/schemas/protocols/inbound/amneziawg.ts:26` (field present, unbound). Carried forward and re-verified at tip: `internal/amneziawgnet/device.go:216` `if opts.HeaderProtectionKey != "" {`; `manager.go:258-260`; `udp.go:38` `handler(src, dst, data)` vs `forwarder.go:27` `go func(r *tcp.ForwarderRequest) {`; `relay.go:105` (sole timeout). Not determined: Why the peer stops being heard ~1 s after the handshake. The single check that would split it is §2 above — a netns capture during an *active* attempt, not a dead window. The §3 keepalive test did not settle it either way: 25 s exceeds the server's own 15 s threshold, and the post-handshake keepalive is not a positive control. Still unreadable from this checkout: amneziawg-go itself (`go.mod:6`, not vendored), so its timer identities, receive path and logging are inference throughout this thread, never source. Suggested fix: Unchanged and scoped to the confirmed defects: emit the AWG 3.x string fields unconditionally (empty = clear) as `random_trailers`/`disable_cookies` already are at `device.go:241-242`, or add the unmergeable fields to `addressFingerprint` so clearing one forces the rebuild branch; and take the SOCKS5 associate off gVisor's delivery callback the way `forwarder.go:27` already does. The `keepAlive` gap is separate and smaller — a bound input on the client editor plus a sensible default for AmneziaWG peers. @MHSanaei — no change to the two confirmed defects; this round only retracts the keepalive theory as a diagnostic and records that the panel cannot emit `PersistentKeepalive` at all, which `internal/amneziawg/params.go:86-87` assumes clients have. Removing "clarification needed" — nothing further is blocked on the reporter. *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#4295
No description provided.