Xray-core icon indicating copy to clipboard operation
Xray-core copied to clipboard

Hysteria: rejected authentication responses leak HTTP/3 cancellation goroutines and QUIC state

Open zanyatta opened this issue 1 month ago • 0 comments

Integrity requirements

  • [x] I have read the issue template and its requirements.
  • [x] I understand the settings used in the reproducer; it contains only the settings needed for this test.
  • [x] The complete self-contained client/server reproducer and its output are included below.
  • [x] I searched issues and did not find a duplicate of this authentication-response leak. Related issue #7100 is discussed below.
  • [x] Reproduced on the latest published release, v26.10.10 (marked prerelease), as well as v26.9.30.

Description

Hysteria 客户端收到非 233 的认证响应后,会持续泄漏 HTTP/3 请求取消协程以及协程持有的 QUIC 状态。长期反复连接一个认证失败的节点,内存会不断增长。

已实测版本:

  • v26.10.10,commit 701af60772cda123492f86e383e1fdba066614a9。
  • v26.9.30,commit b26a91de4f3294e26a0ad0a970b81a386a41f789。
  • 主分支此前的 commit c7dbfd5e1ea3bb2dee042582507b2ce78a44d3a7,包含 #7107 的实例连接池清理修复。
  • Linux amd64,Go 1.27.0;各版本使用其原始 go.mod/go.sum,没有修改内核或依赖版本。

对于 401、403、500,每类重复 128 次均留下 128 个 http3.(*ClientConn).roundTrip.func1 协程,GC 后保留约 7–8 MB 堆内存。调用方每次都会取消拨号上下文;测试还调用关联的 core.Instance.Close() 并等待超过连接池清理周期,泄漏依然存在。233 成功对照组没有残留这些协程(128 次 Dial 复用一次认证)。

Resource lifecycle analysis

Hysteria dialer 在非 233 分支中关闭 QUIC transport/socket 后直接返回,跳过后面的 resp.Body.Close()。认证 HTTP 请求也没有绑定传入的 ctx。

该版本依赖的 HTTP/3 client 启动了一个取消协程,仅等待请求上下文取消或 reqDone;没有监听 QUIC 连接关闭。reqDone 在响应体被读取完成/报错或 Close 时关闭。因此,关闭连接无法结束这个协程。

这与 #7100 的全局连接池跨实例存活不同:#7107 负责清理连接池里的 client,无法结束这批未完成的 HTTP/3 认证响应。测试特意关联了真实 core.Instance 并执行 Close,而非仅检查某一行代码。

一个可能的最小修复是:RoundTrip 成功返回后,在状态码判断之前关闭响应体,使所有认证状态都执行清理。此前在 v26.3.27 上验证过这个调整:同样的失败响应测试不再留下等待协程。此处只提交问题报告,没有 PR。

Reproduction Method

  1. checkout v26.10.10,将下方完整测试保存为 transport/internet/hysteria/auth_audit_test.go。
  2. 执行:
go test -v -count=1 ./transport/internet/hysteria -run '^TestHysteriaAuthenticationResponsesReleaseResources$'
  1. 预期三个失败认证子测试报告残留协程/堆内存,成功认证子测试通过。

这是进程内的本地 HTTP/3 合成测试,无需外部节点、真实密码、DNS 或互联网请求。DisableChromeParrot 仅用于兼容测试生成的 Ed25519 证书;TLS 使用证书 SHA-256 pin 验证。

Client config / Server config

客户端完整 MemoryStreamConfig、core 实例生命周期、服务端 handler 和临时证书均包含在以下测试中,不需要额外 JSON 配置。服务端故意返回非 233 的认证状态;这里测试的是认证响应的清理,不是 TCP 业务转发。

完整可运行测试
package hysteria_test

import (
	"bytes"
	"context"
	"crypto/ed25519"
	"crypto/rand"
	"crypto/sha256"
	stdtls "crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"math/big"
	"net"
	"net/http"
	"runtime"
	"runtime/pprof"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"github.com/apernet/quic-go"
	"github.com/apernet/quic-go/http3"
	xnet "github.com/xtls/xray-core/common/net"
	"github.com/xtls/xray-core/core"
	"github.com/xtls/xray-core/transport/internet"
	"github.com/xtls/xray-core/transport/internet/hysteria"
	xtls "github.com/xtls/xray-core/transport/internet/tls"
)

