From bc98cb67212df127a457cf88bd07197ee8fbb5b2 Mon Sep 17 00:00:00 2001 From: Nemu-x Date: Tue, 20 Oct 2026 19:40:12 +0300 Subject: [PATCH 1/2] fix: bound REALITY handshakes and preserve JLS application verification --- handshake_client.go | 6 -- jls_verify_test.go | 57 ++++++++++++ reality.go | 60 ++++++++++--- reality_guard.go | 72 +++++++++++++++ reality_guard_test.go | 198 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 374 insertions(+), 19 deletions(-) create mode 100644 jls_verify_test.go create mode 100644 reality_guard.go create mode 100644 reality_guard_test.go diff --git a/handshake_client.go b/handshake_client.go index 3726e669e7..18788b0327 100644 --- a/handshake_client.go +++ b/handshake_client.go @@ -1277,12 +1277,6 @@ func (c *Conn) verifyServerCertificate(certificates [][]byte) error { c.activeCertHandles = activeHandles c.peerCertificates = certs - // JLS BEGIN: external verifiers are skipped after successful JLS authentication. - if c.jlsAuthenticated() { - return nil - } - // JLS END - if c.config.VerifyPeerCertificate != nil && !echRejected { if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil { c.sendAlert(alertBadCertificate) diff --git a/jls_verify_test.go b/jls_verify_test.go new file mode 100644 index 0000000000..84628d893f --- /dev/null +++ b/jls_verify_test.go @@ -0,0 +1,57 @@ +package tls + +import ( + "bytes" + "crypto/x509" + "errors" + "testing" +) + +func TestJLSAuthenticationStillRunsCertificateCallbacks(t *testing.T) { + for _, reject := range []string{"", "peer", "connection"} { + t.Run(reject, func(t *testing.T) { + refusal := errors.New("application refused JLS peer") + var calls []string + config := &Config{ + InsecureSkipVerify: true, + VerifyPeerCertificate: func(raw [][]byte, chains [][]*x509.Certificate) error { + calls = append(calls, "peer") + if len(raw) != 1 || !bytes.Equal(raw[0], testRSACertificate) { + t.Fatal("callback received wrong certificate") + } + if reject == "peer" { + return refusal + } + return nil + }, + VerifyConnection: func(state ConnectionState) error { + calls = append(calls, "connection") + if len(state.PeerCertificates) != 1 { + t.Fatal("connection state lacks peer certificate") + } + if reject == "connection" { + return refusal + } + return nil + }, + } + conn := Client(&bytesConn{Reader: bytes.NewReader(nil)}, config) + conn.jlsState = jlsStateAuthSuccess + err := conn.verifyServerCertificate([][]byte{testRSACertificate}) + if reject == "" { + if err != nil { + t.Fatal(err) + } + } else if !errors.Is(err, refusal) { + t.Fatalf("application verifier bypassed: %v", err) + } + want := 2 + if reject == "peer" { + want = 1 + } + if len(calls) != want || calls[0] != "peer" { + t.Fatalf("callback sequence %v", calls) + } + }) + } +} diff --git a/reality.go b/reality.go index e6db803e37..28da544c2a 100644 --- a/reality.go +++ b/reality.go @@ -6,6 +6,7 @@ import ( "context" "crypto/aes" "crypto/cipher" + "crypto/ecdh" "crypto/ed25519" "crypto/hmac" "crypto/rand" @@ -27,7 +28,6 @@ import ( "github.com/metacubex/utls/internal/mlkem" "github.com/metacubex/utls/internal/ratelimit" - "golang.org/x/crypto/curve25519" "golang.org/x/crypto/hkdf" ) @@ -60,15 +60,15 @@ func (c *realityMirrorConn) Close() error { } func (c *realityMirrorConn) SetDeadline(t time.Time) error { - return nil + return c.Conn.SetDeadline(t) } func (c *realityMirrorConn) SetReadDeadline(t time.Time) error { - return nil + return c.Conn.SetReadDeadline(t) } func (c *realityMirrorConn) SetWriteDeadline(t time.Time) error { - return nil + return c.Conn.SetWriteDeadline(t) } // realitySize bounds the target's first flight buffered by the REALITY @@ -118,6 +118,11 @@ type RealityConfig struct { LimitFallbackUpload RealityLimitFallback LimitFallbackDownload RealityLimitFallback + // HandshakeTimeout bounds authentication and the TLS handshake, until the + // connection is accepted or handed to fallback. Zero uses 15 seconds. + // A fallback relay has no total duration limit imposed by this setting. + HandshakeTimeout time.Duration + // Mldsa65Seed is the 32-byte ML-DSA-65 private key seed, the // base64url-decoded value of Xray's "mldsa65Seed". When set, the temporary // certificate carries an ML-DSA-65 signature in its first extension, which @@ -140,6 +145,7 @@ type RealityConfig struct { // mldsa65 caches the private key expanded from Mldsa65Seed. mldsa65 atomic.Pointer[realityMldsa65Key] + ecdhKey atomic.Pointer[realityECDHKey] } func (a *RealityConfig) Clone() *RealityConfig { @@ -157,11 +163,13 @@ func (a *RealityConfig) Clone() *RealityConfig { ShortIds: a.ShortIds, LimitFallbackUpload: a.LimitFallbackUpload, LimitFallbackDownload: a.LimitFallbackDownload, + HandshakeTimeout: a.HandshakeTimeout, Mldsa65Seed: a.Mldsa65Seed, RequireX25519MLKEM768: a.RequireX25519MLKEM768, Config: *a.Config.Clone(), } c.postHandshake.Store(a.postHandshakeCache()) + c.ecdhKey.Store(a.ecdhKey.Load()) return c } @@ -172,6 +180,10 @@ type rateLimitedConn struct { } func (c *rateLimitedConn) Read(b []byte) (int, error) { + // Do not let the last free read cross the configured threshold. + if c.After > 0 && int64(len(b)) > c.After { + b = b[:int(c.After)] + } n, err := c.Conn.Read(b) if n != 0 { if c.After > 0 { @@ -409,6 +421,8 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* conn.Close() return nil, errors.New("REALITY: failed to dial dest: " + err.Error()) } + stopHandshake := guardRealityHandshake(ctx, conn, target, config.HandshakeTimeout) + defer stopHandshake() underlying := conn @@ -424,7 +438,7 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* }, config: &config.Config, }, - ctx: context.Background(), + ctx: ctx, }, Config: config, } @@ -437,7 +451,7 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* go func() { for { mutex.Lock() - hs.clientHello, _, err = hs.c.readClientHello(context.Background()) // TODO: Change some rules in this function. + hs.clientHello, _, err = hs.c.readClientHello(ctx) // TODO: Change some rules in this function. if copying || err != nil || hs.c.vers != VersionTLS13 || !config.ServerNames[hs.clientHello.serverName] { break } @@ -446,7 +460,17 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* config.Log("REALITY remoteAddr: %v no acceptable key share", remoteAddr) } for peerPub != nil { - if hs.AuthKey, err = curve25519.X25519(config.PrivateKey, peerPub); err != nil { + privateKey, keyErr := config.realityPrivateKey() + if keyErr != nil { + err = keyErr + break + } + publicKey, keyErr := ecdh.X25519().NewPublicKey(peerPub) + if keyErr != nil { + err = keyErr + break + } + if hs.AuthKey, err = privateKey.ECDH(publicKey); err != nil { break } if _, err = hkdf.New(sha256.New, hs.AuthKey, hs.clientHello.random[:20], []byte("REALITY")).Read(hs.AuthKey); err != nil { @@ -454,9 +478,6 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* } block, _ := aes.NewCipher(hs.AuthKey) aead, _ := cipher.NewGCM(block) - if config.Log != nil { - config.Log("REALITY remoteAddr: %v hs.c.AuthKey[:16]: %v AEAD: %T", remoteAddr, hs.AuthKey[:16], aead) - } ciphertext := make([]byte, 32) plainText := make([]byte, 32) copy(ciphertext, hs.clientHello.sessionId) @@ -471,7 +492,6 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* if config.Log != nil { config.Log("REALITY remoteAddr: %v hs.c.ClientVer: %v", remoteAddr, hs.ClientVer) config.Log("REALITY remoteAddr: %v hs.c.ClientTime: %v", remoteAddr, hs.ClientTime) - config.Log("REALITY remoteAddr: %v hs.c.ClientShortId: %v", remoteAddr, hs.ClientShortId) } if (config.MinClientVer == nil || realityValue(hs.ClientVer[:]...) >= realityValue(config.MinClientVer...)) && (config.MaxClientVer == nil || realityValue(hs.ClientVer[:]...) <= realityValue(config.MaxClientVer...)) && @@ -488,6 +508,7 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* } mutex.Unlock() if hs.c.conn != conn { + stopHandshake() if config.Log != nil && hs.clientHello != nil { config.Log("REALITY remoteAddr: %v forwarded SNI: %v", remoteAddr, hs.clientHello.serverName) } @@ -497,8 +518,17 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* }() go func() { - s2cSaved := make([]byte, 0, realitySize) - buf := make([]byte, realitySize) + savedBlock := realityBufferPool.Get().(*[realitySize]byte) + defer realityBufferPool.Put(savedBlock) + s2cSaved := savedBlock[:0] + readBlock := realityBufferPool.Get().(*[realitySize]byte) + probeOwnsBuffer := false + defer func() { + if !probeOwnsBuffer { + realityBufferPool.Put(readBlock) + } + }() + buf := readBlock[:] handshakeLen := 0 f: for { @@ -581,7 +611,9 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* if err != nil { break } + probeOwnsBuffer = true go func() { // TODO: Probe target's maxUselessRecords and some time-outs in advance. + defer realityBufferPool.Put(readBlock) if handshakeLen-len(s2cSaved) > 0 { io.ReadFull(target, buf[:handshakeLen-len(s2cSaved)]) } @@ -609,10 +641,12 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (* break } hs.c.isHandshakeComplete.Store(true) + stopHandshake() break } mutex.Unlock() if hs.c.out.handshakeLen[0] == 0 { // if the target sent an incorrect Server Hello, or before that + stopHandshake() if hs.c.conn == conn { // if we processed the Client Hello successfully but the target did not waitGroup.Add(1) go func() { diff --git a/reality_guard.go b/reality_guard.go new file mode 100644 index 0000000000..b6308eebb5 --- /dev/null +++ b/reality_guard.go @@ -0,0 +1,72 @@ +package tls + +import ( + "context" + "crypto/ecdh" + "errors" + "net" + "sync" + "time" +) + +var realityBufferPool = sync.Pool{New: func() any { return new([realitySize]byte) }} + +type realityECDHKey struct { + source [32]byte + key *ecdh.PrivateKey +} + +func (c *RealityConfig) realityPrivateKey() (*ecdh.PrivateKey, error) { + if len(c.PrivateKey) != 32 { + return nil, errors.New("REALITY: invalid private key length") + } + source := [32]byte(c.PrivateKey) + if cached := c.ecdhKey.Load(); cached != nil && cached.source == source { + return cached.key, nil + } + key, err := ecdh.X25519().NewPrivateKey(c.PrivateKey) + if err != nil { + return nil, err + } + c.ecdhKey.Store(&realityECDHKey{source: source, key: key}) + return key, nil +} + +func guardRealityHandshake(ctx context.Context, conn, target net.Conn, timeout time.Duration) func() { + if timeout <= 0 { + timeout = 15 * time.Second + } + deadline := time.Now().Add(timeout) + if until, ok := ctx.Deadline(); ok && until.Before(deadline) { + deadline = until + } + _ = conn.SetReadDeadline(deadline) + stopped := make(chan struct{}) + closePending := func() { + select { + case <-stopped: + return + default: + } + _ = conn.Close() + _ = target.Close() + } + timer := time.AfterFunc(time.Until(deadline), closePending) + if ctx.Done() != nil { + go func() { + select { + case <-ctx.Done(): + closePending() + case <-stopped: + } + }() + } + var once sync.Once + return func() { + once.Do(func() { + close(stopped) + timer.Stop() + _ = conn.SetReadDeadline(time.Time{}) + }) + } +} diff --git a/reality_guard_test.go b/reality_guard_test.go new file mode 100644 index 0000000000..66cc1161a5 --- /dev/null +++ b/reality_guard_test.go @@ -0,0 +1,198 @@ +package tls + +import ( + "bytes" + "context" + "crypto/ecdh" + "fmt" + "io" + "net" + "strings" + "sync" + "testing" + "time" + + "github.com/metacubex/utls/internal/ratelimit" + "golang.org/x/crypto/curve25519" +) + +func TestRealitySilentHandshakeTimesOut(t *testing.T) { + for _, cancelled := range []bool{false, true} { + t.Run(fmt.Sprint(cancelled), func(t *testing.T) { + client, server := net.Pipe() + target, peer := net.Pipe() + defer client.Close() + defer peer.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + config := &RealityConfig{HandshakeTimeout: 30 * time.Millisecond, DialContext: func(context.Context, string, string) (net.Conn, error) { return target, nil }} + done := make(chan error, 1) + go func() { _, err := RealityServer(ctx, server, config); done <- err }() + if cancelled { + cancel() + } + select { + case err := <-done: + if err == nil { + t.Fatal("silent peer authenticated") + } + case <-time.After(time.Second): + t.Fatal("handshake did not close") + } + for _, c := range []net.Conn{client, peer} { + c.SetReadDeadline(time.Now().Add(time.Second)) + if _, err := c.Read(make([]byte, 1)); err != io.EOF { + t.Fatalf("socket retained after handshake: %v", err) + } + } + }) + } +} + +func TestRealityFallbackOutlivesHandshakeTimeout(t *testing.T) { + client, server := net.Pipe() + target, peer := net.Pipe() + done := make(chan struct{}) + config := &RealityConfig{HandshakeTimeout: 100 * time.Millisecond, DialContext: func(context.Context, string, string) (net.Conn, error) { return target, nil }} + go func() { defer close(done); RealityServer(context.Background(), server, config) }() + defer func() { client.Close(); peer.Close(); <-done }() + go func() { + defer peer.Close() + for n := 0; n < 2; n++ { + var data [5]byte + if _, err := io.ReadFull(peer, data[:]); err != nil { + return + } + if _, err := peer.Write(data[:]); err != nil { + return + } + } + }() + client.SetDeadline(time.Now().Add(2 * time.Second)) + for n := 0; n < 2; n++ { + if n == 1 { + time.Sleep(200 * time.Millisecond) + } + if _, err := client.Write([]byte("hello")); err != nil { + t.Fatal(err) + } + var data [5]byte + if _, err := io.ReadFull(client, data[:]); err != nil { + t.Fatal(err) + } + if string(data[:]) != "hello" { + t.Fatal("fallback changed bytes") + } + } +} + +func TestRealityMirrorHonorsReadDeadline(t *testing.T) { + a, b := net.Pipe() + defer a.Close() + defer b.Close() + x, y := net.Pipe() + defer x.Close() + defer y.Close() + m := &realityMirrorConn{Mutex: new(sync.Mutex), Conn: a, Target: x} + if err := m.SetReadDeadline(time.Now()); err != nil { + t.Fatal(err) + } + m.Lock() + _, err := m.Read(make([]byte, 1)) + m.Unlock() + if timeout, ok := err.(net.Error); !ok || !timeout.Timeout() { + t.Fatalf("expected timeout, got %v", err) + } +} + +func TestRealityFallbackFreeThresholdIsExact(t *testing.T) { + raw := &bytesConn{Reader: bytes.NewReader(bytes.Repeat([]byte{'x'}, 32))} + c := &rateLimitedConn{Conn: raw, After: 3, Bucket: ratelimit.NewBucketWithRate(1e9, 32)} + buffer := make([]byte, 32) + if n, err := c.Read(buffer); n != 3 || err != nil { + t.Fatalf("free read crossed threshold: %d, %v", n, err) + } + if c.After != 0 { + t.Fatal("invalid remaining free budget") + } + if n, err := c.Read(buffer); n != 29 || err != nil { + t.Fatalf("limited read: %d, %v", n, err) + } +} + +type bytesConn struct{ *bytes.Reader } + +func (*bytesConn) Write(p []byte) (int, error) { return len(p), nil } +func (*bytesConn) Close() error { return nil } +func (*bytesConn) LocalAddr() net.Addr { return nil } +func (*bytesConn) RemoteAddr() net.Addr { return nil } +func (*bytesConn) SetDeadline(time.Time) error { return nil } +func (*bytesConn) SetReadDeadline(time.Time) error { return nil } +func (*bytesConn) SetWriteDeadline(time.Time) error { return nil } + +func TestRealityPrivateKeyCacheFollowsCloneAndRotation(t *testing.T) { + c := &RealityConfig{PrivateKey: bytes.Repeat([]byte{1}, 32)} + first, err := c.realityPrivateKey() + if err != nil { + t.Fatal(err) + } + clone := c.Clone() + again, err := clone.realityPrivateKey() + if err != nil || again != first { + t.Fatal("clone did not share cached key") + } + clone.PrivateKey = bytes.Repeat([]byte{2}, 32) + rotated, err := clone.realityPrivateKey() + if err != nil || rotated == first { + t.Fatal("rotated clone retained old key") + } + if !bytes.Equal(rotated.Bytes(), clone.PrivateKey) { + t.Fatal("wrong private key after rotation") + } + if original, _ := c.realityPrivateKey(); original != first { + t.Fatal("rotation changed original config") + } +} + +func TestRealityLogsOmitAuthenticationMaterial(t *testing.T) { + target := realityTestBigTarget(t, 8000) + config, pub := newRealityTestConfig(t, target.addr()) + var mu sync.Mutex + var output strings.Builder + config.Log = func(format string, args ...any) { mu.Lock(); defer mu.Unlock(); fmt.Fprintf(&output, format, args...) } + addr := newRealityTestServer(t, config) + conn, _ := realityTestDialShares(t, addr, pub, []CurveID{X25519MLKEM768, X25519}) + defer conn.Close() + mu.Lock() + defer mu.Unlock() + if strings.Contains(output.String(), "AuthKey") || strings.Contains(output.String(), "ClientShortId") { + t.Fatal("authentication material logged") + } +} + +func BenchmarkRealityECDH(b *testing.B) { + c := &RealityConfig{PrivateKey: bytes.Repeat([]byte{1}, 32)} + key, _ := c.realityPrivateKey() + peerBytes := key.PublicKey().Bytes() + b.Run("uncached", func(b *testing.B) { + b.ReportAllocs() + for n := 0; n < b.N; n++ { + if _, err := curve25519.X25519(c.PrivateKey, peerBytes); err != nil { + b.Fatal(err) + } + } + }) + b.Run("cached", func(b *testing.B) { + b.ReportAllocs() + for n := 0; n < b.N; n++ { + k, _ := c.realityPrivateKey() + peer, err := ecdh.X25519().NewPublicKey(peerBytes) + if err != nil { + b.Fatal(err) + } + if _, err := k.ECDH(peer); err != nil { + b.Fatal(err) + } + } + }) +} From 9c481dd0134be5084407e3c02c6ffd09fe21936e Mon Sep 17 00:00:00 2001 From: Nemu-x Date: Tue, 20 Oct 2026 20:19:24 +0300 Subject: [PATCH 2/2] fix(reality): release hosting handshake guards on fallback --- reality_guard.go | 3 +++ reality_guard_test.go | 14 +++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/reality_guard.go b/reality_guard.go index b6308eebb5..e40f7a4bea 100644 --- a/reality_guard.go +++ b/reality_guard.go @@ -67,6 +67,9 @@ func guardRealityHandshake(ctx context.Context, conn, target net.Conn, timeout t close(stopped) timer.Stop() _ = conn.SetReadDeadline(time.Time{}) + if notifier, ok := conn.(interface{ HandshakeComplete() }); ok { + notifier.HandshakeComplete() + } }) } } diff --git a/reality_guard_test.go b/reality_guard_test.go index 66cc1161a5..919e865ae9 100644 --- a/reality_guard_test.go +++ b/reality_guard_test.go @@ -9,6 +9,7 @@ import ( "net" "strings" "sync" + "sync/atomic" "testing" "time" @@ -51,10 +52,11 @@ func TestRealitySilentHandshakeTimesOut(t *testing.T) { func TestRealityFallbackOutlivesHandshakeTimeout(t *testing.T) { client, server := net.Pipe() + notifier := &realityHandshakeNotifier{Conn: server} target, peer := net.Pipe() done := make(chan struct{}) config := &RealityConfig{HandshakeTimeout: 100 * time.Millisecond, DialContext: func(context.Context, string, string) (net.Conn, error) { return target, nil }} - go func() { defer close(done); RealityServer(context.Background(), server, config) }() + go func() { defer close(done); RealityServer(context.Background(), notifier, config) }() defer func() { client.Close(); peer.Close(); <-done }() go func() { defer peer.Close() @@ -83,9 +85,19 @@ func TestRealityFallbackOutlivesHandshakeTimeout(t *testing.T) { if string(data[:]) != "hello" { t.Fatal("fallback changed bytes") } + if notifier.calls.Load() != 1 { + t.Fatal("fallback did not release the hosting listener's handshake guard exactly once") + } } } +type realityHandshakeNotifier struct { + net.Conn + calls atomic.Int32 +} + +func (c *realityHandshakeNotifier) HandshakeComplete() { c.calls.Add(1) } + func TestRealityMirrorHonorsReadDeadline(t *testing.T) { a, b := net.Pipe() defer a.Close()