Compare commits

..
7 Commits
32 changed files with 2167 additions and 201 deletions
+3
View File
@@ -112,6 +112,7 @@
- [GenyConnect](https://github.com/genyleap/GenyConnect) - [GenyConnect](https://github.com/genyleap/GenyConnect)
- [OneXray](https://github.com/OneXray/OneXray) - [OneXray](https://github.com/OneXray/OneXray)
- [XrayUI-dev](https://github.com/PhoenixNil/XrayUI-dev) - [XrayUI-dev](https://github.com/PhoenixNil/XrayUI-dev)
- [keqdroid](https://github.com/Lemonochka/keqdroid)
- Android - Android
- [v2rayNG](https://github.com/2dust/v2rayNG) - [v2rayNG](https://github.com/2dust/v2rayNG)
- [X-flutter](https://github.com/XTLS/X-flutter) - [X-flutter](https://github.com/XTLS/X-flutter)
@@ -121,6 +122,7 @@
- [AnyPortal](https://github.com/AnyPortal/AnyPortal) - [AnyPortal](https://github.com/AnyPortal/AnyPortal)
- [OneXray](https://github.com/OneXray/OneXray) - [OneXray](https://github.com/OneXray/OneXray)
- [AsteriskNG](https://github.com/Asterisk4Magisk/AsteriskNG) - [AsteriskNG](https://github.com/Asterisk4Magisk/AsteriskNG)
- [keqdroid](https://github.com/Lemonochka/keqdroid)
- iOS & macOS arm64 & tvOS - iOS & macOS arm64 & tvOS
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274) - [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
- [Streisand](https://apps.apple.com/app/streisand/id6450534064) - [Streisand](https://apps.apple.com/app/streisand/id6450534064)
@@ -146,6 +148,7 @@
- [v2rayN](https://github.com/2dust/v2rayN) - [v2rayN](https://github.com/2dust/v2rayN)
- [GenyConnect](https://github.com/genyleap/GenyConnect) - [GenyConnect](https://github.com/genyleap/GenyConnect)
- [OneXray](https://github.com/OneXray/OneXray) - [OneXray](https://github.com/OneXray/OneXray)
- [keqdroid](https://github.com/Lemonochka/keqdroid)
- HarmonyOS - HarmonyOS
- [Hey](https://github.com/popsiclelmlm/Hey) - [Hey](https://github.com/popsiclelmlm/Hey)
+22 -19
View File
@@ -181,26 +181,29 @@ func (h *Handler) Tag() string {
func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) { func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
outbounds := session.OutboundsFromContext(ctx) outbounds := session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1] ob := outbounds[len(outbounds)-1]
content := session.ContentFromContext(ctx) if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() {
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() && (content == nil || !content.SkipDNSResolve) { if session.SkipDNSResolveFromContext(ctx) {
strategy := h.senderSettings.TargetStrategy errors.LogInfo(ctx, "bypassing targetStrategy ", h.senderSettings.TargetStrategy, " for ", ob.Target, "; preserving target domain")
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
}
ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
if err != nil {
errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
if h.senderSettings.TargetStrategy.ForceIP() {
err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
session.SubmitOutboundErrorToOriginator(ctx, err)
common.Interrupt(link.Writer)
common.Interrupt(link.Reader)
return
}
} else { } else {
unchangedDomain := ob.Target.Address.Domain() strategy := h.senderSettings.TargetStrategy
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))]) if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil {
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String()) strategy = strategy.GetDynamicStrategy(ob.OriginalTarget.Address.Family())
}
ips, err := internet.LookupForIP(ob.Target.Address.Domain(), strategy, nil)
if err != nil {
errors.LogInfoInner(ctx, err, "failed to resolve ip for target ", ob.Target.Address.Domain())
if h.senderSettings.TargetStrategy.ForceIP() {
err := errors.New("failed to resolve ip for target ", ob.Target.Address.Domain()).Base(err)
session.SubmitOutboundErrorToOriginator(ctx, err)
common.Interrupt(link.Writer)
common.Interrupt(link.Reader)
return
}
} else {
unchangedDomain := ob.Target.Address.Domain()
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
errors.LogInfo(ctx, "target: ", unchangedDomain, " resolved to: ", ob.Target.Address.String())
}
} }
} }
if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address { if ob.Target.Network == net.Network_UDP && ob.OriginalTarget.Address != nil && ob.OriginalTarget.Address != ob.Target.Address {
+1
View File
@@ -91,6 +91,7 @@ func (b *Bridge) monitor() error {
} }
func (b *Bridge) Start() error { func (b *Bridge) Start() error {
b.monitor()
return b.monitorTask.Start() return b.monitorTask.Start()
} }
+2 -3
View File
@@ -44,9 +44,8 @@ func (c routingContext) GetRuleTag() string {
return "" return ""
} }
// GetSkipDNSResolve is a mock implementation here to match the interface, // GetSkipDNSResolve implements routing.Context.
// SkipDNSResolve is set from dns module, no use if coming from a protobuf object? // The protobuf RoutingContext has no skip flag, so API contexts use false.
// TODO: please confirm @Vigilans
func (c routingContext) GetSkipDNSResolve() bool { func (c routingContext) GetSkipDNSResolve() bool {
return false return false
} }
+1 -1
View File
@@ -23,7 +23,7 @@ func RegisterLua(L *lua.LState) {
return 0 return 0
} }
xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{ xlua.PushWithDirectMethods(L, matcher, map[string]xlua.DirectMethod{
"Match": newLuaDomainMatch(xlua.NewReadOnlySlicePusher[uint32](L)), "Match": newLuaDomainMatch(xlua.NewSlicePusher[uint32](L)),
"MatchAny": luaDomainMatchAny, "MatchAny": luaDomainMatchAny,
}) })
return 1 return 1
+1 -3
View File
@@ -104,9 +104,7 @@ for _, value in ipairs({matcher, domain}) do
assert(not pcall(function() return value ^ {} end)) assert(not pcall(function() return value ^ {} end))
end end
assert(domain:matchAny("example.com")) assert(domain:matchAny("example.com"))
local indices = domain:Match("example.com") assert(#domain:Match("example.com") == 1)
assert(#indices == 1)
assert(not pcall(function() indices[1] = 7 end))
assert(domain:match("example.com")[1] == 0) assert(domain:match("example.com")[1] == 0)
assert(not pcall(function() matcher:AnyMatch() end)) assert(not pcall(function() matcher:AnyMatch() end))
assert(not pcall(function() matcher:AnyMatch(matched, true) end)) assert(not pcall(function() matcher:AnyMatch(matched, true) end))
+3 -3
View File
@@ -8,10 +8,10 @@ import (
luar "layeh.com/gopher-luar" luar "layeh.com/gopher-luar"
) )
// newSlicePusher captures luar's slice metatable during state initialization. // NewSlicePusher captures luar's slice metatable during state initialization.
// The returned function wraps slices without reflection or metatable lookup, // The returned function wraps slices without reflection or metatable lookup,
// and pushes nil for nil slices. Use it with this state or its coroutines. // and pushes nil for nil slices. Use it with this state or its coroutines.
func newSlicePusher[T any](L *glua.LState) func(*glua.LState, []T) { func NewSlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
metatable := luar.MT(L, []T(nil)).LTable metatable := luar.MT(L, []T(nil)).LTable
return func(L *glua.LState, values []T) { return func(L *glua.LState, values []T) {
if values == nil { if values == nil {
@@ -38,7 +38,7 @@ func NewReadOnlySlicePusher[T any](L *glua.LState) func(*glua.LState, []T) {
}) })
setSliceReadOnly[[]T](L, readOnly) setSliceReadOnly[[]T](L, readOnly)
} }
return newSlicePusher[T](L) return NewSlicePusher[T](L)
} }
func setSliceReadOnly[S ~[]E, E any](L *glua.LState, readOnly *glua.LFunction) { func setSliceReadOnly[S ~[]E, E any](L *glua.LState, readOnly *glua.LFunction) {
+43 -21
View File
@@ -9,20 +9,53 @@ import (
luar "layeh.com/gopher-luar" luar "layeh.com/gopher-luar"
) )
func TestReadOnlySlicePusher(t *testing.T) { func TestSlicePusher(t *testing.T) {
L := glua.NewState() L := glua.NewState()
defer L.Close() defer L.Close()
push := NewReadOnlySlicePusher[int](L) push := NewSlicePusher[int](L)
values := []int{3, 5} values := []int{3, 5}
L.SetGlobal("getValues", L.NewFunction(func(L *glua.LState) int { L.SetGlobal("getValues", L.NewFunction(func(L *glua.LState) int {
push(L, values) push(L, values)
return 1 return 1
})) }))
if err := L.DoString(` if err := L.DoString(`
local co = coroutine.create(function() return getValues() end) local values = getValues()
assert(#values == 2 and values[1] == 3 and values[2] == 5)
values[2] = 7
local co = coroutine.create(function()
local values = getValues()
assert(#values == 2 and values[1] == 3 and values[2] == 7)
return true
end)
local ok, result = coroutine.resume(co) local ok, result = coroutine.resume(co)
assert(ok, result) assert(ok and result == true)
values = result `); err != nil {
t.Fatal(err)
}
if values[1] != 7 {
t.Fatal("slice storage was copied")
}
push(L, nil)
if L.Get(-1) != glua.LNil {
t.Fatal("nil slice must push Lua nil")
}
L.Pop(1)
push(L, []int{})
L.SetGlobal("empty", L.Get(-1))
L.Pop(1)
if err := L.DoString(`assert(type(empty) == "userdata" and #empty == 0)`); err != nil {
t.Fatal(err)
}
}
func TestReadOnlySlicePusher(t *testing.T) {
L := glua.NewState()
defer L.Close()
values := []int{3, 5}
NewReadOnlySlicePusher[int](L)(L, values)
L.SetGlobal("values", L.Get(-1))
L.Pop(1)
if err := L.DoString(`
assert(#values == 2 and values[1] == 3 and values[2] == 5) assert(#values == 2 and values[1] == 3 and values[2] == 5)
assert(not pcall(function() values[1] = 7 end)) assert(not pcall(function() values[1] = 7 end))
assert(not pcall(function() return values + 7 end)) assert(not pcall(function() return values + 7 end))
@@ -36,17 +69,6 @@ assert(sum == 8)
if &got[0] != &values[0] || values[0] != 3 || values[1] != 5 { if &got[0] != &values[0] || values[0] != 3 || values[1] != 5 {
t.Fatal("read-only binding copied or modified the slice") t.Fatal("read-only binding copied or modified the slice")
} }
push(L, nil)
if L.Get(-1) != glua.LNil {
t.Fatal("nil slice must push Lua nil")
}
L.Pop(1)
push(L, []int{})
L.SetGlobal("empty", L.Get(-1))
L.Pop(1)
if err := L.DoString(`assert(type(empty) == "userdata" and #empty == 0)`); err != nil {
t.Fatal(err)
}
} }
func TestReadOnlyIPSlicePusher(t *testing.T) { func TestReadOnlyIPSlicePusher(t *testing.T) {
@@ -208,23 +230,23 @@ assert(not pcall(function() return nested + nested end))
} }
} }
func TestReadOnlySlicePusherMetatablePerState(t *testing.T) { func TestSlicePusherMetatablePerState(t *testing.T) {
first := glua.NewState() first := glua.NewState()
defer first.Close() defer first.Close()
second := glua.NewState() second := glua.NewState()
defer second.Close() defer second.Close()
NewReadOnlySlicePusher[int](first)(first, []int{1}) NewSlicePusher[int](first)(first, []int{1})
NewReadOnlySlicePusher[int](second)(second, []int{1}) NewSlicePusher[int](second)(second, []int{1})
if first.Get(-1).(*glua.LUserData).Metatable == second.Get(-1).(*glua.LUserData).Metatable { if first.Get(-1).(*glua.LUserData).Metatable == second.Get(-1).(*glua.LUserData).Metatable {
t.Fatal("independent states share a slice metatable") t.Fatal("independent states share a slice metatable")
} }
} }
func BenchmarkReadOnlySlicePusher(b *testing.B) { func BenchmarkSlicePusher(b *testing.B) {
L := glua.NewState() L := glua.NewState()
defer L.Close() defer L.Close()
ips := []net.IP{net.ParseIP("127.0.0.1")} ips := []net.IP{net.ParseIP("127.0.0.1")}
pushIPs := NewReadOnlySlicePusher[net.IP](L) pushIPs := NewSlicePusher[net.IP](L)
for _, benchmark := range []struct { for _, benchmark := range []struct {
name string name string
push func(*glua.LState, []net.IP) push func(*glua.LState, []net.IP)
+4 -2
View File
@@ -671,7 +671,7 @@ string.__tostring = nil
L.SetGlobal("testNativeError", L.Get(-1)) L.SetGlobal("testNativeError", L.Get(-1))
L.Pop(1) L.Pop(1)
L.SetGlobal("testGoStruct", luar.New(L, &struct{ Value string }{"readable field"})) L.SetGlobal("testGoStruct", luar.New(L, &struct{ Value string }{"readable field"}))
NewReadOnlySlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")}) NewSlicePusher[net.IP](L)(L, []net.IP{net.ParseIP("192.0.2.1")})
L.SetGlobal("testIPs", L.Get(-1)) L.SetGlobal("testIPs", L.Get(-1))
L.Pop(1) L.Pop(1)
userdata := L.NewUserData() userdata := L.NewUserData()
@@ -865,7 +865,9 @@ assert(not ok and a == "{<address> <address>}")
PushUserData(L, struct{ Pointer *int }{&target}) PushUserData(L, struct{ Pointer *int }{&target})
L.SetGlobal("testObject", L.Get(-1)) L.SetGlobal("testObject", L.Get(-1))
L.Pop(1) L.Pop(1)
L.SetGlobal("testValues", luar.New(L, []int{1})) NewSlicePusher[int](L)(L, []int{1})
L.SetGlobal("testValues", L.Get(-1))
L.Pop(1)
L.SetGlobal("testPanic", L.NewFunction(func(L *glua.LState) int { L.SetGlobal("testPanic", L.NewFunction(func(L *glua.LState) int {
panic(struct{ First, Second *int }{&target, &target}) panic(struct{ First, Second *int }{&target, &target})
})) }))
+5
View File
@@ -77,6 +77,11 @@ func ContentFromContext(ctx context.Context) *Content {
return nil return nil
} }
func SkipDNSResolveFromContext(ctx context.Context) bool {
content := ContentFromContext(ctx)
return content != nil && content.SkipDNSResolve
}
func ContextWithIsReverseMux(ctx context.Context, isReverseMux bool) context.Context { func ContextWithIsReverseMux(ctx context.Context, isReverseMux bool) context.Context {
return context.WithValue(ctx, isReverseMuxKey, isReverseMux) return context.WithValue(ctx, isReverseMuxKey, isReverseMux)
} }
-1
View File
@@ -71,7 +71,6 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
} }
common.CloseIfExists(t.checkTask) common.CloseIfExists(t.checkTask)
t.checkTask = newCheckTask t.checkTask = newCheckTask
t.Update()
common.Must(newCheckTask.Start()) common.Must(newCheckTask.Start())
} }
+3 -7
View File
@@ -58,15 +58,11 @@ func (t *Periodic) Start() error {
return nil return nil
} }
t.running = true t.running = true
t.timer = time.AfterFunc(t.Interval, func() {
t.checkedExecute()
})
t.access.Unlock() t.access.Unlock()
if err := t.checkedExecute(); err != nil {
t.access.Lock()
t.running = false
t.access.Unlock()
return err
}
return nil return nil
} }
+6 -6
View File
@@ -20,17 +20,17 @@ func TestPeriodicTaskStop(t *testing.T) {
common.Must(task.Start()) common.Must(task.Start())
time.Sleep(time.Second * 5) time.Sleep(time.Second * 5)
common.Must(task.Close()) common.Must(task.Close())
if value != 3 { if value != 2 {
t.Fatal("expected 3, but got ", value) t.Fatal("expected 2, but got ", value)
} }
time.Sleep(time.Second * 4) time.Sleep(time.Second * 4)
if value != 3 { if value != 2 {
t.Fatal("expected 3, but got ", value) t.Fatal("expected 2, but got ", value)
} }
common.Must(task.Start()) common.Must(task.Start())
time.Sleep(time.Second * 3) time.Sleep(time.Second * 3)
if value != 5 { if value != 3 {
t.Fatal("Expected 5, but ", value) t.Fatal("Expected 3, but ", value)
} }
common.Must(task.Close()) common.Must(task.Close())
} }
+92 -18
View File
@@ -2,6 +2,8 @@ package conf
import ( import (
"context" "context"
"crypto/rand"
"crypto/rsa"
"crypto/x509" "crypto/x509"
"encoding/base64" "encoding/base64"
"encoding/hex" "encoding/hex"
@@ -961,10 +963,11 @@ func (c *XDNS) Build() (proto.Message, error) {
} }
type XMC struct { type XMC struct {
Hostname string `json:"hostname"` Hostname string `json:"hostname"`
Profiles []XMCProfile `json:"profiles"` Profiles []XMCProfile `json:"profiles"`
Password string `json:"password"` Password string `json:"password"`
Paddings []XMCPaddingTurn `json:"paddings,omitempty"` Paddings []XMCPaddingTurn `json:"paddings,omitempty"`
Yggdrasil *XMCYggdrasil `json:"yggdrasil,omitempty"`
// A configured list is the complete padding schedule and replaces the // A configured list is the complete padding schedule and replaces the
// built-in preset entirely, including the preset's Play-state join tail. // built-in preset entirely, including the preset's Play-state join tail.
// NoPadding disables padding. An explicit empty "paddings" array means the // NoPadding disables padding. An explicit empty "paddings" array means the
@@ -982,6 +985,19 @@ type XMCPaddingTurn struct {
Delay string `json:"delay,omitempty"` Delay string `json:"delay,omitempty"`
} }
// XMCYggdrasil enables third-party login through a Yggdrasil API server such
// as Blessing Skin. The client authenticates with the API and the server
// verifies players through its hasJoined endpoint.
type XMCYggdrasil struct {
// API root of the Yggdrasil API, for example
// https://skin.example.com/api/yggdrasil
API string `json:"api"`
Username string `json:"username"`
Password string `json:"password"`
// Optional player name, required when the account owns several players.
Player string `json:"player"`
}
type XMCProfile struct { type XMCProfile struct {
// Resolve the UUID by username, then request the session profile with // Resolve the UUID by username, then request the session profile with
// unsigned=false. Client and server must use the same signed profile. // unsigned=false. Client and server must use the same signed profile.
@@ -1015,16 +1031,6 @@ func (c *XMCProfile) Build() (*xmc.Profile, error) {
} }
func (c *XMC) Build() (proto.Message, error) { func (c *XMC) Build() (proto.Message, error) {
if len(c.Profiles) == 0 {
return nil, fmt.Errorf("minecraft profiles are required")
}
if c.Password == "" {
return nil, fmt.Errorf("empty password")
}
if len(c.Password) > xmc.MaxLegacyPasswordLength {
return nil, fmt.Errorf("minecraft password is longer than %d bytes", xmc.MaxLegacyPasswordLength)
}
// An explicit empty array is different from an absent field: json leaves // An explicit empty array is different from an absent field: json leaves
// Paddings nil when it is absent, so the user can turn padding off without // Paddings nil when it is absent, so the user can turn padding off without
// a second switch. // a second switch.
@@ -1032,7 +1038,7 @@ func (c *XMC) Build() (proto.Message, error) {
if noPadding && len(c.Paddings) > 0 { if noPadding && len(c.Paddings) > 0 {
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive") return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
} }
config := &xmc.Config{Password: c.Password, Hostname: c.Hostname, NoPadding: noPadding} config := &xmc.Config{Hostname: c.Hostname, NoPadding: noPadding}
for i, turn := range c.Paddings { for i, turn := range c.Paddings {
minimum, maximum, err := ParseRangeString(turn.Length) minimum, maximum, err := ParseRangeString(turn.Length)
if err != nil { if err != nil {
@@ -1065,9 +1071,75 @@ func (c *XMC) Build() (proto.Message, error) {
return nil, fmt.Errorf("minecraft padding: %w", err) return nil, fmt.Errorf("minecraft padding: %w", err)
} }
rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password) var yggdrasil *xmc.Yggdrasil
if err != nil { if c.Yggdrasil != nil {
return nil, fmt.Errorf("derive minecraft rsa key: %w", err) if c.Yggdrasil.API == "" {
return nil, fmt.Errorf("empty minecraft yggdrasil api")
}
apiURL, err := url.Parse(c.Yggdrasil.API)
if err != nil {
return nil, fmt.Errorf("invalid minecraft yggdrasil api: %w", err)
}
if apiURL.Scheme != "http" && apiURL.Scheme != "https" {
return nil, fmt.Errorf("invalid minecraft yggdrasil api scheme: %q", apiURL.Scheme)
}
if apiURL.Host == "" {
return nil, fmt.Errorf("invalid minecraft yggdrasil api: missing host")
}
if apiURL.RawQuery != "" || apiURL.Fragment != "" {
return nil, fmt.Errorf("invalid minecraft yggdrasil api: query and fragment are not allowed")
}
if (c.Yggdrasil.Username == "") != (c.Yggdrasil.Password == "") {
return nil, fmt.Errorf("minecraft yggdrasil username and password must be set together")
}
if c.Yggdrasil.Player != "" && !xmcUsernamePattern.MatchString(c.Yggdrasil.Player) {
return nil, fmt.Errorf("invalid minecraft yggdrasil player: %q", c.Yggdrasil.Player)
}
yggdrasil = &xmc.Yggdrasil{
Api: strings.TrimSuffix(c.Yggdrasil.API, "/"),
Username: c.Yggdrasil.Username,
Password: c.Yggdrasil.Password,
Player: c.Yggdrasil.Player,
}
} else if len(c.Profiles) == 0 {
return nil, fmt.Errorf("minecraft profiles are required")
}
var (
rsaPrivateKey *rsa.PrivateKey
password string
)
if yggdrasil != nil {
// Yggdrasil mode binds the transport through the session hash: the
// client joins with the server's actual public key and the server
// checks hasJoined. The key pair is therefore generated per process
// instead of being derived from the password.
generated, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
return nil, fmt.Errorf("generate minecraft rsa key: %w", err)
}
rsaPrivateKey = generated
warning := `XMC: Yggdrasil mode is enabled. The RSA key pair is generated randomly and "password" is no longer used to derive it or to authenticate the transport; players are verified through ` + yggdrasil.Api + ` (client /join, server /hasJoined). Both ends must be able to reach the Yggdrasil API.`
if c.Password != "" {
warning += ` The configured "password" is ignored.`
}
errors.LogWarning(context.Background(), warning)
} else {
if c.Password == "" {
return nil, fmt.Errorf("empty password")
}
if len(c.Password) > xmc.MaxLegacyPasswordLength {
return nil, fmt.Errorf("minecraft password is longer than %d bytes", xmc.MaxLegacyPasswordLength)
}
derived, err := xmc.DeriveRSAKey(c.Password)
if err != nil {
return nil, fmt.Errorf("derive minecraft rsa key: %w", err)
}
rsaPrivateKey = derived
password = c.Password
} }
rsaPublicKey, err := x509.MarshalPKIXPublicKey(&rsaPrivateKey.PublicKey) rsaPublicKey, err := x509.MarshalPKIXPublicKey(&rsaPrivateKey.PublicKey)
@@ -1084,9 +1156,11 @@ func (c *XMC) Build() (proto.Message, error) {
profiles = append(profiles, profile) profiles = append(profiles, profile)
} }
config.Password = password
config.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey) config.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey)
config.RsaPublicKey = rsaPublicKey config.RsaPublicKey = rsaPublicKey
config.Profiles = profiles config.Profiles = profiles
config.Yggdrasil = yggdrasil
return config, nil return config, nil
} }
@@ -1,6 +1,7 @@
package conf package conf
import ( import (
"crypto/x509"
"encoding/json" "encoding/json"
"strings" "strings"
"testing" "testing"
@@ -113,6 +114,96 @@ func TestXMCBuildRejectsLongPassword(t *testing.T) {
} }
} }
func TestXMCBuildYggdrasil(t *testing.T) {
built, err := (&XMC{
Password: "test-password",
Yggdrasil: &XMCYggdrasil{
API: "https://skin.example.com/api/yggdrasil/",
Username: "user@example.com",
Password: "login-password",
Player: "TestUser",
},
}).Build()
if err != nil {
t.Fatalf("build XMC config: %v", err)
}
config := built.(*xmc.Config)
if config.Yggdrasil == nil {
t.Fatal("yggdrasil config is missing")
}
if config.Yggdrasil.Api != "https://skin.example.com/api/yggdrasil" {
t.Fatalf("yggdrasil api = %q", config.Yggdrasil.Api)
}
if config.Yggdrasil.Username != "user@example.com" || config.Yggdrasil.Password != "login-password" || config.Yggdrasil.Player != "TestUser" {
t.Fatalf("unexpected yggdrasil config: %+v", config.Yggdrasil)
}
if config.Password != "" {
t.Fatalf("password must not be used in yggdrasil mode: %q", config.Password)
}
if len(config.RsaPrivateKey) == 0 || len(config.RsaPublicKey) == 0 {
t.Fatal("yggdrasil mode must build a random rsa key pair")
}
privateKey, err := x509.ParsePKCS1PrivateKey(config.RsaPrivateKey)
if err != nil {
t.Fatalf("parse generated rsa private key: %v", err)
}
publicKey, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
t.Fatalf("marshal generated rsa public key: %v", err)
}
if string(publicKey) != string(config.RsaPublicKey) {
t.Fatal("generated rsa key pair does not match")
}
}
func TestXMCBuildYggdrasilServerWithoutCredentials(t *testing.T) {
built, err := (&XMC{
Yggdrasil: &XMCYggdrasil{
API: "https://skin.example.com/api/yggdrasil",
},
}).Build()
if err != nil {
t.Fatalf("build server-side XMC config: %v", err)
}
if built.(*xmc.Config).Yggdrasil == nil {
t.Fatal("yggdrasil config is missing")
}
}
func TestXMCBuildRejectsInvalidYggdrasil(t *testing.T) {
cases := []*XMCYggdrasil{
{API: ""},
{API: "ftp://skin.example.com/api/yggdrasil"},
{API: "https://skin.example.com/api/yggdrasil?foo=bar"},
{API: "https://skin.example.com/api/yggdrasil", Username: "user@example.com"},
{API: "https://skin.example.com/api/yggdrasil", Password: "login-password"},
{API: "https://skin.example.com/api/yggdrasil", Player: "bad name"},
}
for i, yggdrasil := range cases {
_, err := (&XMC{Yggdrasil: yggdrasil}).Build()
if err == nil {
t.Fatalf("case %d was accepted: %+v", i, yggdrasil)
}
}
}
func TestXMCBuildRequiresPasswordInLegacyMode(t *testing.T) {
_, err := (&XMC{
Profiles: []XMCProfile{
{
Username: "TestUser",
UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value",
TexturesSignature: "textures-signature",
},
},
}).Build()
if err == nil || !strings.Contains(err.Error(), "empty password") {
t.Fatalf("expected empty password error, got %v", err)
}
}
func TestXMCBuildDisablesPadding(t *testing.T) { func TestXMCBuildDisablesPadding(t *testing.T) {
profile := XMCProfile{ profile := XMCProfile{
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff", Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
+5
View File
@@ -318,6 +318,7 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
} }
ob.Name = "freedom" ob.Name = "freedom"
ob.CanSpliceCopy = 1 ob.CanSpliceCopy = 1
if !h.usesDialerProxy && len(h.firewall) > 0 { if !h.usesDialerProxy && len(h.firewall) > 0 {
rule := h.firewall[0] rule := h.firewall[0]
if rule.action == RuleAction_Block && rule.network == allNetworks && len(rule.port) == 0 && rule.ip == nil { if rule.action == RuleAction_Block && rule.network == allNetworks && len(rule.port) == 0 && rule.ip == nil {
@@ -350,6 +351,10 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
} }
} }
if h.resolveStrategy.HasStrategy() && session.SkipDNSResolveFromContext(ctx) {
errors.LogInfo(ctx, "DNS-origin connection to ", destination, " may recursively resolve with sockopt.domainStrategy ", h.resolveStrategy)
}
input := link.Reader input := link.Reader
output := link.Writer output := link.Writer
+1 -1
View File
@@ -30,7 +30,7 @@ func (l *Loopback) Process(ctx context.Context, link *transport.Link, _ internet
errors.LogInfo(ctx, "opening connection to ", destination) errors.LogInfo(ctx, "opening connection to ", destination)
content := new(session.Content) content := new(session.Content)
content.SkipDNSResolve = true content.SkipDNSResolve = session.SkipDNSResolveFromContext(ctx)
content.SniffingRequest = l.sniffingRequest content.SniffingRequest = l.sniffingRequest
ctx = session.ContextWithContent(ctx, content) ctx = session.ContextWithContent(ctx, content)
+12 -6
View File
@@ -12,8 +12,10 @@ import (
"sync" "sync"
"time" "time"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/crypto" "github.com/xtls/xray-core/common/crypto"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/task"
"lukechampine.com/blake3" "lukechampine.com/blake3"
) )
@@ -38,6 +40,7 @@ type ServerInstance struct {
Lasts map[int64][16]byte Lasts map[int64][16]byte
Tickets [][16]byte Tickets [][16]byte
Sessions map[[16]byte]*ServerSession Sessions map[[16]byte]*ServerSession
Cleanup *task.Periodic
} }
func (i *ServerInstance) Init(nfsSKeysBytes [][]byte, xorMode uint32, secondsFrom, secondsTo int64, padding string) (err error) { func (i *ServerInstance) Init(nfsSKeysBytes [][]byte, xorMode uint32, secondsFrom, secondsTo int64, padding string) (err error) {
@@ -79,13 +82,12 @@ func (i *ServerInstance) Init(nfsSKeysBytes [][]byte, xorMode uint32, secondsFro
i.Lasts = make(map[int64][16]byte) i.Lasts = make(map[int64][16]byte)
i.Tickets = make([][16]byte, 0, 1024) i.Tickets = make([][16]byte, 0, 1024)
i.Sessions = make(map[[16]byte]*ServerSession) i.Sessions = make(map[[16]byte]*ServerSession)
go func() { i.Cleanup = &task.Periodic{
for { Execute: func() error {
time.Sleep(time.Minute)
i.RWLock.Lock() i.RWLock.Lock()
if i.Closed { if i.Closed {
i.RWLock.Unlock() i.RWLock.Unlock()
return return errors.New("closed")
} }
minute := time.Now().Unix() / 60 minute := time.Now().Unix() / 60
last := i.Lasts[minute] last := i.Lasts[minute]
@@ -101,13 +103,17 @@ func (i *ServerInstance) Init(nfsSKeysBytes [][]byte, xorMode uint32, secondsFro
} }
} }
i.RWLock.Unlock() i.RWLock.Unlock()
} return nil
}() },
Interval: time.Minute,
}
i.Cleanup.Start()
} }
return return
} }
func (i *ServerInstance) Close() (err error) { func (i *ServerInstance) Close() (err error) {
common.CloseIfExists(i.Cleanup)
i.RWLock.Lock() i.RWLock.Lock()
i.Closed = true i.Closed = true
i.RWLock.Unlock() i.RWLock.Unlock()
+59 -10
View File
@@ -3,6 +3,7 @@ package xmc
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"crypto/rand" "crypto/rand"
"crypto/rsa" "crypto/rsa"
"crypto/x509" "crypto/x509"
@@ -29,6 +30,7 @@ type clientConn struct {
password string password string
rsaPublicKey []byte rsaPublicKey []byte
hostname string hostname string
yggdrasil *yggdrasilAuth
paddingSchedule []paddingTurn paddingSchedule []paddingTurn
packet *packetStream packet *packetStream
deadlines *connectionDeadlines deadlines *connectionDeadlines
@@ -44,11 +46,11 @@ var (
clientStateProxy clientState = 2 clientStateProxy clientState = 2
) )
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn) (*clientConn, error) { func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth) (*clientConn, error) {
if len(rsaPublicKey) == 0 { if len(rsaPublicKey) == 0 && yggdrasil == nil {
return nil, fmt.Errorf("empty rsa public key") return nil, fmt.Errorf("empty rsa public key")
} }
if len(profiles) == 0 { if len(profiles) == 0 && yggdrasil == nil {
return nil, fmt.Errorf("empty profiles") return nil, fmt.Errorf("empty profiles")
} }
if len(password) > MaxLegacyPasswordLength { if len(password) > MaxLegacyPasswordLength {
@@ -64,6 +66,7 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl
password: password, password: password,
rsaPublicKey: rsaPublicKey, rsaPublicKey: rsaPublicKey,
hostname: hostname, hostname: hostname,
yggdrasil: yggdrasil,
paddingSchedule: paddingSchedule, paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c), deadlines: newConnectionDeadlines(c),
done: make(chan struct{}), done: make(chan struct{}),
@@ -113,11 +116,27 @@ func (c *clientConn) handshake() error {
} }
// Login Start // Login Start
randomProfile, err := rand.Int(rand.Reader, big.NewInt(int64(len(c.profiles)))) var selectedProfile loginProfile
if err != nil { if c.yggdrasil != nil {
return fmt.Errorf("select profile: %w", err) token, loginErr := c.yggdrasil.login(context.Background())
if loginErr != nil {
return fmt.Errorf("yggdrasil login: %w", loginErr)
}
profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID)
if uuidErr != nil {
return fmt.Errorf("yggdrasil login: %w", uuidErr)
}
selectedProfile = loginProfile{
Username: token.profile.Name,
UUID: profileUUID,
}
} else {
randomProfile, randErr := rand.Int(rand.Reader, big.NewInt(int64(len(c.profiles))))
if randErr != nil {
return fmt.Errorf("select profile: %w", randErr)
}
selectedProfile = c.profiles[randomProfile.Int64()]
} }
selectedProfile := c.profiles[randomProfile.Int64()]
username := String(selectedProfile.Username) username := String(selectedProfile.Username)
err = writePacket(c.writer, 0x00, &username, &selectedProfile.UUID) err = writePacket(c.writer, 0x00, &username, &selectedProfile.UUID)
@@ -146,7 +165,7 @@ func (c *clientConn) handshake() error {
return fmt.Errorf("read encryption request fields: %w", err) return fmt.Errorf("read encryption request fields: %w", err)
} }
if !bytes.Equal(publicKey, c.rsaPublicKey) { if c.yggdrasil == nil && !bytes.Equal(publicKey, c.rsaPublicKey) {
return fmt.Errorf("server public key mismatch") return fmt.Errorf("server public key mismatch")
} }
@@ -159,6 +178,9 @@ func (c *clientConn) handshake() error {
if !ok { if !ok {
return fmt.Errorf("parse server public key: not rsa") return fmt.Errorf("parse server public key: not rsa")
} }
if rsaPublicKey.N.BitLen() < 1024 {
return fmt.Errorf("server public key is too short: %d bits", rsaPublicKey.N.BitLen())
}
sharedSecret := make([]byte, 16) sharedSecret := make([]byte, 16)
if _, err = rand.Read(sharedSecret); err != nil { if _, err = rand.Read(sharedSecret); err != nil {
@@ -170,7 +192,9 @@ func (c *clientConn) handshake() error {
return fmt.Errorf("encrypt shared secret: %w", err) return fmt.Errorf("encrypt shared secret: %w", err)
} }
verifyToken = append(verifyToken, []byte(c.password)...) // append pre-shared password if c.yggdrasil == nil {
verifyToken = append(verifyToken, []byte(c.password)...) // append pre-shared password
}
encryptedVerifyToken, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, verifyToken) encryptedVerifyToken, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, verifyToken)
if err != nil { if err != nil {
@@ -199,6 +223,24 @@ func (c *clientConn) handshake() error {
return fmt.Errorf("new crypto writer: %w", err) return fmt.Errorf("new crypto writer: %w", err)
} }
if c.yggdrasil != nil {
// Standard online-mode login: join the session with the hash of the
// handshake data, the server verifies it through hasJoined.
serverID := minecraftServerID(string(serverId), sharedSecret, publicKey)
token, joinErr := c.yggdrasil.join(context.Background(), serverID)
if joinErr != nil {
return fmt.Errorf("yggdrasil session join: %w", joinErr)
}
profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID)
if uuidErr != nil {
return fmt.Errorf("yggdrasil session join: %w", uuidErr)
}
selectedProfile = loginProfile{
Username: token.profile.Name,
UUID: profileUUID,
}
}
pkt, err = readPacket(c.reader) pkt, err = readPacket(c.reader)
if err != nil { if err != nil {
return fmt.Errorf("read login finished: %w", err) return fmt.Errorf("read login finished: %w", err)
@@ -236,7 +278,14 @@ func (c *clientConn) handshake() error {
if err != nil { if err != nil {
return fmt.Errorf("read login finished fields: %w", err) return fmt.Errorf("read login finished fields: %w", err)
} }
if receivedProfile != selectedProfile { if c.yggdrasil != nil {
if !sameProfileIdentity(receivedProfile, selectedProfile) {
return fmt.Errorf("login profile mismatch")
}
if verifyErr := c.yggdrasil.verifyLoginProfile(receivedProfile); verifyErr != nil {
return fmt.Errorf("verify login profile: %w", verifyErr)
}
} else if !sameLoginProfile(receivedProfile, selectedProfile) {
return fmt.Errorf("login profile mismatch") return fmt.Errorf("login profile mismatch")
} }
loginAcknowledgedLength, err := writePacketWithLength(c.writer, 0x03) loginAcknowledgedLength, err := writePacketWithLength(c.writer, 0x03)
+43 -2
View File
@@ -18,6 +18,18 @@ const maxPaddingDelayMilliseconds = int64(math.MaxInt64 / int64(time.Millisecond
// one RSA-1024 PKCS#1 v1.5 block, which holds at most 128-11 bytes. // one RSA-1024 PKCS#1 v1.5 block, which holds at most 128-11 bytes.
const MaxLegacyPasswordLength = 128 - 11 - 4 const MaxLegacyPasswordLength = 128 - 11 - 4
func (c *Config) wrapClientAuth() (*yggdrasilAuth, error) {
if c.Yggdrasil == nil {
return nil, nil
}
return yggdrasilAuthFor(
c.Yggdrasil.Api,
c.Yggdrasil.Username,
c.Yggdrasil.Password,
c.Yggdrasil.Player,
)
}
func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) { func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) {
profiles, err := profilesFromConfig(c.Profiles) profiles, err := profilesFromConfig(c.Profiles)
if err != nil { if err != nil {
@@ -27,7 +39,24 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
if err != nil { if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err) return nil, fmt.Errorf("minecraft finalmask: %w", err)
} }
cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname, paddingSchedule)
auth, err := c.wrapClientAuth()
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
if auth == nil && len(profiles) == 0 {
return nil, fmt.Errorf("minecraft finalmask: empty profiles")
}
// In Yggdrasil mode the server key is authenticated by the session hash
// handshake, so the client accepts the key sent in Encryption Request
// instead of pinning a configured one.
var rsaPublicKey []byte
if auth == nil {
rsaPublicKey = c.RsaPublicKey
}
cc, err := newClientConn(conn, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth)
if err != nil { if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err) return nil, fmt.Errorf("minecraft finalmask: %w", err)
} }
@@ -44,7 +73,19 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
if err != nil { if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err) return nil, fmt.Errorf("minecraft finalmask: %w", err)
} }
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule)
var verifier *yggdrasilVerifier
if c.Yggdrasil != nil {
verifier, err = yggdrasilVerifierFor(c.Yggdrasil.Api)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
}
if verifier == nil && len(profiles) == 0 {
return nil, fmt.Errorf("minecraft finalmask: empty profiles")
}
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule, verifier)
if err != nil { if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err) return nil, fmt.Errorf("minecraft finalmask: %w", err)
} }
+124 -25
View File
@@ -92,17 +92,101 @@ func (x *Profile) GetTexturesSignature() string {
return "" return ""
} }
type Yggdrasil struct {
state protoimpl.MessageState `protogen:"open.v1"`
// API root of a third-party Yggdrasil API server, for example
// https://skin.example.com/api/yggdrasil. The client logs in to this API
// and joins the session with the server's actual public key, while the
// server verifies players through
// sessionserver/session/minecraft/hasJoined. The API's
// signaturePublickey is used to verify the signed textures property.
Api string `protobuf:"bytes,1,opt,name=api,proto3" json:"api,omitempty"`
// Account used by the client to authenticate with the API. Usually an
// email address, depending on the API implementation.
Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"`
Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"`
// Optional player name. Required when the account owns several players.
Player string `protobuf:"bytes,4,opt,name=player,proto3" json:"player,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Yggdrasil) Reset() {
*x = Yggdrasil{}
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Yggdrasil) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Yggdrasil) ProtoMessage() {}
func (x *Yggdrasil) ProtoReflect() protoreflect.Message {
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Yggdrasil.ProtoReflect.Descriptor instead.
func (*Yggdrasil) Descriptor() ([]byte, []int) {
return file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP(), []int{1}
}
func (x *Yggdrasil) GetApi() string {
if x != nil {
return x.Api
}
return ""
}
func (x *Yggdrasil) GetUsername() string {
if x != nil {
return x.Username
}
return ""
}
func (x *Yggdrasil) GetPassword() string {
if x != nil {
return x.Password
}
return ""
}
func (x *Yggdrasil) GetPlayer() string {
if x != nil {
return x.Player
}
return ""
}
type Config struct { type Config struct {
state protoimpl.MessageState `protogen:"open.v1"` state protoimpl.MessageState `protogen:"open.v1"`
Password string `protobuf:"bytes,1,opt,name=password,proto3" json:"password,omitempty"` // Legacy mode only: seeds the derived RSA key pair and is the pre-shared
RsaPrivateKey []byte `protobuf:"bytes,8,opt,name=rsa_private_key,json=rsaPrivateKey,proto3" json:"rsa_private_key,omitempty"` // password checked during login. Ignored in Yggdrasil mode, where the RSA
RsaPublicKey []byte `protobuf:"bytes,9,opt,name=rsa_public_key,json=rsaPublicKey,proto3" json:"rsa_public_key,omitempty"` // key pair is generated randomly and players are authenticated through the
Hostname string `protobuf:"bytes,10,opt,name=hostname,proto3" json:"hostname,omitempty"` // Yggdrasil API.
Profiles []*Profile `protobuf:"bytes,11,rep,name=profiles,proto3" json:"profiles,omitempty"` Password string `protobuf:"bytes,1,opt,name=password,proto3" json:"password,omitempty"`
RsaPrivateKey []byte `protobuf:"bytes,8,opt,name=rsa_private_key,json=rsaPrivateKey,proto3" json:"rsa_private_key,omitempty"`
RsaPublicKey []byte `protobuf:"bytes,9,opt,name=rsa_public_key,json=rsaPublicKey,proto3" json:"rsa_public_key,omitempty"`
Hostname string `protobuf:"bytes,10,opt,name=hostname,proto3" json:"hostname,omitempty"`
Profiles []*Profile `protobuf:"bytes,11,rep,name=profiles,proto3" json:"profiles,omitempty"`
// Padding turns. Empty uses the built-in preset, unless no_padding is set. // Padding turns. Empty uses the built-in preset, unless no_padding is set.
// A configured list is the complete schedule and replaces the preset // A configured list is the complete schedule and replaces the preset
// entirely: the preset's Play-state join tail runs only with the preset. // entirely: the preset's Play-state join tail runs only with the preset.
Paddings []*Padding `protobuf:"bytes,12,rep,name=paddings,proto3" json:"paddings,omitempty"` Paddings []*Padding `protobuf:"bytes,12,rep,name=paddings,proto3" json:"paddings,omitempty"`
// Optional third-party Yggdrasil login. Field 13 keeps configurations
// that already set 12 for paddings working unchanged.
Yggdrasil *Yggdrasil `protobuf:"bytes,13,opt,name=yggdrasil,proto3" json:"yggdrasil,omitempty"`
// Disables startup padding. The configuration sets this for an explicit // Disables startup padding. The configuration sets this for an explicit
// empty "paddings" array, which an unset repeated field cannot express. // empty "paddings" array, which an unset repeated field cannot express.
NoPadding bool `protobuf:"varint,14,opt,name=no_padding,json=noPadding,proto3" json:"no_padding,omitempty"` NoPadding bool `protobuf:"varint,14,opt,name=no_padding,json=noPadding,proto3" json:"no_padding,omitempty"`
@@ -112,7 +196,7 @@ type Config struct {
func (x *Config) Reset() { func (x *Config) Reset() {
*x = Config{} *x = Config{}
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[1] mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi) ms.StoreMessageInfo(mi)
} }
@@ -124,7 +208,7 @@ func (x *Config) String() string {
func (*Config) ProtoMessage() {} func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message { func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[1] mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2]
if x != nil { if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil { if ms.LoadMessageInfo() == nil {
@@ -137,7 +221,7 @@ func (x *Config) ProtoReflect() protoreflect.Message {
// Deprecated: Use Config.ProtoReflect.Descriptor instead. // Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) { func (*Config) Descriptor() ([]byte, []int) {
return file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP(), []int{1} return file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP(), []int{2}
} }
func (x *Config) GetPassword() string { func (x *Config) GetPassword() string {
@@ -182,6 +266,13 @@ func (x *Config) GetPaddings() []*Padding {
return nil return nil
} }
func (x *Config) GetYggdrasil() *Yggdrasil {
if x != nil {
return x.Yggdrasil
}
return nil
}
func (x *Config) GetNoPadding() bool { func (x *Config) GetNoPadding() bool {
if x != nil { if x != nil {
return x.NoPadding return x.NoPadding
@@ -211,7 +302,7 @@ type Padding struct {
func (x *Padding) Reset() { func (x *Padding) Reset() {
*x = Padding{} *x = Padding{}
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2] mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi) ms.StoreMessageInfo(mi)
} }
@@ -223,7 +314,7 @@ func (x *Padding) String() string {
func (*Padding) ProtoMessage() {} func (*Padding) ProtoMessage() {}
func (x *Padding) ProtoReflect() protoreflect.Message { func (x *Padding) ProtoReflect() protoreflect.Message {
mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2] mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[3]
if x != nil { if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil { if ms.LoadMessageInfo() == nil {
@@ -236,7 +327,7 @@ func (x *Padding) ProtoReflect() protoreflect.Message {
// Deprecated: Use Padding.ProtoReflect.Descriptor instead. // Deprecated: Use Padding.ProtoReflect.Descriptor instead.
func (*Padding) Descriptor() ([]byte, []int) { func (*Padding) Descriptor() ([]byte, []int) {
return file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP(), []int{2} return file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP(), []int{3}
} }
func (x *Padding) GetLengthMin() int64 { func (x *Padding) GetLengthMin() int64 {
@@ -283,7 +374,12 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\busername\x18\x01 \x01(\tR\busername\x12\x12\n" + "\busername\x18\x01 \x01(\tR\busername\x12\x12\n" +
"\x04uuid\x18\x02 \x01(\fR\x04uuid\x12%\n" + "\x04uuid\x18\x02 \x01(\fR\x04uuid\x12%\n" +
"\x0etextures_value\x18\x03 \x01(\tR\rtexturesValue\x12-\n" + "\x0etextures_value\x18\x03 \x01(\tR\rtexturesValue\x12-\n" +
"\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xcb\x02\n" + "\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"m\n" +
"\tYggdrasil\x12\x10\n" +
"\x03api\x18\x01 \x01(\tR\x03api\x12\x1a\n" +
"\busername\x18\x02 \x01(\tR\busername\x12\x1a\n" +
"\bpassword\x18\x03 \x01(\tR\bpassword\x12\x16\n" +
"\x06player\x18\x04 \x01(\tR\x06player\"\x9b\x03\n" +
"\x06Config\x12\x1a\n" + "\x06Config\x12\x1a\n" +
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" + "\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" + "\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
@@ -291,7 +387,8 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\bhostname\x18\n" + "\bhostname\x18\n" +
" \x01(\tR\bhostname\x12J\n" + " \x01(\tR\bhostname\x12J\n" +
"\bprofiles\x18\v \x03(\v2..xray.transport.internet.finalmask.xmc.ProfileR\bprofiles\x12J\n" + "\bprofiles\x18\v \x03(\v2..xray.transport.internet.finalmask.xmc.ProfileR\bprofiles\x12J\n" +
"\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddings\x12\x1d\n" + "\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddings\x12N\n" +
"\tyggdrasil\x18\r \x01(\v20.xray.transport.internet.finalmask.xmc.YggdrasilR\tyggdrasil\x12\x1d\n" +
"\n" + "\n" +
"no_padding\x18\x0e \x01(\bR\tnoPaddingJ\x04\b\x02\x10\x03\"\x9f\x01\n" + "no_padding\x18\x0e \x01(\bR\tnoPaddingJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
"\aPadding\x12\x1d\n" + "\aPadding\x12\x1d\n" +
@@ -316,20 +413,22 @@ func file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP() []byte {
return file_transport_internet_finalmask_xmc_config_proto_rawDescData return file_transport_internet_finalmask_xmc_config_proto_rawDescData
} }
var file_transport_internet_finalmask_xmc_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_transport_internet_finalmask_xmc_config_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_transport_internet_finalmask_xmc_config_proto_goTypes = []any{ var file_transport_internet_finalmask_xmc_config_proto_goTypes = []any{
(*Profile)(nil), // 0: xray.transport.internet.finalmask.xmc.Profile (*Profile)(nil), // 0: xray.transport.internet.finalmask.xmc.Profile
(*Config)(nil), // 1: xray.transport.internet.finalmask.xmc.Config (*Yggdrasil)(nil), // 1: xray.transport.internet.finalmask.xmc.Yggdrasil
(*Padding)(nil), // 2: xray.transport.internet.finalmask.xmc.Padding (*Config)(nil), // 2: xray.transport.internet.finalmask.xmc.Config
(*Padding)(nil), // 3: xray.transport.internet.finalmask.xmc.Padding
} }
var file_transport_internet_finalmask_xmc_config_proto_depIdxs = []int32{ var file_transport_internet_finalmask_xmc_config_proto_depIdxs = []int32{
0, // 0: xray.transport.internet.finalmask.xmc.Config.profiles:type_name -> xray.transport.internet.finalmask.xmc.Profile 0, // 0: xray.transport.internet.finalmask.xmc.Config.profiles:type_name -> xray.transport.internet.finalmask.xmc.Profile
2, // 1: xray.transport.internet.finalmask.xmc.Config.paddings:type_name -> xray.transport.internet.finalmask.xmc.Padding 3, // 1: xray.transport.internet.finalmask.xmc.Config.paddings:type_name -> xray.transport.internet.finalmask.xmc.Padding
2, // [2:2] is the sub-list for method output_type 1, // 2: xray.transport.internet.finalmask.xmc.Config.yggdrasil:type_name -> xray.transport.internet.finalmask.xmc.Yggdrasil
2, // [2:2] is the sub-list for method input_type 3, // [3:3] is the sub-list for method output_type
2, // [2:2] is the sub-list for extension type_name 3, // [3:3] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension extendee 3, // [3:3] is the sub-list for extension type_name
0, // [0:2] is the sub-list for field type_name 3, // [3:3] is the sub-list for extension extendee
0, // [0:3] is the sub-list for field type_name
} }
func init() { file_transport_internet_finalmask_xmc_config_proto_init() } func init() { file_transport_internet_finalmask_xmc_config_proto_init() }
@@ -343,7 +442,7 @@ func file_transport_internet_finalmask_xmc_config_proto_init() {
GoPackagePath: reflect.TypeOf(x{}).PkgPath(), GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_xmc_config_proto_rawDesc), len(file_transport_internet_finalmask_xmc_config_proto_rawDesc)), RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_xmc_config_proto_rawDesc), len(file_transport_internet_finalmask_xmc_config_proto_rawDesc)),
NumEnums: 0, NumEnums: 0,
NumMessages: 3, NumMessages: 4,
NumExtensions: 0, NumExtensions: 0,
NumServices: 0, NumServices: 0,
}, },
@@ -16,7 +16,27 @@ message Profile {
string textures_signature = 4; string textures_signature = 4;
} }
message Yggdrasil {
// API root of a third-party Yggdrasil API server, for example
// https://skin.example.com/api/yggdrasil. The client logs in to this API
// and joins the session with the server's actual public key, while the
// server verifies players through
// sessionserver/session/minecraft/hasJoined. The API's
// signaturePublickey is used to verify the signed textures property.
string api = 1;
// Account used by the client to authenticate with the API. Usually an
// email address, depending on the API implementation.
string username = 2;
string password = 3;
// Optional player name. Required when the account owns several players.
string player = 4;
}
message Config { message Config {
// Legacy mode only: seeds the derived RSA key pair and is the pre-shared
// password checked during login. Ignored in Yggdrasil mode, where the RSA
// key pair is generated randomly and players are authenticated through the
// Yggdrasil API.
string password = 1; string password = 1;
reserved 2; reserved 2;
bytes rsa_private_key = 8; bytes rsa_private_key = 8;
@@ -27,6 +47,9 @@ message Config {
// A configured list is the complete schedule and replaces the preset // A configured list is the complete schedule and replaces the preset
// entirely: the preset's Play-state join tail runs only with the preset. // entirely: the preset's Play-state join tail runs only with the preset.
repeated Padding paddings = 12; repeated Padding paddings = 12;
// Optional third-party Yggdrasil login. Field 13 keeps configurations
// that already set 12 for paddings working unchanged.
Yggdrasil yggdrasil = 13;
// Disables startup padding. The configuration sets this for an explicit // Disables startup padding. The configuration sets this for an explicit
// empty "paddings" array, which an unset repeated field cannot express. // empty "paddings" array, which an unset repeated field cannot express.
bool no_padding = 14; bool no_padding = 14;
@@ -16,10 +16,10 @@ func TestClientRejectsLongLegacyPassword(t *testing.T) {
profiles := []loginProfile{{Username: "TestUser"}} profiles := []loginProfile{{Username: "TestUser"}}
publicKey := []byte{0x01} publicKey := []byte{0x01}
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil); err != nil { if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil); err != nil {
t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err) t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err)
} }
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil); err == nil { if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil); err == nil {
t.Fatal("expected the long password to be rejected") t.Fatal("expected the long password to be rejected")
} }
} }
@@ -130,7 +130,7 @@ func TestCloseCancelsPaddingPause(t *testing.T) {
client, server := net.Pipe() client, server := net.Pipe()
defer server.Close() defer server.Close()
conn, err := newClientConn(client, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil) conn, err := newClientConn(client, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -55,7 +55,15 @@ func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, lengt
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
profiles := []loginProfile{{Username: "TestUser", TexturesValue: "texture", TexturesSignature: "signature"}} profiles := []loginProfile{{
Username: "TestUser",
Properties: loginProperties{{
Name: "textures",
Value: "texture",
Signature: "signature",
Signed: true,
}},
}}
padding := []*Padding{ padding := []*Padding{
{Direction: 1, LengthMin: length, LengthMax: length}, {Direction: 1, LengthMin: length, LengthMax: length},
{Direction: 2, LengthMin: length, LengthMax: length}, {Direction: 2, LengthMin: length, LengthMax: length},
@@ -64,12 +72,12 @@ func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, lengt
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
client, err := newClientConn(clientRaw, profiles, "password", publicKey, "localhost", paddingSchedule) client, err := newClientConn(clientRaw, profiles, "password", publicKey, "localhost", paddingSchedule, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer client.Close() defer client.Close()
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule) server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
+156 -23
View File
@@ -1,17 +1,136 @@
package xmc package xmc
import "fmt" import (
"fmt"
"io"
)
const maxLoginProperties = 16
type loginProperty struct {
Name string
Value string
Signature string
Signed bool
}
// loginProperties is the list of profile properties carried by the Login
// Success packet. It implements the field interface so it can be read and
// written together with the other packet fields.
type loginProperties []loginProperty
func (p *loginProperties) readFrom(r io.Reader) error {
var count Varint
if err := count.readFrom(r); err != nil {
return fmt.Errorf("read property count: %w", err)
}
if count < 0 || count > maxLoginProperties {
return fmt.Errorf("read property count: bad value: %d", count)
}
properties := make([]loginProperty, 0, int(count))
for range int(count) {
var (
name String
value String
flag Boolean
)
if err := name.readFrom(r); err != nil {
return fmt.Errorf("read property name: %w", err)
}
if err := value.readFrom(r); err != nil {
return fmt.Errorf("read property value: %w", err)
}
if err := flag.readFrom(r); err != nil {
return fmt.Errorf("read property signature flag: %w", err)
}
property := loginProperty{
Name: string(name),
Value: string(value),
Signed: bool(flag),
}
if property.Signed {
var signature String
if err := signature.readFrom(r); err != nil {
return fmt.Errorf("read property signature: %w", err)
}
property.Signature = string(signature)
}
properties = append(properties, property)
}
*p = properties
return nil
}
func (p *loginProperties) writeTo(w io.Writer) error {
count := Varint(len(*p))
if err := count.writeTo(w); err != nil {
return fmt.Errorf("write property count: %w", err)
}
for _, property := range *p {
name := String(property.Name)
value := String(property.Value)
signed := Boolean(property.Signed)
if err := name.writeTo(w); err != nil {
return fmt.Errorf("write property name: %w", err)
}
if err := value.writeTo(w); err != nil {
return fmt.Errorf("write property value: %w", err)
}
if err := signed.writeTo(w); err != nil {
return fmt.Errorf("write property signature flag: %w", err)
}
if property.Signed {
signature := String(property.Signature)
if err := signature.writeTo(w); err != nil {
return fmt.Errorf("write property signature: %w", err)
}
}
}
return nil
}
type loginProfile struct { type loginProfile struct {
Username string Username string
UUID UUID UUID UUID
TexturesValue string Properties loginProperties
TexturesSignature string }
func (p loginProfile) textures() (loginProperty, bool) {
for _, property := range p.Properties {
if property.Name == "textures" {
return property, true
}
}
return loginProperty{}, false
}
func sameProfileIdentity(a, b loginProfile) bool {
return a.Username == b.Username && a.UUID == b.UUID
}
// sameLoginProfile also compares the signed textures, so a client that has a
// local copy of the signed profile can detect a server returning another one.
func sameLoginProfile(a, b loginProfile) bool {
if !sameProfileIdentity(a, b) {
return false
}
aTextures, aFound := a.textures()
bTextures, bFound := b.textures()
if !aFound || !bFound {
return aFound == bFound
}
return aTextures.Value == bTextures.Value && aTextures.Signature == bTextures.Signature
} }
func profilesFromConfig(configured []*Profile) ([]loginProfile, error) { func profilesFromConfig(configured []*Profile) ([]loginProfile, error) {
if len(configured) == 0 { if len(configured) == 0 {
return nil, fmt.Errorf("empty profiles") return nil, nil
} }
profiles := make([]loginProfile, 0, len(configured)) profiles := make([]loginProfile, 0, len(configured))
@@ -27,9 +146,15 @@ func profilesFromConfig(configured []*Profile) ([]loginProfile, error) {
} }
profile := loginProfile{ profile := loginProfile{
Username: configuredProfile.Username, Username: configuredProfile.Username,
TexturesValue: configuredProfile.TexturesValue, Properties: loginProperties{
TexturesSignature: configuredProfile.TexturesSignature, {
Name: "textures",
Value: configuredProfile.TexturesValue,
Signature: configuredProfile.TexturesSignature,
Signed: true,
},
},
} }
copy(profile.UUID[:], configuredProfile.Uuid) copy(profile.UUID[:], configuredProfile.Uuid)
profiles = append(profiles, profile) profiles = append(profiles, profile)
@@ -39,31 +164,39 @@ func profilesFromConfig(configured []*Profile) ([]loginProfile, error) {
func findProfile(profiles []loginProfile, username string, uuid UUID) (loginProfile, bool) { func findProfile(profiles []loginProfile, username string, uuid UUID) (loginProfile, bool) {
for _, profile := range profiles { for _, profile := range profiles {
if profile.Username == username && profile.UUID == uuid { if sameProfileIdentity(profile, loginProfile{Username: username, UUID: uuid}) {
return profile, true return profile, true
} }
} }
return loginProfile{}, false return loginProfile{}, false
} }
func propertyListFromYggdrasil(properties []yggdrasilProperty) loginProperties {
result := make(loginProperties, 0, len(properties))
for _, property := range properties {
result = append(result, loginProperty{
Name: property.Name,
Value: property.Value,
Signature: property.Signature,
Signed: property.Signature != "",
})
}
return result
}
func readLoginSuccess(packet *mcPacket) (loginProfile, error) { func readLoginSuccess(packet *mcPacket) (loginProfile, error) {
var ( var (
profile loginProfile profile loginProfile
username String username String
propertyCount Varint
propertyName String
value String
signed Boolean
signature String
) )
if err := packet.readFields(&profile.UUID, &username, &propertyCount, &propertyName, &value, &signed, &signature); err != nil { if err := packet.readFields(&profile.UUID, &username, &profile.Properties); err != nil {
return loginProfile{}, err return loginProfile{}, err
} }
if propertyCount != 1 || propertyName != "textures" || !signed {
return loginProfile{}, fmt.Errorf("invalid login profile properties")
}
profile.Username = string(username) profile.Username = string(username)
profile.TexturesValue = string(value)
profile.TexturesSignature = string(signature)
return profile, nil return profile, nil
} }
func writeLoginSuccess(w io.Writer, profile loginProfile) error {
username := String(profile.Username)
return writePacket(w, 0x02, &profile.UUID, &username, &profile.Properties)
}
+95 -20
View File
@@ -3,10 +3,12 @@ package xmc
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"crypto/rand" "crypto/rand"
"crypto/rsa" "crypto/rsa"
"crypto/subtle" "crypto/subtle"
"crypto/x509" "crypto/x509"
"errors"
"fmt" "fmt"
"io" "io"
"net" "net"
@@ -14,6 +16,18 @@ import (
"time" "time"
) )
const (
yggdrasilVerifyTimeout = 10 * time.Second
// The client sends its join request right after the encryption response,
// so the session is usually registered within a few milliseconds. Poll
// quickly at first and back off to yggdrasilVerifyMaxPoll while it is
// still missing, instead of making every login wait a fixed interval.
yggdrasilVerifyFirstPoll = 10 * time.Millisecond
yggdrasilVerifyMaxPoll = 200 * time.Millisecond
)
var errYggdrasilNotJoined = errors.New("player did not join the minecraft session")
// Response by vanilla 26.1.2 server. // Response by vanilla 26.1.2 server.
var statusResponse = `{"description":"A Minecraft Server","players":{"max":20,"online":0},"version":{"name":"26.1.2","protocol":775},"enforcesSecureChat":true}` var statusResponse = `{"description":"A Minecraft Server","players":{"max":20,"online":0},"version":{"name":"26.1.2","protocol":775},"enforcesSecureChat":true}`
@@ -38,6 +52,7 @@ type serverConn struct {
password string password string
rsaPrivateKey *rsa.PrivateKey rsaPrivateKey *rsa.PrivateKey
rsaPublicKey []byte rsaPublicKey []byte
yggdrasil *yggdrasilVerifier
paddingSchedule []paddingTurn paddingSchedule []paddingTurn
packet *packetStream packet *packetStream
deadlines *connectionDeadlines deadlines *connectionDeadlines
@@ -216,27 +231,42 @@ func (c *serverConn) handshake() error {
return fmt.Errorf("new crypto writer: %w", err) return fmt.Errorf("new crypto writer: %w", err)
} }
// verify password if c.yggdrasil != nil {
receivedPassword := decryptedVerifyToken[4:] // Online-mode login: verify the player through the session server
// instead of the pre-shared password and the static profile list.
if subtle.ConstantTimeCompare(receivedPassword, []byte(c.password)) != 1 { if !bytes.Equal(decryptedVerifyToken, verifyToken) {
writeDisconnectPacket(c.writer, `{"type":"translatable","translate":"multiplayer.disconnect.authservers_down"}`) return fmt.Errorf("verify token mismatch")
return fmt.Errorf("bad password") }
}
if !found { serverID := minecraftServerID(string(serverId), sharedSecret, c.rsaPublicKey)
if err = writeDisconnectPacket(c.writer, `{"text":"You are not white-listed on this server!"}`); err != nil { profile, err = c.verifyYggdrasilLogin(string(username), uuid, serverID)
return fmt.Errorf("write unknown login profile disconnect: %w", err) if err != nil {
reason := `{"type":"translatable","translate":"multiplayer.disconnect.unverified_username"}`
if !errors.Is(err, errYggdrasilNotJoined) {
reason = `{"type":"translatable","translate":"multiplayer.disconnect.authservers_down"}`
}
if writeErr := writeDisconnectPacket(c.writer, reason); writeErr != nil {
return fmt.Errorf("write yggdrasil disconnect: %w", writeErr)
}
return fmt.Errorf("verify yggdrasil login: %w", err)
}
} else {
// verify password
receivedPassword := decryptedVerifyToken[4:]
if subtle.ConstantTimeCompare(receivedPassword, []byte(c.password)) != 1 {
_ = writeDisconnectPacket(c.writer, `{"type":"translatable","translate":"multiplayer.disconnect.authservers_down"}`)
return fmt.Errorf("bad password")
}
if !found {
if err = writeDisconnectPacket(c.writer, `{"text":"You are not white-listed on this server!"}`); err != nil {
return fmt.Errorf("write unknown login profile disconnect: %w", err)
}
return fmt.Errorf("unknown login profile")
} }
return fmt.Errorf("unknown login profile")
} }
loginName := String(profile.Username) if err = writeLoginSuccess(c.writer, profile); err != nil {
propertyCount := Varint(1)
propertyName := String("textures")
texturesValue := String(profile.TexturesValue)
signed := Boolean(true)
texturesSignature := String(profile.TexturesSignature)
if err = writePacket(c.writer, 0x02, &profile.UUID, &loginName, &propertyCount, &propertyName, &texturesValue, &signed, &texturesSignature); err != nil {
return fmt.Errorf("write login finished: %w", err) return fmt.Errorf("write login finished: %w", err)
} }
@@ -274,6 +304,50 @@ func (c *serverConn) handshake() error {
} }
} }
func (c *serverConn) verifyYggdrasilLogin(username string, uuid UUID, serverID string) (loginProfile, error) {
ctx, cancel := context.WithTimeout(context.Background(), yggdrasilVerifyTimeout)
defer cancel()
poll := yggdrasilVerifyFirstPoll
for {
account, err := c.yggdrasil.hasJoined(ctx, username, serverID)
if err != nil {
return loginProfile{}, err
}
if account != nil {
profileUUID, err := normalizeMinecraftUUID(account.ID)
if err != nil {
return loginProfile{}, err
}
if profileUUID != uuid {
return loginProfile{}, fmt.Errorf("yggdrasil profile UUID mismatch")
}
if account.Name != username {
return loginProfile{}, fmt.Errorf("yggdrasil profile name mismatch")
}
return loginProfile{
Username: account.Name,
UUID: profileUUID,
Properties: propertyListFromYggdrasil(account.Properties),
}, nil
}
timer := time.NewTimer(poll)
select {
case <-ctx.Done():
timer.Stop()
return loginProfile{}, fmt.Errorf("%w: %q", errYggdrasilNotJoined, username)
case <-timer.C:
}
if poll < yggdrasilVerifyMaxPoll {
poll *= 2
if poll > yggdrasilVerifyMaxPoll {
poll = yggdrasilVerifyMaxPoll
}
}
}
}
func validateLoginAcknowledgedPacket(pkt *mcPacket) error { func validateLoginAcknowledgedPacket(pkt *mcPacket) error {
if pkt.packetID != 0x03 { if pkt.packetID != 0x03 {
return fmt.Errorf("bad login acknowledged packet id: %d", pkt.packetID) return fmt.Errorf("bad login acknowledged packet id: %d", pkt.packetID)
@@ -339,8 +413,8 @@ func (c *serverConn) SetWriteDeadline(t time.Time) error {
return c.deadlines.setWriteDeadline(t) return c.deadlines.setWriteDeadline(t)
} }
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn) (*serverConn, error) { func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn, yggdrasil *yggdrasilVerifier) (*serverConn, error) {
if len(profiles) == 0 { if len(profiles) == 0 && yggdrasil == nil {
return nil, fmt.Errorf("empty profiles") return nil, fmt.Errorf("empty profiles")
} }
if len(rsaPrivateKeyDER) == 0 { if len(rsaPrivateKeyDER) == 0 {
@@ -363,6 +437,7 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
password: password, password: password,
rsaPrivateKey: rsaPrivateKey, rsaPrivateKey: rsaPrivateKey,
rsaPublicKey: rsaPublicKey, rsaPublicKey: rsaPublicKey,
yggdrasil: yggdrasil,
paddingSchedule: paddingSchedule, paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c), deadlines: newConnectionDeadlines(c),
done: make(chan struct{}), done: make(chan struct{}),
@@ -0,0 +1,710 @@
package xmc
import (
"bytes"
"context"
"crypto"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
const (
yggdrasilRequestTimeout = 15 * time.Second
yggdrasilMaxBodySize = 1 << 20
yggdrasilJoinAttempts = 2
)
// minecraftServerID computes the login hash used by the Minecraft session
// server: sha1(serverId + sharedSecret + serverPublicKey) rendered like Java's
// BigInteger#toString(16), including a minus sign for two's-complement values.
func minecraftServerID(serverID string, sharedSecret, publicKey []byte) string {
hash := sha1.New()
_, _ = hash.Write([]byte(serverID))
_, _ = hash.Write(sharedSecret)
_, _ = hash.Write(publicKey)
digest := hash.Sum(nil)
negative := digest[0]&0x80 != 0
if negative {
digest = twosComplement(digest)
}
rendered := strings.TrimLeft(hex.EncodeToString(digest), "0")
if rendered == "" {
rendered = "0"
}
if negative {
rendered = "-" + rendered
}
return rendered
}
func twosComplement(value []byte) []byte {
carry := true
for i := len(value) - 1; i >= 0; i-- {
value[i] = ^value[i]
if carry {
value[i]++
carry = value[i] == 0
}
}
return value
}
func normalizeMinecraftUUID(value string) (UUID, error) {
var id UUID
decoded, err := hex.DecodeString(strings.ReplaceAll(value, "-", ""))
if err != nil {
return id, fmt.Errorf("invalid minecraft UUID %q: %w", value, err)
}
if len(decoded) != len(id) {
return id, fmt.Errorf("invalid minecraft UUID %q: bad length %d", value, len(decoded))
}
copy(id[:], decoded)
return id, nil
}
func sameYggdrasilID(a, b string) bool {
return strings.EqualFold(strings.ReplaceAll(a, "-", ""), strings.ReplaceAll(b, "-", ""))
}
type yggdrasilAgent struct {
Name string `json:"name"`
Version int `json:"version"`
}
type yggdrasilProfile struct {
ID string `json:"id"`
Name string `json:"name"`
}
type yggdrasilProperty struct {
Name string `json:"name"`
Value string `json:"value"`
Signature string `json:"signature,omitempty"`
}
type yggdrasilAccountProfile struct {
ID string `json:"id"`
Name string `json:"name"`
Properties []yggdrasilProperty `json:"properties"`
}
type yggdrasilAuthenticateRequest struct {
Agent yggdrasilAgent `json:"agent"`
Username string `json:"username"`
Password string `json:"password"`
ClientToken string `json:"clientToken,omitempty"`
RequestUser bool `json:"requestUser,omitempty"`
}
type yggdrasilAuthenticateResponse struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
AvailableProfiles []yggdrasilProfile `json:"availableProfiles"`
SelectedProfile *yggdrasilProfile `json:"selectedProfile"`
}
type yggdrasilRefreshRequest struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken,omitempty"`
SelectedProfile *yggdrasilProfile `json:"selectedProfile,omitempty"`
RequestUser bool `json:"requestUser,omitempty"`
}
type yggdrasilRefreshResponse struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
SelectedProfile *yggdrasilProfile `json:"selectedProfile"`
}
type yggdrasilJoinRequest struct {
AccessToken string `json:"accessToken"`
SelectedProfile string `json:"selectedProfile"`
ServerID string `json:"serverId"`
}
// yggdrasilError is the error document returned by Yggdrasil APIs.
type yggdrasilError struct {
Status int `json:"-"`
Code string `json:"error"`
Message string `json:"errorMessage"`
}
func (e *yggdrasilError) Error() string {
if e.Message != "" {
return fmt.Sprintf("%s: %s", e.Code, e.Message)
}
return e.Code
}
func isYggdrasilForbidden(err error) bool {
var yggErr *yggdrasilError
if !errors.As(err, &yggErr) {
return false
}
return yggErr.Status == http.StatusForbidden || yggErr.Code == "ForbiddenOperationException"
}
// yggdrasilConfig is the parsed configuration shared by the client and server
// side of the finalmask.
type yggdrasilConfig struct {
baseURL *url.URL
username string
password string
player string
}
func newYggdrasilConfig(api, username, password, player string) (*yggdrasilConfig, error) {
baseURL, err := url.Parse(strings.TrimSpace(api))
if err != nil {
return nil, fmt.Errorf("invalid yggdrasil api: %w", err)
}
if baseURL.Scheme != "http" && baseURL.Scheme != "https" {
return nil, fmt.Errorf("invalid yggdrasil api scheme: %q", baseURL.Scheme)
}
if baseURL.Host == "" {
return nil, fmt.Errorf("invalid yggdrasil api: missing host")
}
if baseURL.RawQuery != "" || baseURL.Fragment != "" {
return nil, fmt.Errorf("invalid yggdrasil api: query and fragment are not allowed")
}
baseURL.Path = strings.TrimSuffix(baseURL.Path, "/")
return &yggdrasilConfig{
baseURL: baseURL,
username: username,
password: password,
player: player,
}, nil
}
func (c *yggdrasilConfig) endpoint(parts ...string) string {
u := *c.baseURL
u.Path = c.baseURL.Path + "/" + strings.Join(parts, "/")
return u.String()
}
func newYggdrasilHTTPClient() *http.Client {
return &http.Client{Timeout: yggdrasilRequestTimeout}
}
func doYggdrasilJSON(ctx context.Context, client *http.Client, method, endpoint string, request, response any) error {
var body io.Reader
if request != nil {
encoded, err := json.Marshal(request)
if err != nil {
return fmt.Errorf("encode yggdrasil request: %w", err)
}
body = bytes.NewReader(encoded)
}
httpRequest, err := http.NewRequestWithContext(ctx, method, endpoint, body)
if err != nil {
return fmt.Errorf("create yggdrasil request: %w", err)
}
httpRequest.Header.Set("Accept", "application/json")
if request != nil {
httpRequest.Header.Set("Content-Type", "application/json")
}
httpResponse, err := client.Do(httpRequest)
if err != nil {
return fmt.Errorf("yggdrasil request: %w", err)
}
defer httpResponse.Body.Close()
content, err := io.ReadAll(io.LimitReader(httpResponse.Body, yggdrasilMaxBodySize))
if err != nil {
return fmt.Errorf("read yggdrasil response: %w", err)
}
if httpResponse.StatusCode < 200 || httpResponse.StatusCode >= 300 {
yggErr := &yggdrasilError{Status: httpResponse.StatusCode}
if len(content) > 0 {
_ = json.Unmarshal(content, yggErr)
}
if yggErr.Code == "" {
yggErr.Code = httpResponse.Status
}
return yggErr
}
if response == nil || len(bytes.TrimSpace(content)) == 0 {
return nil
}
if err := json.Unmarshal(content, response); err != nil {
return fmt.Errorf("decode yggdrasil response: %w", err)
}
return nil
}
func (c *yggdrasilConfig) authenticate(ctx context.Context, client *http.Client, clientToken string) (*yggdrasilAuthenticateResponse, error) {
var response yggdrasilAuthenticateResponse
err := doYggdrasilJSON(
ctx,
client,
http.MethodPost,
c.endpoint("authserver", "authenticate"),
&yggdrasilAuthenticateRequest{
Agent: yggdrasilAgent{Name: "Minecraft", Version: 1},
Username: c.username,
Password: c.password,
ClientToken: clientToken,
},
&response,
)
if err != nil {
return nil, fmt.Errorf("yggdrasil authenticate: %w", err)
}
if response.AccessToken == "" {
return nil, fmt.Errorf("yggdrasil authenticate: empty access token")
}
return &response, nil
}
func (c *yggdrasilConfig) refresh(ctx context.Context, client *http.Client, accessToken, clientToken string, profile yggdrasilProfile) (*yggdrasilRefreshResponse, error) {
var response yggdrasilRefreshResponse
err := doYggdrasilJSON(
ctx,
client,
http.MethodPost,
c.endpoint("authserver", "refresh"),
&yggdrasilRefreshRequest{
AccessToken: accessToken,
ClientToken: clientToken,
SelectedProfile: &profile,
},
&response,
)
if err != nil {
return nil, fmt.Errorf("yggdrasil refresh: %w", err)
}
if response.AccessToken == "" {
return nil, fmt.Errorf("yggdrasil refresh: empty access token")
}
return &response, nil
}
func (c *yggdrasilConfig) join(ctx context.Context, client *http.Client, accessToken string, profile yggdrasilProfile, serverID string) error {
err := doYggdrasilJSON(
ctx,
client,
http.MethodPost,
c.endpoint("sessionserver", "session", "minecraft", "join"),
&yggdrasilJoinRequest{
AccessToken: accessToken,
SelectedProfile: strings.ReplaceAll(profile.ID, "-", ""),
ServerID: serverID,
},
nil,
)
if err != nil {
return fmt.Errorf("yggdrasil join: %w", err)
}
return nil
}
func (c *yggdrasilConfig) hasJoined(ctx context.Context, client *http.Client, username, serverID string) (*yggdrasilAccountProfile, error) {
values := url.Values{}
values.Set("username", username)
values.Set("serverId", serverID)
var profile yggdrasilAccountProfile
err := doYggdrasilJSON(
ctx,
client,
http.MethodGet,
c.endpoint("sessionserver", "session", "minecraft", "hasJoined")+"?"+values.Encode(),
nil,
&profile,
)
if err != nil {
return nil, fmt.Errorf("yggdrasil hasJoined: %w", err)
}
if profile.ID == "" && profile.Name == "" {
return nil, nil
}
return &profile, nil
}
type yggdrasilMetadata struct {
SignaturePublicKey string `json:"signaturePublickey"`
}
// metadata fetches the API description, which carries the public key used to
// sign texture properties. Both the API root and its trailing-slash form are
// tried because implementations differ.
func (c *yggdrasilConfig) metadata(ctx context.Context, client *http.Client) (*yggdrasilMetadata, error) {
endpoints := []string{c.baseURL.String()}
if c.baseURL.Path != "" && !strings.HasSuffix(c.baseURL.Path, "/") {
withSlash := *c.baseURL
withSlash.Path += "/"
endpoints = append(endpoints, withSlash.String())
}
var lastErr error
for _, endpoint := range endpoints {
var metadata yggdrasilMetadata
if err := doYggdrasilJSON(ctx, client, http.MethodGet, endpoint, nil, &metadata); err != nil {
lastErr = err
continue
}
return &metadata, nil
}
return nil, fmt.Errorf("yggdrasil metadata: %w", lastErr)
}
func parseYggdrasilPublicKey(value string) (*rsa.PublicKey, error) {
value = strings.TrimSpace(value)
if value == "" {
return nil, fmt.Errorf("yggdrasil api does not expose signaturePublickey")
}
var der []byte
if block, _ := pem.Decode([]byte(value)); block != nil {
der = block.Bytes
} else {
decoded, err := base64.StdEncoding.DecodeString(strings.Join(strings.Fields(value), ""))
if err != nil {
return nil, fmt.Errorf("decode signaturePublickey: %w", err)
}
der = decoded
}
parsed, err := x509.ParsePKIXPublicKey(der)
if err != nil {
return nil, fmt.Errorf("parse signaturePublickey: %w", err)
}
key, ok := parsed.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("signaturePublickey is not an RSA key")
}
return key, nil
}
func verifyYggdrasilProperty(key *rsa.PublicKey, value, signature string) error {
raw, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
raw, err = base64.RawStdEncoding.DecodeString(signature)
if err != nil {
return fmt.Errorf("decode property signature: %w", err)
}
}
digest := sha1.Sum([]byte(value))
if err := rsa.VerifyPKCS1v15(key, crypto.SHA1, digest[:], raw); err != nil {
return fmt.Errorf("verify property signature: %w", err)
}
return nil
}
// selectProfile picks the player owned by the authenticated account.
func (c *yggdrasilConfig) selectProfile(response *yggdrasilAuthenticateResponse) (yggdrasilProfile, error) {
if c.player != "" {
for _, available := range response.AvailableProfiles {
if available.Name == c.player {
return available, nil
}
}
for _, available := range response.AvailableProfiles {
if strings.EqualFold(available.Name, c.player) {
return available, nil
}
}
return yggdrasilProfile{}, fmt.Errorf(
"yggdrasil profile %q is not available for this account",
c.player,
)
}
if response.SelectedProfile != nil {
return *response.SelectedProfile, nil
}
if len(response.AvailableProfiles) == 1 {
return response.AvailableProfiles[0], nil
}
if len(response.AvailableProfiles) == 0 {
return yggdrasilProfile{}, fmt.Errorf("yggdrasil account has no available profiles")
}
names := make([]string, 0, len(response.AvailableProfiles))
for _, available := range response.AvailableProfiles {
names = append(names, available.Name)
}
return yggdrasilProfile{}, fmt.Errorf(
"yggdrasil account has multiple profiles (%s), set \"player\" to choose one",
strings.Join(names, ", "),
)
}
type yggdrasilToken struct {
accessToken string
clientToken string
profile yggdrasilProfile
}
// yggdrasilAuth is the client side login state. Tokens are cached for the
// lifetime of the process and shared by all connections using the same account.
type yggdrasilAuth struct {
config *yggdrasilConfig
client *http.Client
mu sync.Mutex
token yggdrasilToken
keyMu sync.Mutex
signatureKey *rsa.PublicKey
}
func newYggdrasilAuth(config *yggdrasilConfig) *yggdrasilAuth {
return &yggdrasilAuth{
config: config,
client: newYggdrasilHTTPClient(),
}
}
var (
yggdrasilAuthMu sync.Mutex
yggdrasilAuths = make(map[string]*yggdrasilAuth)
)
func yggdrasilAuthFor(api, username, password, player string) (*yggdrasilAuth, error) {
if username == "" || password == "" {
return nil, fmt.Errorf("yggdrasil username and password are required on client")
}
config, err := newYggdrasilConfig(api, username, password, player)
if err != nil {
return nil, err
}
// The cache key uses a digest so plaintext passwords are not retained in
// the package level map.
digest := sha256.Sum256([]byte(password))
key := config.baseURL.String() + "\x00" + username + "\x00" + hex.EncodeToString(digest[:]) + "\x00" + player
yggdrasilAuthMu.Lock()
defer yggdrasilAuthMu.Unlock()
if auth, found := yggdrasilAuths[key]; found {
return auth, nil
}
auth := newYggdrasilAuth(config)
yggdrasilAuths[key] = auth
return auth, nil
}
func (a *yggdrasilAuth) loginLocked(ctx context.Context) (yggdrasilToken, error) {
if a.token.accessToken != "" && a.token.profile.ID != "" {
return a.token, nil
}
response, err := a.config.authenticate(ctx, a.client, a.token.clientToken)
if err != nil {
return yggdrasilToken{}, err
}
profile, err := a.config.selectProfile(response)
if err != nil {
return yggdrasilToken{}, err
}
if _, err := normalizeMinecraftUUID(profile.ID); err != nil {
return yggdrasilToken{}, err
}
token := yggdrasilToken{
accessToken: response.AccessToken,
clientToken: response.ClientToken,
profile: profile,
}
if token.clientToken == "" {
token.clientToken = a.token.clientToken
}
// The session server only accepts a token that is already bound to the
// selected profile, which the API only binds automatically when the
// account owns exactly one player.
if response.SelectedProfile == nil || !sameYggdrasilID(response.SelectedProfile.ID, profile.ID) {
refreshed, err := a.config.refresh(ctx, a.client, token.accessToken, token.clientToken, profile)
if err != nil {
return yggdrasilToken{}, err
}
token.accessToken = refreshed.AccessToken
if refreshed.ClientToken != "" {
token.clientToken = refreshed.ClientToken
}
if refreshed.SelectedProfile != nil {
token.profile = *refreshed.SelectedProfile
}
}
a.token = token
return token, nil
}
func (a *yggdrasilAuth) login(ctx context.Context) (yggdrasilToken, error) {
a.mu.Lock()
defer a.mu.Unlock()
return a.loginLocked(ctx)
}
// join performs the standard Minecraft session join and returns the token and
// profile used for the connection. When the cached token has been revoked the
// client logs in again once.
func (a *yggdrasilAuth) join(ctx context.Context, serverID string) (yggdrasilToken, error) {
a.mu.Lock()
defer a.mu.Unlock()
var lastErr error
for range yggdrasilJoinAttempts {
token, err := a.loginLocked(ctx)
if err != nil {
return yggdrasilToken{}, err
}
err = a.config.join(ctx, a.client, token.accessToken, token.profile, serverID)
if err == nil {
return token, nil
}
lastErr = err
if !isYggdrasilForbidden(err) {
break
}
a.token = yggdrasilToken{}
}
return yggdrasilToken{}, lastErr
}
// verifyLoginProfile validates the signature of the signed textures property
// returned in Login Success, like a vanilla Minecraft client does.
func (a *yggdrasilAuth) verifyLoginProfile(profile loginProfile) error {
textures, found := profile.textures()
if !found {
return fmt.Errorf("login success has no textures property")
}
if !textures.Signed || textures.Signature == "" {
return fmt.Errorf("textures property is not signed")
}
key, err := a.signaturePublicKey()
if err == nil {
if verifyErr := verifyYggdrasilProperty(key, textures.Value, textures.Signature); verifyErr == nil {
return nil
}
}
// The API may have rotated its key pair, so fetch it again and retry once.
key, refreshErr := a.refreshSignaturePublicKey()
if refreshErr != nil {
if err != nil {
return fmt.Errorf("fetch texture signature key: %w", err)
}
return fmt.Errorf("refresh texture signature key: %w", refreshErr)
}
if verifyErr := verifyYggdrasilProperty(key, textures.Value, textures.Signature); verifyErr != nil {
return fmt.Errorf("invalid textures signature: %w", verifyErr)
}
return nil
}
func (a *yggdrasilAuth) signaturePublicKey() (*rsa.PublicKey, error) {
a.keyMu.Lock()
defer a.keyMu.Unlock()
if a.signatureKey != nil {
return a.signatureKey, nil
}
key, err := a.fetchSignaturePublicKeyLocked()
if err != nil {
return nil, err
}
a.signatureKey = key
return key, nil
}
func (a *yggdrasilAuth) refreshSignaturePublicKey() (*rsa.PublicKey, error) {
a.keyMu.Lock()
defer a.keyMu.Unlock()
key, err := a.fetchSignaturePublicKeyLocked()
if err != nil {
return nil, err
}
a.signatureKey = key
return key, nil
}
func (a *yggdrasilAuth) fetchSignaturePublicKeyLocked() (*rsa.PublicKey, error) {
ctx, cancel := context.WithTimeout(context.Background(), yggdrasilRequestTimeout)
defer cancel()
metadata, err := a.config.metadata(ctx, a.client)
if err != nil {
return nil, err
}
return parseYggdrasilPublicKey(metadata.SignaturePublicKey)
}
// yggdrasilVerifier is the server side hasJoined check.
type yggdrasilVerifier struct {
config *yggdrasilConfig
client *http.Client
}
func newYggdrasilVerifier(api string) (*yggdrasilVerifier, error) {
config, err := newYggdrasilConfig(api, "", "", "")
if err != nil {
return nil, err
}
return &yggdrasilVerifier{
config: config,
client: newYggdrasilHTTPClient(),
}, nil
}
var (
yggdrasilVerifierMu sync.Mutex
yggdrasilVerifiers = make(map[string]*yggdrasilVerifier)
)
// yggdrasilVerifierFor returns the process-wide verifier of one API root, so
// every connection reuses its HTTP client and its keep-alive connections
// instead of dialing the API again for each login.
func yggdrasilVerifierFor(api string) (*yggdrasilVerifier, error) {
config, err := newYggdrasilConfig(api, "", "", "")
if err != nil {
return nil, err
}
key := config.baseURL.String()
yggdrasilVerifierMu.Lock()
defer yggdrasilVerifierMu.Unlock()
if verifier, found := yggdrasilVerifiers[key]; found {
return verifier, nil
}
verifier := &yggdrasilVerifier{
config: config,
client: newYggdrasilHTTPClient(),
}
yggdrasilVerifiers[key] = verifier
return verifier, nil
}
// hasJoined returns the signed profile of the player that joined the session,
// or nil when the player has not joined this server ID.
func (v *yggdrasilVerifier) hasJoined(ctx context.Context, username, serverID string) (*yggdrasilAccountProfile, error) {
return v.config.hasJoined(ctx, v.client, username, serverID)
}
@@ -0,0 +1,617 @@
package xmc
import (
"bytes"
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"math/big"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
)
func deriveTestRSAKey(t *testing.T, password string) ([]byte, []byte) {
t.Helper()
key, err := DeriveRSAKey(password)
if err != nil {
t.Fatalf("failed to derive rsa key: %v", err)
}
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
t.Fatalf("failed to marshal public key: %v", err)
}
return x509.MarshalPKCS1PrivateKey(key), publicKey
}
type fakeYggdrasilProfile struct {
ID string
Name string
}
type fakeYggdrasil struct {
mu sync.Mutex
profile fakeYggdrasilProfile
signingKey *rsa.PrivateKey
publicKeyPEM string
authenticateCalls int
refreshCalls int
joinCalls int
boundProfile string
joined map[string]string // serverId -> profile name
}
func writeFakeYggdrasilJSON(w http.ResponseWriter, status int, body string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = io.WriteString(w, body)
}
func newFakeYggdrasilHandler(state *fakeYggdrasil) http.Handler {
mux := http.NewServeMux()
prefix := "/api/yggdrasil"
metadata := func(w http.ResponseWriter, r *http.Request) {
state.mu.Lock()
key := state.publicKeyPEM
state.mu.Unlock()
writeFakeYggdrasilJSON(w, http.StatusOK, fmt.Sprintf(
`{"meta":{"serverName":"Fake Skin"},"skinDomains":["example.com"],"signaturePublickey":%q}`,
key,
))
}
mux.HandleFunc(prefix, metadata)
mux.HandleFunc(prefix+"/", metadata)
mux.HandleFunc(prefix+"/authserver/authenticate", func(w http.ResponseWriter, r *http.Request) {
var request yggdrasilAuthenticateRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
writeFakeYggdrasilJSON(w, http.StatusBadRequest, `{"error":"IllegalArgumentException","errorMessage":"bad request"}`)
return
}
if request.Username != "user@example.com" || request.Password != "password" {
writeFakeYggdrasilJSON(w, http.StatusForbidden, `{"error":"ForbiddenOperationException","errorMessage":"bad credentials"}`)
return
}
state.mu.Lock()
defer state.mu.Unlock()
state.authenticateCalls++
writeFakeYggdrasilJSON(w, http.StatusOK, fmt.Sprintf(
`{"accessToken":"token-1","clientToken":"client-1","availableProfiles":[{"id":%q,"name":%q}],"selectedProfile":{"id":%q,"name":%q}}`,
state.profile.ID, state.profile.Name, state.profile.ID, state.profile.Name,
))
})
mux.HandleFunc(prefix+"/authserver/refresh", func(w http.ResponseWriter, r *http.Request) {
state.mu.Lock()
defer state.mu.Unlock()
state.refreshCalls++
writeFakeYggdrasilJSON(w, http.StatusOK, fmt.Sprintf(
`{"accessToken":"token-2","clientToken":"client-1","selectedProfile":{"id":%q,"name":%q}}`,
state.profile.ID, state.profile.Name,
))
})
mux.HandleFunc(prefix+"/sessionserver/session/minecraft/join", func(w http.ResponseWriter, r *http.Request) {
var request yggdrasilJoinRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
writeFakeYggdrasilJSON(w, http.StatusBadRequest, `{"error":"IllegalArgumentException","errorMessage":"bad request"}`)
return
}
state.mu.Lock()
defer state.mu.Unlock()
state.joinCalls++
state.boundProfile = request.SelectedProfile
state.joined[request.ServerID] = state.profile.Name
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc(prefix+"/sessionserver/session/minecraft/hasJoined", func(w http.ResponseWriter, r *http.Request) {
state.mu.Lock()
defer state.mu.Unlock()
name, found := state.joined[r.URL.Query().Get("serverId")]
if !found || name != r.URL.Query().Get("username") {
w.WriteHeader(http.StatusNoContent)
return
}
digest := sha1.Sum([]byte("textures-value"))
signature, err := rsa.SignPKCS1v15(rand.Reader, state.signingKey, crypto.SHA1, digest[:])
if err != nil {
writeFakeYggdrasilJSON(w, http.StatusInternalServerError, `{"error":"InternalError"}`)
return
}
writeFakeYggdrasilJSON(w, http.StatusOK, fmt.Sprintf(
`{"id":%q,"name":%q,"properties":[{"name":"textures","value":"textures-value","signature":%q},{"name":"uploadableTextures","value":"skin,cape"}]}`,
state.profile.ID, state.profile.Name, base64.StdEncoding.EncodeToString(signature),
))
})
return mux
}
func newFakeYggdrasilServer(t *testing.T) (*fakeYggdrasil, string) {
t.Helper()
signingKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate signing key: %v", err)
}
der, err := x509.MarshalPKIXPublicKey(&signingKey.PublicKey)
if err != nil {
t.Fatalf("marshal signing key: %v", err)
}
state := &fakeYggdrasil{
profile: fakeYggdrasilProfile{
ID: "0123456789abcdef0123456789abcdef",
Name: "SkinUser",
},
signingKey: signingKey,
publicKeyPEM: string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der})),
joined: make(map[string]string),
}
server := httptest.NewServer(newFakeYggdrasilHandler(state))
t.Cleanup(server.Close)
return state, server.URL + "/api/yggdrasil"
}
func newTestYggdrasilAuth(t *testing.T, api, player string) *yggdrasilAuth {
t.Helper()
config, err := newYggdrasilConfig(api, "user@example.com", "password", player)
if err != nil {
t.Fatalf("new yggdrasil config: %v", err)
}
return newYggdrasilAuth(config)
}
func TestMinecraftServerID(t *testing.T) {
// Vectors from the Java implementation (SHA-1 hexdigest as a signed
// BigInteger), including a negative hash.
for input, want := range map[string]string{
"Notch": "4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48",
"jeb_": "-7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1",
"simon": "88e16a1019277b15d58faf0541e11910eb756f6",
} {
if got := minecraftServerID(input, nil, nil); got != want {
t.Fatalf("server ID for %q = %q, want %q", input, got, want)
}
}
// Java renders the digest as a signed BigInteger, so mirrors of the
// two's-complement sign and of leading zero trimming are covered.
signedHash := func(serverID string, secret, publicKey []byte) string {
hasher := sha1.New()
_, _ = hasher.Write([]byte(serverID))
_, _ = hasher.Write(secret)
_, _ = hasher.Write(publicKey)
digest := hasher.Sum(nil)
value := new(big.Int).SetBytes(digest)
if digest[0]&0x80 != 0 {
value.Sub(value, new(big.Int).Lsh(big.NewInt(1), 160))
}
return value.Text(16)
}
secret := []byte("0123456789abcdef")
publicKey := []byte("public-key")
foundPositive := false
foundNegative := false
for i := 0; i < 1<<16; i++ {
serverID := fmt.Sprintf("probe-%d", i)
got := minecraftServerID(serverID, secret, publicKey)
want := signedHash(serverID, secret, publicKey)
if got != want {
t.Fatalf("server ID for %q = %q, want %q", serverID, got, want)
}
if strings.HasPrefix(want, "-") {
foundNegative = true
} else {
foundPositive = true
}
if foundPositive && foundNegative {
return
}
}
t.Fatalf("probe did not cover both hash signs: positive=%v negative=%v", foundPositive, foundNegative)
}
func TestYggdrasilAuthenticateCachesToken(t *testing.T) {
state, api := newFakeYggdrasilServer(t)
auth := newTestYggdrasilAuth(t, api, "SkinUser")
token, err := auth.login(context.Background())
if err != nil {
t.Fatalf("login: %v", err)
}
if token.profile.ID != state.profile.ID || token.profile.Name != state.profile.Name {
t.Fatalf("unexpected profile: %+v", token.profile)
}
if _, err := auth.login(context.Background()); err != nil {
t.Fatalf("second login: %v", err)
}
state.mu.Lock()
defer state.mu.Unlock()
if state.authenticateCalls != 1 {
t.Fatalf("token was not cached: authenticate calls = %d", state.authenticateCalls)
}
if state.refreshCalls != 0 {
t.Fatalf("unexpected refresh calls: %d", state.refreshCalls)
}
}
func TestYggdrasilSelectsPlayerAndBindsToken(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/api/yggdrasil/authserver/authenticate", func(w http.ResponseWriter, r *http.Request) {
writeFakeYggdrasilJSON(w, http.StatusOK, `{"accessToken":"token-1","clientToken":"client-1","availableProfiles":[`+
`{"id":"0123456789abcdef0123456789abcdef","name":"FirstPlayer"},`+
`{"id":"fedcba9876543210fedcba9876543210","name":"SecondPlayer"}]}`)
})
var refreshed string
mux.HandleFunc("/api/yggdrasil/authserver/refresh", func(w http.ResponseWriter, r *http.Request) {
var request yggdrasilRefreshRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
t.Errorf("decode refresh: %v", err)
return
}
if request.SelectedProfile == nil {
t.Error("refresh did not select a profile")
return
}
refreshed = request.SelectedProfile.Name
writeFakeYggdrasilJSON(w, http.StatusOK, `{"accessToken":"token-2","clientToken":"client-1","selectedProfile":{"id":"fedcba9876543210fedcba9876543210","name":"SecondPlayer"}}`)
})
server := httptest.NewServer(mux)
defer server.Close()
auth := newTestYggdrasilAuth(t, server.URL+"/api/yggdrasil", "SecondPlayer")
token, err := auth.login(context.Background())
if err != nil {
t.Fatalf("login: %v", err)
}
if token.profile.Name != "SecondPlayer" || token.accessToken != "token-2" {
t.Fatalf("unexpected token: %+v", token)
}
if refreshed != "SecondPlayer" {
t.Fatalf("refresh selected %q", refreshed)
}
}
func TestYggdrasilRejectsMultiplePlayersWithoutSelection(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/api/yggdrasil/authserver/authenticate", func(w http.ResponseWriter, r *http.Request) {
writeFakeYggdrasilJSON(w, http.StatusOK, `{"accessToken":"token-1","clientToken":"client-1","availableProfiles":[{"id":"0123456789abcdef0123456789abcdef","name":"FirstPlayer"},{"id":"fedcba9876543210fedcba9876543210","name":"SecondPlayer"}]}`)
})
server := httptest.NewServer(mux)
defer server.Close()
auth := newTestYggdrasilAuth(t, server.URL+"/api/yggdrasil", "")
if _, err := auth.login(context.Background()); err == nil || !strings.Contains(err.Error(), "multiple profiles") {
t.Fatalf("expected multiple profiles error, got %v", err)
}
}
func TestYggdrasilRejectsInvalidAPI(t *testing.T) {
for _, api := range []string{
"",
"ftp://example.com/api/yggdrasil",
"https://example.com/api/yggdrasil?query=1",
"https://example.com/api/yggdrasil#fragment",
"/api/yggdrasil",
} {
if _, err := newYggdrasilConfig(api, "user", "password", ""); err == nil {
t.Fatalf("api %q was accepted", api)
}
}
}
func TestHandshakeWithYggdrasil(t *testing.T) {
state, api := newFakeYggdrasilServer(t)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
defer ln.Close()
password := "yggdrasil-rsa-seed"
privateKey, publicKey := deriveTestRSAKey(t, password)
serverDone := make(chan struct{})
go func() {
defer close(serverDone)
rawConn, err := ln.Accept()
if err != nil {
t.Errorf("accept: %v", err)
return
}
defer rawConn.Close()
verifier, err := newYggdrasilVerifier(api)
if err != nil {
t.Errorf("new verifier: %v", err)
return
}
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier)
if err != nil {
t.Errorf("wrap server: %v", err)
return
}
buf := make([]byte, 1024)
n, err := server.Read(buf)
if err != nil {
t.Errorf("server read: %v", err)
return
}
if !bytes.Equal(buf[:n], []byte("hello server")) {
t.Errorf("unexpected client payload: %q", buf[:n])
return
}
if _, err := server.Write([]byte("hello client")); err != nil {
t.Errorf("server write: %v", err)
}
}()
rawClient, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatalf("dial: %v", err)
}
defer rawClient.Close()
// The client intentionally has no pinned server key: Yggdrasil mode accepts
// the key sent by the server and binds it through the session hash.
client, err := newClientConn(rawClient, nil, password, nil, "localhost", nil, newTestYggdrasilAuth(t, api, "SkinUser"))
if err != nil {
t.Fatalf("new client: %v", err)
}
defer client.Close()
if _, err := client.Write([]byte("hello server")); err != nil {
t.Fatalf("client write: %v", err)
}
response := make([]byte, len("hello client"))
client.SetReadDeadline(time.Now().Add(5 * time.Second))
if _, err := io.ReadFull(client, response); err != nil {
t.Fatalf("client read: %v", err)
}
if string(response) != "hello client" {
t.Fatalf("unexpected response: %q", response)
}
select {
case <-serverDone:
case <-time.After(5 * time.Second):
t.Fatal("server handshake timed out")
}
state.mu.Lock()
defer state.mu.Unlock()
if state.joinCalls != 1 {
t.Errorf("join calls = %d", state.joinCalls)
}
if state.boundProfile != state.profile.ID {
t.Errorf("joined profile = %q", state.boundProfile)
}
}
func TestYggdrasilVerifiesTexturesSignature(t *testing.T) {
state, api := newFakeYggdrasilServer(t)
auth := newTestYggdrasilAuth(t, api, "SkinUser")
signTextures := func(key *rsa.PrivateKey, value string) loginProfile {
digest := sha1.Sum([]byte(value))
signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA1, digest[:])
if err != nil {
t.Fatalf("sign textures: %v", err)
}
return loginProfile{
Username: "SkinUser",
Properties: loginProperties{
{Name: "textures", Value: value, Signature: base64.StdEncoding.EncodeToString(signature), Signed: true},
},
}
}
valid := signTextures(state.signingKey, "textures-value")
if err := auth.verifyLoginProfile(valid); err != nil {
t.Fatalf("valid textures signature was rejected: %v", err)
}
tampered := valid
tampered.Properties = loginProperties{
{Name: "textures", Value: "tampered-value", Signature: valid.Properties[0].Signature, Signed: true},
}
if err := auth.verifyLoginProfile(tampered); err == nil {
t.Fatal("tampered textures value was accepted")
}
unsigned := loginProfile{
Username: "SkinUser",
Properties: loginProperties{
{Name: "textures", Value: "textures-value"},
},
}
if err := auth.verifyLoginProfile(unsigned); err == nil {
t.Fatal("unsigned textures property was accepted")
}
missing := loginProfile{Username: "SkinUser"}
if err := auth.verifyLoginProfile(missing); err == nil {
t.Fatal("missing textures property was accepted")
}
// The API may rotate its signing key; the cached key must be refreshed.
rotatedKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate rotated key: %v", err)
}
der, err := x509.MarshalPKIXPublicKey(&rotatedKey.PublicKey)
if err != nil {
t.Fatalf("marshal rotated key: %v", err)
}
state.mu.Lock()
state.signingKey = rotatedKey
state.publicKeyPEM = string(pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}))
state.mu.Unlock()
if err := auth.verifyLoginProfile(signTextures(rotatedKey, "textures-value")); err != nil {
t.Fatalf("rotated textures signature was rejected: %v", err)
}
}
func TestYggdrasilJoinRetriesAfterForbidden(t *testing.T) {
var mu sync.Mutex
authenticateCalls := 0
joinCalls := 0
mux := http.NewServeMux()
mux.HandleFunc("/api/yggdrasil/authserver/authenticate", func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
authenticateCalls++
calls := authenticateCalls
mu.Unlock()
writeFakeYggdrasilJSON(w, http.StatusOK, fmt.Sprintf(
`{"accessToken":"token-%d","clientToken":"client-1","availableProfiles":[{"id":"0123456789abcdef0123456789abcdef","name":"SkinUser"}],"selectedProfile":{"id":"0123456789abcdef0123456789abcdef","name":"SkinUser"}}`,
calls,
))
})
mux.HandleFunc("/api/yggdrasil/sessionserver/session/minecraft/join", func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
joinCalls++
calls := joinCalls
mu.Unlock()
if calls == 1 {
writeFakeYggdrasilJSON(w, http.StatusForbidden, `{"error":"ForbiddenOperationException","errorMessage":"Invalid token"}`)
return
}
w.WriteHeader(http.StatusNoContent)
})
server := httptest.NewServer(mux)
defer server.Close()
auth := newTestYggdrasilAuth(t, server.URL+"/api/yggdrasil", "SkinUser")
token, err := auth.join(context.Background(), "0123456789abcdef0123456789abcdef01234567")
if err != nil {
t.Fatalf("join: %v", err)
}
if token.accessToken != "token-2" {
t.Fatalf("token = %q", token.accessToken)
}
mu.Lock()
defer mu.Unlock()
if authenticateCalls != 2 || joinCalls != 2 {
t.Fatalf("calls: authenticate=%d join=%d", authenticateCalls, joinCalls)
}
}
func TestYggdrasilLoginFailure(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
defer ln.Close()
password := "yggdrasil-login-failure"
privateKey, publicKey := deriveTestRSAKey(t, password)
api := "http://127.0.0.1:1/api/yggdrasil"
go func() {
rawConn, err := ln.Accept()
if err != nil {
return
}
defer rawConn.Close()
verifier, err := newYggdrasilVerifier(api)
if err != nil {
return
}
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier)
if err != nil {
return
}
buf := make([]byte, 16)
_, _ = server.Read(buf)
}()
rawClient, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatalf("dial: %v", err)
}
defer rawClient.Close()
client, err := newClientConn(rawClient, nil, password, publicKey, "localhost", nil, newTestYggdrasilAuth(t, api, ""))
if err != nil {
t.Fatal(err)
}
client.SetDeadline(time.Now().Add(5 * time.Second))
if _, err := client.Write([]byte("x")); err == nil {
t.Fatal("expected yggdrasil login to fail")
}
}
func TestYggdrasilPropertyConversion(t *testing.T) {
properties := propertyListFromYggdrasil([]yggdrasilProperty{
{Name: "textures", Value: "value", Signature: "signature"},
{Name: "uploadableTextures", Value: "skin,cape"},
})
if len(properties) != 2 {
t.Fatalf("unexpected properties: %+v", properties)
}
if !properties[0].Signed || properties[0].Signature != "signature" {
t.Fatalf("signed property was not preserved: %+v", properties[0])
}
if properties[1].Signed {
t.Fatalf("unsigned property was marked signed: %+v", properties[1])
}
profile := loginProfile{
Username: "SkinUser",
Properties: properties,
}
textures, found := profile.textures()
if !found || textures.Value != "value" {
t.Fatalf("textures property not found: %+v", profile)
}
}
func TestYggdrasilVerifierCache(t *testing.T) {
first, err := yggdrasilVerifierFor("https://skin.example.com/api/yggdrasil")
if err != nil {
t.Fatal(err)
}
second, err := yggdrasilVerifierFor("https://skin.example.com/api/yggdrasil/")
if err != nil {
t.Fatal(err)
}
if first != second {
t.Fatal("the verifier was not reused for the same API root")
}
}
+2
View File
@@ -111,6 +111,7 @@ func dialhttpUpgrade(ctx context.Context, dest net.Destination, streamSettings *
err = req.Write(conn) err = req.Write(conn)
if err != nil { if err != nil {
conn.Close()
return nil, err return nil, err
} }
@@ -123,6 +124,7 @@ func dialhttpUpgrade(ctx context.Context, dest net.Destination, streamSettings *
if transportConfiguration.Ed == 0 { if transportConfiguration.Ed == 0 {
_, err = connRF.Read([]byte{}) _, err = connRF.Read([]byte{})
if err != nil { if err != nil {
conn.Close()
return nil, err return nil, err
} }
} }
+11 -11
View File
@@ -26,6 +26,7 @@ import (
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
http_proto "github.com/xtls/xray-core/common/protocol/http" http_proto "github.com/xtls/xray-core/common/protocol/http"
"github.com/xtls/xray-core/common/signal/done" "github.com/xtls/xray-core/common/signal/done"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet"
"github.com/xtls/xray-core/transport/internet/hysteria/congestion" "github.com/xtls/xray-core/transport/internet/hysteria/congestion"
"github.com/xtls/xray-core/transport/internet/hysteria/congestion/bbr" "github.com/xtls/xray-core/transport/internet/hysteria/congestion/bbr"
@@ -78,10 +79,9 @@ func (h *requestHandler) upsertSession(sessionId string) *httpSession {
h.sessions.Store(sessionId, s) h.sessions.Store(sessionId, s)
shouldReap := done.New() shouldReap := done.New()
go func() { time.AfterFunc(30*time.Second, func() {
time.Sleep(30 * time.Second)
shouldReap.Close() shouldReap.Close()
}() })
go func() { go func() {
select { select {
case <-shouldReap.Wait(): case <-shouldReap.Wait():
@@ -222,15 +222,15 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
scStreamUpServerSecs := h.config.GetNormalizedScStreamUpServerSecs() scStreamUpServerSecs := h.config.GetNormalizedScStreamUpServerSecs()
hasLegacyRefererCompatMarker := request.Header.Get("Referer") != "" hasLegacyRefererCompatMarker := request.Header.Get("Referer") != ""
if (hasLegacyRefererCompatMarker || obfsPaddingAccepted) && scStreamUpServerSecs.To > 0 { if (hasLegacyRefererCompatMarker || obfsPaddingAccepted) && scStreamUpServerSecs.To > 0 {
go func() { writePadding := &task.Periodic{
for { Execute: func() error {
_, err := httpSC.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand()))) _, err := httpSC.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand())))
if err != nil { return err
break },
} Interval: time.Duration(scStreamUpServerSecs.rand()) * time.Second,
time.Sleep(time.Duration(scStreamUpServerSecs.rand()) * time.Second) }
} defer writePadding.Close()
}() writePadding.Start()
} }
select { select {
case <-request.Context().Done(): case <-request.Context().Done():
+1 -1
View File
@@ -17,7 +17,7 @@ func DialTaggedOutbound(ctx context.Context, dispatcher routing.Dispatcher, dest
return nil, errors.New("Instance context variable is not in context, dial denied. ") return nil, errors.New("Instance context variable is not in context, dial denied. ")
} }
content := new(session.Content) content := new(session.Content)
content.SkipDNSResolve = true content.SkipDNSResolve = tag != ""
ctx = session.ContextWithContent(ctx, content) ctx = session.ContextWithContent(ctx, content)
ctx = session.SetForcedOutboundTagToContext(ctx, tag) ctx = session.SetForcedOutboundTagToContext(ctx, tag)
+17 -12
View File
@@ -6,9 +6,11 @@ import (
"time" "time"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/serial" "github.com/xtls/xray-core/common/serial"
"github.com/xtls/xray-core/common/task"
) )
var _ buf.Writer = (*connection)(nil) var _ buf.Writer = (*connection)(nil)
@@ -20,25 +22,27 @@ type connection struct {
conn *websocket.Conn conn *websocket.Conn
reader io.Reader reader io.Reader
remoteAddr net.Addr remoteAddr net.Addr
keepalive *task.Periodic
} }
func NewConnection(conn *websocket.Conn, remoteAddr net.Addr, extraReader io.Reader, heartbeatPeriod uint32) *connection { func NewConnection(conn *websocket.Conn, remoteAddr net.Addr, extraReader io.Reader, heartbeatPeriod uint32) *connection {
if heartbeatPeriod != 0 { wrappedConn := &connection{
go func() {
for {
time.Sleep(time.Duration(heartbeatPeriod) * time.Second)
if err := conn.WriteControl(websocket.PingMessage, []byte{}, time.Time{}); err != nil {
break
}
}
}()
}
return &connection{
conn: conn, conn: conn,
remoteAddr: remoteAddr, remoteAddr: remoteAddr,
reader: extraReader, reader: extraReader,
} }
if heartbeatPeriod != 0 {
keepalive := task.Periodic{
Execute: func() error {
return conn.WriteControl(websocket.PingMessage, []byte{}, time.Time{})
},
Interval: time.Duration(heartbeatPeriod) * time.Second,
}
keepalive.Start()
wrappedConn.keepalive = &keepalive
}
return wrappedConn
} }
// Read implements net.Conn.Read() // Read implements net.Conn.Read()
@@ -93,6 +97,7 @@ func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
} }
func (c *connection) Close() error { func (c *connection) Close() error {
common.CloseIfExists(c.keepalive)
var errs []interface{} var errs []interface{}
if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil { if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil {
errs = append(errs, err) errs = append(errs, err)