func authWaiters() int {
	var b bytes.Buffer
	_ = pprof.Lookup("goroutine").WriteTo(&b, 2)
	return strings.Count(b.String(), "http3.(*ClientConn).roundTrip.func1(")
}

func TestHysteriaAuthenticationResponsesReleaseResources(t *testing.T) {
	for _, status := range []int{401, 403, 500, hysteria.StatusAuthOK} {
		t.Run(fmt.Sprint(status), func(t *testing.T) {
			pub, priv, err := ed25519.GenerateKey(rand.Reader)
			if err != nil {
				t.Fatal(err)
			}
			template := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), DNSNames: []string{"localhost"}, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
			der, err := x509.CreateCertificate(rand.Reader, template, template, pub, priv)
			if err != nil {
				t.Fatal(err)
			}
			key, err := x509.MarshalPKCS8PrivateKey(priv)
			if err != nil {
				t.Fatal(err)
			}
			cert, err := stdtls.X509KeyPair(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: key}))
			if err != nil {
				t.Fatal(err)
			}
			pc, err := net.ListenPacket("udp", "127.0.0.1:0")
			if err != nil {
				t.Fatal(err)
			}
			var requests atomic.Int64
			server := &http3.Server{QUICConfig: &quic.Config{MaxIncomingStreams: 1024}, TLSConfig: &stdtls.Config{Certificates: []stdtls.Certificate{cert}}, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				requests.Add(1)
				w.WriteHeader(status)
				if status != hysteria.StatusAuthOK {
					_, _ = w.Write([]byte("authentication rejected"))
				}
			})}
			exited := make(chan error, 1)
			go func() { exited <- server.Serve(pc) }()
			t.Cleanup(func() { _ = server.Close(); _ = pc.Close(); <-exited })
			addr := pc.LocalAddr().(*net.UDPAddr)
			pin := sha256.Sum256(der)
			settings := &internet.MemoryStreamConfig{ProtocolName: "hysteria", QuicParams: &internet.QuicParams{DisableChromeParrot: true}, ProtocolSettings: &hysteria.Config{Auth: "synthetic-test-password"}, SecurityType: "tls", SecuritySettings: &xtls.Config{ServerName: "localhost", NextProtocol: []string{"h3"}, PinnedPeerCertSha256: [][]byte{pin[:]}}}
			dest := xnet.TCPDestination(xnet.IPAddress(addr.IP), xnet.Port(addr.Port))
			instance, err := core.New(&core.Config{})
			if err != nil {
				t.Fatal(err)
			}
			if err := instance.Start(); err != nil {
				t.Fatal(err)
			}
			ownerCtx := context.WithValue(context.Background(), core.XrayKey(1), instance)
			beforeWaiters := authWaiters()
			runtime.GC()
			var before runtime.MemStats
			runtime.ReadMemStats(&before)
			const attempts = 128
			for i := 0; i < attempts; i++ {
				ctx, cancel := context.WithTimeout(ownerCtx, 2*time.Second)
				conn, err := hysteria.Dial(ctx, dest, settings)
				cancel()
				if status == hysteria.StatusAuthOK {
					if err != nil {
						t.Fatal(err)
					}
					_ = conn.Close()
				} else if err == nil || !strings.Contains(err.Error(), "auth failed") {
					t.Fatalf("attempt %d: expected auth rejection, got %v", i, err)
				}
			}
			t.Logf("before instance.Close: auth_waiters=%d", authWaiters()-beforeWaiters)
			if err := instance.Close(); err != nil {
				t.Fatal(err)
			}
			time.Sleep(1500 * time.Millisecond)
			deadline := time.Now().Add(2 * time.Second)
			for authWaiters() > beforeWaiters+2 && time.Now().Before(deadline) {
				time.Sleep(20 * time.Millisecond)
			}
			runtime.GC()
			var after runtime.MemStats
			runtime.ReadMemStats(&after)
			retained := int64(after.HeapAlloc) - int64(before.HeapAlloc)
			waiters := authWaiters() - beforeWaiters
			t.Logf("status=%d attempts=%d HTTP/3_requests=%d retained_heap=%d bytes leaked_auth_waiters=%d", status, attempts, requests.Load(), retained, waiters)
			if requests.Load() == 0 {
				t.Fatal("test did not reach HTTP/3 authentication server")
			}
			if waiters > 2 {
				t.Errorf("authentication requests retained %d cancellation goroutines", waiters)
			}
			if retained > 4<<20 {
				t.Errorf("authentication requests retained %d bytes", retained)
			}
		})
	}
}

