Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions handshake_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
57 changes: 57 additions & 0 deletions jls_verify_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
60 changes: 47 additions & 13 deletions reality.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"context"
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/ed25519"
"crypto/hmac"
"crypto/rand"
Expand All @@ -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"
)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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
}

Expand All @@ -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 {
Expand Down Expand Up @@ -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

Expand All @@ -424,7 +438,7 @@ func RealityServer(ctx context.Context, conn net.Conn, config *RealityConfig) (*
},
config: &config.Config,
},
ctx: context.Background(),
ctx: ctx,
},
Config: config,
}
Expand All @@ -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
}
Expand All @@ -446,17 +460,24 @@ 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 {
break
}
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)
Expand All @@ -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...)) &&
Expand All @@ -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)
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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)])
}
Expand Down Expand Up @@ -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() {
Expand Down
75 changes: 75 additions & 0 deletions reality_guard.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
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{})
if notifier, ok := conn.(interface{ HandshakeComplete() }); ok {
notifier.HandshakeComplete()
}
})
}
}
Loading
Loading