Files
3x-ui/internal/tuic/auth.go
T
Egor 0054e671f8 feat(tuic): implement native in-process Go TUIC v5 server (#6577)
* feat(tuic): implement native in-process Go TUIC v5 server

- Implement native TUIC v5 protocol server on pure Go using quic-go
- Bridge decrypted TCP/UDP traffic into Xray-core via loopback SOCKS5 inbound
- Support full Xray routing rules (geosite/geoip) and cascading outbounds
- Implement atomic per-client traffic accounting with TotalGB and ExpiryTime
- Add automatic legacy cleanup for older Rust tuic-server binaries, configs, and orphaned processes
- Eliminate external Rust tuic-server downloads from install/CI scripts

* fix(tuic): address traffic accounting, client reload, and socket lifecycle issues

* fix(service): update checkTuicSocksReverseConflict to use bindAddr for listenOverlaps

* fix(tuic): resolve traffic double-accounting, UDP fragmentation, and socket lifecycle issues

* feat(tuic): complete native Go integration and address audit findings

- Integrate an isolated QUIC fork pinned to a specific commit
- Preserve original QUIC dependencies for Xray, Hysteria and Gin
- Apply BBR, CUBIC and Reno to server connections and exported client profiles
- Bridge Xray BBR with correct monotonic time and congestion type conversions
- Handle congestion sender recreation after PMTU changes
- Update congestion control for new connections without restarting the listener
- Preserve existing connections and their selected congestion controller
- Apply per-inbound log levels through the shared panel logger
- Add lifecycle, authentication and TCP/UDP relay events without exposing secrets
- Rate-limit repeated authentication and relay warnings
- Support native and QUIC UDP relay modes on the same listener
- Recover UDP associations after relay worker failures
- Fix TCP relay cancellation, idle shutdown and half-close handling
- Close active sessions when client credentials are revoked or disabled
- Track traffic by immutable client statistics IDs across email and UUID changes
- Prevent ambiguous accounting and duplicate UUIDs within TUIC inbounds
- Persist pending traffic in a durable shutdown journal
- Replay journal batches transactionally without duplicate accounting
- Report server shutdown failures through the shared logger
- Preserve legacy flat and nested TUIC settings compatibility
- Normalize congestion controller values consistently across backend and frontend
- Preserve controller, UDP mode and SNI in client links and subscriptions
- Separate client profile options from server settings in the TUIC form
- Keep certificate path autofill explicit when changing client SNI
- Align UDP packet size validation with protocol limits
- Simplify and localize TUIC field hints and certificate autofill messages
- Add controller, TCP/UDP, logging and live settings update tests
- Add accounting identity, journal replay and shutdown regression tests
- Add relay recovery, session revocation and legacy frontend form tests

* fix(service): alias the TUIC duplicate-UUID subquery for PostgreSQL < 16

syncInboundClients runs a COUNT(*) FROM (subquery) for every client sync,
whatever the protocol. PostgreSQL before 16 rejects a FROM subquery with
no alias, so on the distro PostgreSQL install.sh provisions (14 on Ubuntu
22.04, 15 on Debian 12) every client add or edit failed with SQLSTATE
42601. Reproduced against postgres:15 with the new env-gated test.

* fix(database): create tuic_traffic_receipts through the model migration

AddTuicTrafficBatch issued CREATE TABLE IF NOT EXISTS at runtime, a schema
change outside db.go. The table was invisible to allModels and
migrationModels, so x-ui migrate-db dropped the receipts and a retained
journal could be counted twice after a SQLite to PostgreSQL move. It is
now a GORM model in both lists, and the insert uses OnConflict DoNothing.

* chore(tuic): skip the ICMP-dependent relay test on Windows, drop dead collectors

Go disables SIO_UDP_CONNRESET on Windows, so a dead UDP bridge never fails
a read there and TestAudit3UDPAssociationMustRecoverAfterBridgeReadFailure
was red on every Windows run. Server.CollectTotalTraffic and
Manager.CollectTraffic had no caller.

* refactor(tuic): serve TUIC on apernet/quic-go instead of a personal fork

The native server depended on github.com/poise52/quic-go, a personal fork
of apernet/quic-go patched only to pick the congestion controller before
the handshake. That put a second QUIC/TLS stack in the binary that no
upstream security fix reaches. apernet/quic-go is already in the graph
through xray-core and exposes SetCongestionControl, so BBR is now installed
on each accepted connection with Xray's own congestion.UseBBR; the
cross-module BBR adapter is gone.

apernet ships New Reno as its only built-in sender, so a cubic setting is
served as new_reno server-side (clients still get cubic in their profile).
The test inspectors now read the sender under congestionMutex, which the
post-handshake install writes under.

Linux loopback, single stream through Xray: 2428 -> 3383 Mbit/s (bbr).

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-10-03 02:56:02 +02:00

221 lines
5.7 KiB
Go

package tuic
import (
"crypto/subtle"
"crypto/tls"
"errors"
"fmt"
"sync"
"sync/atomic"
"github.com/google/uuid"
)
var (
ErrUserNotFound = errors.New("tuic: user not found")
ErrAuthFailed = errors.New("tuic: authentication failed")
ErrInvalidTLSState = errors.New("tuic: TLS connection state not available")
)
// User represents a configured TUIC client for authentication and billing.
type User struct {
TrafficID int
UUID [16]byte
UUIDStr string
Password string
Email string
Traffic *UserTraffic
sessions atomic.Int64
}
type UserTraffic struct {
BytesUp atomic.Int64
BytesDown atomic.Int64
}
// UserRegistry is a thread-safe registry of TUIC users for an inbound.
type UserRegistry struct {
mu sync.RWMutex
users map[[16]byte]*User
retired map[*User]struct{}
}
// NewUserRegistry creates an empty UserRegistry.
func NewUserRegistry() *UserRegistry {
return &UserRegistry{
users: make(map[[16]byte]*User),
retired: make(map[*User]struct{}),
}
}
// SetUsers updates the user list atomically in memory, preserving counters and
// pointer stability for active sessions. It returns any users removed from the registry.
func (ur *UserRegistry) SetUsers(clients []TuicClientSettings) (revoked []*User) {
ur.mu.Lock()
defer ur.mu.Unlock()
newMap := make(map[[16]byte]*User, len(clients))
for _, c := range clients {
parsed, err := uuid.Parse(c.UUID)
if err != nil {
continue
}
if existing, ok := ur.users[parsed]; ok && existing.Password == c.Password && existing.Email == c.Email && existing.TrafficID == c.TrafficID {
newMap[parsed] = existing
} else if ok {
ur.retired[existing] = struct{}{}
revoked = append(revoked, existing)
newMap[parsed] = newUser(parsed, c)
} else {
newMap[parsed] = newUser(parsed, c)
}
}
for id, oldUser := range ur.users {
if _, ok := newMap[id]; !ok {
revoked = append(revoked, oldUser)
ur.retired[oldUser] = struct{}{}
}
}
ur.users = newMap
return revoked
}
func newUser(id [16]byte, c TuicClientSettings) *User {
return &User{
TrafficID: c.TrafficID, UUID: id, UUIDStr: uuid.UUID(id).String(), Password: c.Password, Email: c.Email,
Traffic: &UserTraffic{},
}
}
// AddTestTraffic adds traffic counters to a user by email for testing purposes.
func (ur *UserRegistry) AddTestTraffic(email string, up, down int64) bool {
ur.mu.RLock()
defer ur.mu.RUnlock()
for _, u := range ur.users {
if u.Email == email {
u.Traffic.BytesUp.Add(up)
u.Traffic.BytesDown.Add(down)
return true
}
}
return false
}
// ClientTrafficDelta represents the traffic delta for a user.
type ClientTrafficDelta struct {
TrafficID int
Email string
UUID string
InboundID int
Up int64
Down int64
}
// CollectTrafficDeltas drains and returns byte deltas for all users since the last call.
func (ur *UserRegistry) CollectTrafficDeltas() []ClientTrafficDelta {
ur.mu.Lock()
defer ur.mu.Unlock()
var deltas []ClientTrafficDelta
collect := func(u *User, retired bool) {
up := u.Traffic.BytesUp.Swap(0)
down := u.Traffic.BytesDown.Swap(0)
if up > 0 || down > 0 {
deltas = append(deltas, ClientTrafficDelta{
TrafficID: u.TrafficID,
Email: u.Email,
UUID: u.UUIDStr,
Up: up,
Down: down,
})
}
if retired && u.sessions.Load() == 0 {
delete(ur.retired, u)
}
}
for _, u := range ur.users {
collect(u, false)
}
for u := range ur.retired {
collect(u, true)
}
return deltas
}
func (ur *UserRegistry) sessionEnded(user *User) {
if user != nil {
user.sessions.Add(-1)
}
}
// Authenticate verifies the client's token using RFC 5705 Keying Material Exporter.
// According to TUIC v5 specification:
// - label: client UUID
// - context: raw password
// - length: 32 bytes
func (ur *UserRegistry) Authenticate(cs *tls.ConnectionState, rawUUID [16]byte, token [32]byte) (*User, error) {
return ur.authenticate(cs, rawUUID, token, nil)
}
// AuthenticateAndRegister holds the registry read lock through connection
// registration, making successful authentication atomic with user revocation.
func (ur *UserRegistry) AuthenticateAndRegister(cs *tls.ConnectionState, rawUUID [16]byte, token [32]byte, register func(*User) bool) (*User, error) {
return ur.authenticate(cs, rawUUID, token, register)
}
func (ur *UserRegistry) authenticate(cs *tls.ConnectionState, rawUUID [16]byte, token [32]byte, register func(*User) bool) (*User, error) {
if cs == nil {
return nil, ErrInvalidTLSState
}
ur.mu.RLock()
defer ur.mu.RUnlock()
user, exists := ur.users[rawUUID]
if !exists {
return nil, ErrUserNotFound
}
if !cs.HandshakeComplete {
return nil, ErrInvalidTLSState
}
// Try with raw 16-byte UUID as label
expectedToken, err := cs.ExportKeyingMaterial(string(rawUUID[:]), []byte(user.Password), 32)
if err == nil && subtle.ConstantTimeCompare(token[:], expectedToken) == 1 {
if register != nil && !register(user) {
return nil, ErrUserNotFound
}
return user, nil
}
// Fallback to formatted 36-char string representation of UUID as label
expectedTokenStr, errStr := cs.ExportKeyingMaterial(user.UUIDStr, []byte(user.Password), 32)
if errStr == nil && subtle.ConstantTimeCompare(token[:], expectedTokenStr) == 1 {
if register != nil && !register(user) {
return nil, ErrUserNotFound
}
return user, nil
}
if err != nil && errStr != nil {
return nil, fmt.Errorf("%w: export keying material: %w", ErrAuthFailed, err)
}
return nil, ErrAuthFailed
}
func ValidateClients(clients []TuicClientSettings) error {
seen := make(map[uuid.UUID]bool, len(clients))
for _, client := range clients {
id, err := uuid.Parse(client.UUID)
if err != nil {
return errors.New("tuic: invalid client UUID")
}
if seen[id] {
return errors.New("tuic: duplicate client UUID")
}
seen[id] = true
}
return nil
}