Client log

v26.10.10 的测试输出如下,仅移除了每次拨号重复出现的 loopback debug 行,保留全部测试结果和失败断言:

测试输出
go: downloading github.com/yuin/gopher-lua v1.1.2
go: downloading layeh.com/gopher-luar v1.0.11
=== RUN   TestHysteriaAuthenticationResponsesReleaseResources
=== RUN   TestHysteriaAuthenticationResponsesReleaseResources/401
2026/10/10 10:56:27.478264 [Warning] core: Xray 26.10.10 started
    auth_audit_test.go:103: before instance.Close: auth_waiters=128
    auth_audit_test.go:117: status=401 attempts=128 HTTP/3_requests=128 retained_heap=8073112 bytes leaked_auth_waiters=128
    auth_audit_test.go:122: authentication requests retained 128 cancellation goroutines
    auth_audit_test.go:125: authentication requests retained 8073112 bytes
=== RUN   TestHysteriaAuthenticationResponsesReleaseResources/403
2026/10/10 10:56:31.513750 [Warning] core: Xray 26.10.10 started
    auth_audit_test.go:103: before instance.Close: auth_waiters=128
    auth_audit_test.go:117: status=403 attempts=128 HTTP/3_requests=128 retained_heap=7408912 bytes leaked_auth_waiters=128
    auth_audit_test.go:122: authentication requests retained 128 cancellation goroutines
    auth_audit_test.go:125: authentication requests retained 7408912 bytes
=== RUN   TestHysteriaAuthenticationResponsesReleaseResources/500
2026/10/10 10:56:35.516457 [Warning] core: Xray 26.10.10 started
    auth_audit_test.go:103: before instance.Close: auth_waiters=128
    auth_audit_test.go:117: status=500 attempts=128 HTTP/3_requests=128 retained_heap=7461016 bytes leaked_auth_waiters=128
    auth_audit_test.go:122: authentication requests retained 128 cancellation goroutines
    auth_audit_test.go:125: authentication requests retained 7461016 bytes
=== RUN   TestHysteriaAuthenticationResponsesReleaseResources/233
2026/10/10 10:56:39.478242 [Warning] core: Xray 26.10.10 started
2026/10/10 10:56:39.491386 [Debug] transport/internet/hysteria: ECHAccepted false
    auth_audit_test.go:103: before instance.Close: auth_waiters=0
    auth_audit_test.go:117: status=233 attempts=128 HTTP/3_requests=1 retained_heap=171480 bytes leaked_auth_waiters=0
--- FAIL: TestHysteriaAuthenticationResponsesReleaseResources (13.54s)
    --- FAIL: TestHysteriaAuthenticationResponsesReleaseResources/401 (4.04s)
    --- FAIL: TestHysteriaAuthenticationResponsesReleaseResources/403 (4.00s)
    --- FAIL: TestHysteriaAuthenticationResponsesReleaseResources/500 (3.96s)
    --- PASS: TestHysteriaAuthenticationResponsesReleaseResources/233 (1.54s)
FAIL
FAIL	github.com/xtls/xray-core/transport/internet/hysteria	13.561s
FAIL

Server log

服务端没有独立日志进程;每个 handler 调用由原子计数记录,输出中的 HTTP/3_requests 是实收请求数。401/403/500 各收到 128 次认证请求;233 收到一次,随后复用已认证连接。

zanyatta avatar Oct 10 '26 10:10 zanyatta