Compare commits

...
Author SHA1 Message Date
dependabot[bot]andGitHub f80315cdc2 Bump golang.org/x/net from 0.62.0 to 0.63.0
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.62.0 to 0.63.0.
- [Commits](https://github.com/golang/net/compare/v0.62.0...v0.63.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-version: 0.63.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-23 00:27:02 +00:00
AliceandGitHub 74cbdf46d8 README.md: Add keqdroid to Windows, Android and Linux in GUI Clients (#7446)
https://github.com/XTLS/Xray-core/pull/7429#issuecomment-6985957550
2026-11-21 21:38:21 +00:00
3dee8518c1 HTTPUpgrade client: Close the connection when the upgrade fails (#7395)
https://github.com/XTLS/Xray-core/pull/7395#issuecomment-6884592648

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 20:40:13 +00:00
MeowandGitHub 8f0bb9fbfa Outbounds: Avoid circular dependencies with the built-in DNS (#7425)
https://github.com/XTLS/Xray-core/pull/7425#issuecomment-6900056768
https://github.com/XTLS/Xray-core/pull/7425#issuecomment-6953371666
https://github.com/XTLS/Xray-core/pull/7425#issuecomment-7023506796
2026-11-21 20:37:44 +00:00
yangdujunandGitHub 5225121aab XMC finalmask: Yggdrasil third-party login and texture verification (#7416)
Closes https://github.com/XTLS/Xray-core/issues/7394
2026-11-21 20:15:31 +00:00
22 changed files with 2083 additions and 148 deletions
+3
View File
@@ -112,6 +112,7 @@
- [GenyConnect](https://github.com/genyleap/GenyConnect)
- [OneXray](https://github.com/OneXray/OneXray)
- [XrayUI-dev](https://github.com/PhoenixNil/XrayUI-dev)
- [keqdroid](https://github.com/Lemonochka/keqdroid)
- Android
- [v2rayNG](https://github.com/2dust/v2rayNG)
- [X-flutter](https://github.com/XTLS/X-flutter)
@@ -121,6 +122,7 @@
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
- [OneXray](https://github.com/OneXray/OneXray)
- [AsteriskNG](https://github.com/Asterisk4Magisk/AsteriskNG)
- [keqdroid](https://github.com/Lemonochka/keqdroid)
- 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)
- [Streisand](https://apps.apple.com/app/streisand/id6450534064)
@@ -146,6 +148,7 @@
- [v2rayN](https://github.com/2dust/v2rayN)
- [GenyConnect](https://github.com/genyleap/GenyConnect)
- [OneXray](https://github.com/OneXray/OneXray)
- [keqdroid](https://github.com/Lemonochka/keqdroid)
- HarmonyOS
- [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) {
outbounds := session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1]
content := session.ContentFromContext(ctx)
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() && (content == nil || !content.SkipDNSResolve) {
strategy := h.senderSettings.TargetStrategy
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
}
if h.senderSettings != nil && h.senderSettings.TargetStrategy.HasStrategy() && ob.Target.Address.Family().IsDomain() {
if session.SkipDNSResolveFromContext(ctx) {
errors.LogInfo(ctx, "bypassing targetStrategy ", h.senderSettings.TargetStrategy, " for ", ob.Target, "; preserving target domain")
} 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())
strategy := h.senderSettings.TargetStrategy
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 {
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 {
+2 -3
View File
@@ -44,9 +44,8 @@ func (c routingContext) GetRuleTag() string {
return ""
}
// GetSkipDNSResolve is a mock implementation here to match the interface,
// SkipDNSResolve is set from dns module, no use if coming from a protobuf object?
// TODO: please confirm @Vigilans
// GetSkipDNSResolve implements routing.Context.
// The protobuf RoutingContext has no skip flag, so API contexts use false.
func (c routingContext) GetSkipDNSResolve() bool {
return false
}
+5
View File
@@ -77,6 +77,11 @@ func ContentFromContext(ctx context.Context) *Content {
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 {
return context.WithValue(ctx, isReverseMuxKey, isReverseMux)
}
+6 -6
View File
@@ -23,12 +23,12 @@ require (
github.com/xtls/reality v0.0.0-20261108101329-4bb46b2afd8b
github.com/yuin/gopher-lua v1.1.2
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
golang.org/x/crypto v0.58.0
golang.org/x/crypto v0.59.0
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
golang.org/x/net v0.62.0
golang.org/x/sync v0.24.0
golang.org/x/sys v0.49.0
golang.org/x/net v0.63.0
golang.org/x/sync v0.25.0
golang.org/x/sys v0.50.0
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2
golang.zx2c4.com/wireguard v0.0.0-20250521234502-f333402bd9cb
golang.zx2c4.com/wireguard/windows v1.1.1
@@ -56,8 +56,8 @@ require (
github.com/vishvananda/netns v0.0.5 // indirect
github.com/wlynxg/anet v0.0.5 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/text v0.43.0 // indirect
golang.org/x/tools v0.51.0 // indirect
golang.org/x/text v0.44.0 // indirect
golang.org/x/tools v0.52.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 // indirect
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.2 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
+12 -14
View File
@@ -31,8 +31,6 @@ github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7Bd
github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI=
github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
@@ -97,8 +95,8 @@ go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBs
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a h1:V5oicZXS0oqZx30gY/apgSVD7YvNBfrIOdcMnlelJY4=
golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
@@ -109,12 +107,12 @@ golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -123,22 +121,22 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+92 -18
View File
@@ -2,6 +2,8 @@ package conf
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/hex"
@@ -961,10 +963,11 @@ func (c *XDNS) Build() (proto.Message, error) {
}
type XMC struct {
Hostname string `json:"hostname"`
Profiles []XMCProfile `json:"profiles"`
Password string `json:"password"`
Paddings []XMCPaddingTurn `json:"paddings,omitempty"`
Hostname string `json:"hostname"`
Profiles []XMCProfile `json:"profiles"`
Password string `json:"password"`
Paddings []XMCPaddingTurn `json:"paddings,omitempty"`
Yggdrasil *XMCYggdrasil `json:"yggdrasil,omitempty"`
// A configured list is the complete padding schedule and replaces the
// built-in preset entirely, including the preset's Play-state join tail.
// NoPadding disables padding. An explicit empty "paddings" array means the
@@ -982,6 +985,19 @@ type XMCPaddingTurn struct {
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 {
// Resolve the UUID by username, then request the session profile with
// 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) {
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
// Paddings nil when it is absent, so the user can turn padding off without
// a second switch.
@@ -1032,7 +1038,7 @@ func (c *XMC) Build() (proto.Message, error) {
if noPadding && len(c.Paddings) > 0 {
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 {
minimum, maximum, err := ParseRangeString(turn.Length)
if err != nil {
@@ -1065,9 +1071,75 @@ func (c *XMC) Build() (proto.Message, error) {
return nil, fmt.Errorf("minecraft padding: %w", err)
}
rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password)
if err != nil {
return nil, fmt.Errorf("derive minecraft rsa key: %w", err)
var yggdrasil *xmc.Yggdrasil
if c.Yggdrasil != nil {
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)
@@ -1084,9 +1156,11 @@ func (c *XMC) Build() (proto.Message, error) {
profiles = append(profiles, profile)
}
config.Password = password
config.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey)
config.RsaPublicKey = rsaPublicKey
config.Profiles = profiles
config.Yggdrasil = yggdrasil
return config, nil
}
@@ -1,6 +1,7 @@
package conf
import (
"crypto/x509"
"encoding/json"
"strings"
"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) {
profile := XMCProfile{
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.CanSpliceCopy = 1
if !h.usesDialerProxy && len(h.firewall) > 0 {
rule := h.firewall[0]
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
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)
content := new(session.Content)
content.SkipDNSResolve = true
content.SkipDNSResolve = session.SkipDNSResolveFromContext(ctx)
content.SniffingRequest = l.sniffingRequest
ctx = session.ContextWithContent(ctx, content)
+59 -10
View File
@@ -3,6 +3,7 @@ package xmc
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
@@ -29,6 +30,7 @@ type clientConn struct {
password string
rsaPublicKey []byte
hostname string
yggdrasil *yggdrasilAuth
paddingSchedule []paddingTurn
packet *packetStream
deadlines *connectionDeadlines
@@ -44,11 +46,11 @@ var (
clientStateProxy clientState = 2
)
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn) (*clientConn, error) {
if len(rsaPublicKey) == 0 {
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth) (*clientConn, error) {
if len(rsaPublicKey) == 0 && yggdrasil == nil {
return nil, fmt.Errorf("empty rsa public key")
}
if len(profiles) == 0 {
if len(profiles) == 0 && yggdrasil == nil {
return nil, fmt.Errorf("empty profiles")
}
if len(password) > MaxLegacyPasswordLength {
@@ -64,6 +66,7 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl
password: password,
rsaPublicKey: rsaPublicKey,
hostname: hostname,
yggdrasil: yggdrasil,
paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c),
done: make(chan struct{}),
@@ -113,11 +116,27 @@ func (c *clientConn) handshake() error {
}
// Login Start
randomProfile, err := rand.Int(rand.Reader, big.NewInt(int64(len(c.profiles))))
if err != nil {
return fmt.Errorf("select profile: %w", err)
var selectedProfile loginProfile
if c.yggdrasil != nil {
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)
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)
}
if !bytes.Equal(publicKey, c.rsaPublicKey) {
if c.yggdrasil == nil && !bytes.Equal(publicKey, c.rsaPublicKey) {
return fmt.Errorf("server public key mismatch")
}
@@ -159,6 +178,9 @@ func (c *clientConn) handshake() error {
if !ok {
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)
if _, err = rand.Read(sharedSecret); err != nil {
@@ -170,7 +192,9 @@ func (c *clientConn) handshake() error {
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)
if err != nil {
@@ -199,6 +223,24 @@ func (c *clientConn) handshake() error {
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)
if err != nil {
return fmt.Errorf("read login finished: %w", err)
@@ -236,7 +278,14 @@ func (c *clientConn) handshake() error {
if err != nil {
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")
}
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.
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) {
profiles, err := profilesFromConfig(c.Profiles)
if err != nil {
@@ -27,7 +39,24 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
if err != nil {
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 {
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 {
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 {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
+124 -25
View File
@@ -92,17 +92,101 @@ func (x *Profile) GetTexturesSignature() string {
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 {
state protoimpl.MessageState `protogen:"open.v1"`
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"`
state protoimpl.MessageState `protogen:"open.v1"`
// 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.
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.
// A configured list is the complete schedule and replaces 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"`
// 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
// 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"`
@@ -112,7 +196,7 @@ type Config struct {
func (x *Config) Reset() {
*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.StoreMessageInfo(mi)
}
@@ -124,7 +208,7 @@ func (x *Config) String() string {
func (*Config) ProtoMessage() {}
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 {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -137,7 +221,7 @@ func (x *Config) ProtoReflect() protoreflect.Message {
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
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 {
@@ -182,6 +266,13 @@ func (x *Config) GetPaddings() []*Padding {
return nil
}
func (x *Config) GetYggdrasil() *Yggdrasil {
if x != nil {
return x.Yggdrasil
}
return nil
}
func (x *Config) GetNoPadding() bool {
if x != nil {
return x.NoPadding
@@ -211,7 +302,7 @@ type Padding struct {
func (x *Padding) Reset() {
*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.StoreMessageInfo(mi)
}
@@ -223,7 +314,7 @@ func (x *Padding) String() string {
func (*Padding) ProtoMessage() {}
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 {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
@@ -236,7 +327,7 @@ func (x *Padding) ProtoReflect() protoreflect.Message {
// Deprecated: Use Padding.ProtoReflect.Descriptor instead.
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 {
@@ -283,7 +374,12 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\busername\x18\x01 \x01(\tR\busername\x12\x12\n" +
"\x04uuid\x18\x02 \x01(\fR\x04uuid\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" +
"\bpassword\x18\x01 \x01(\tR\bpassword\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" +
" \x01(\tR\bhostname\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" +
"no_padding\x18\x0e \x01(\bR\tnoPaddingJ\x04\b\x02\x10\x03\"\x9f\x01\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
}
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{
(*Profile)(nil), // 0: xray.transport.internet.finalmask.xmc.Profile
(*Config)(nil), // 1: xray.transport.internet.finalmask.xmc.Config
(*Padding)(nil), // 2: xray.transport.internet.finalmask.xmc.Padding
(*Profile)(nil), // 0: xray.transport.internet.finalmask.xmc.Profile
(*Yggdrasil)(nil), // 1: xray.transport.internet.finalmask.xmc.Yggdrasil
(*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{
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
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
3, // 1: xray.transport.internet.finalmask.xmc.Config.paddings:type_name -> xray.transport.internet.finalmask.xmc.Padding
1, // 2: xray.transport.internet.finalmask.xmc.Config.yggdrasil:type_name -> xray.transport.internet.finalmask.xmc.Yggdrasil
3, // [3:3] is the sub-list for method output_type
3, // [3:3] is the sub-list for method input_type
3, // [3:3] is the sub-list for extension 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() }
@@ -343,7 +442,7 @@ func file_transport_internet_finalmask_xmc_config_proto_init() {
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)),
NumEnums: 0,
NumMessages: 3,
NumMessages: 4,
NumExtensions: 0,
NumServices: 0,
},
@@ -16,7 +16,27 @@ message Profile {
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 {
// 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;
reserved 2;
bytes rsa_private_key = 8;
@@ -27,6 +47,9 @@ message Config {
// A configured list is the complete schedule and replaces the preset
// entirely: the preset's Play-state join tail runs only with the preset.
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
// empty "paddings" array, which an unset repeated field cannot express.
bool no_padding = 14;
@@ -16,10 +16,10 @@ func TestClientRejectsLongLegacyPassword(t *testing.T) {
profiles := []loginProfile{{Username: "TestUser"}}
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)
}
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")
}
}
@@ -130,7 +130,7 @@ func TestCloseCancelsPaddingPause(t *testing.T) {
client, server := net.Pipe()
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 {
t.Fatal(err)
}
@@ -55,7 +55,15 @@ func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, lengt
if err != nil {
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{
{Direction: 1, 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 {
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 {
t.Fatal(err)
}
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 {
t.Fatal(err)
}
+156 -23
View File
@@ -1,17 +1,136 @@
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 {
Username string
UUID UUID
TexturesValue string
TexturesSignature string
Username string
UUID UUID
Properties loginProperties
}
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) {
if len(configured) == 0 {
return nil, fmt.Errorf("empty profiles")
return nil, nil
}
profiles := make([]loginProfile, 0, len(configured))
@@ -27,9 +146,15 @@ func profilesFromConfig(configured []*Profile) ([]loginProfile, error) {
}
profile := loginProfile{
Username: configuredProfile.Username,
TexturesValue: configuredProfile.TexturesValue,
TexturesSignature: configuredProfile.TexturesSignature,
Username: configuredProfile.Username,
Properties: loginProperties{
{
Name: "textures",
Value: configuredProfile.TexturesValue,
Signature: configuredProfile.TexturesSignature,
Signed: true,
},
},
}
copy(profile.UUID[:], configuredProfile.Uuid)
profiles = append(profiles, profile)
@@ -39,31 +164,39 @@ func profilesFromConfig(configured []*Profile) ([]loginProfile, error) {
func findProfile(profiles []loginProfile, username string, uuid UUID) (loginProfile, bool) {
for _, profile := range profiles {
if profile.Username == username && profile.UUID == uuid {
if sameProfileIdentity(profile, loginProfile{Username: username, UUID: uuid}) {
return profile, true
}
}
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) {
var (
profile loginProfile
username String
propertyCount Varint
propertyName String
value String
signed Boolean
signature String
profile loginProfile
username 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
}
if propertyCount != 1 || propertyName != "textures" || !signed {
return loginProfile{}, fmt.Errorf("invalid login profile properties")
}
profile.Username = string(username)
profile.TexturesValue = string(value)
profile.TexturesSignature = string(signature)
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 (
"bufio"
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/subtle"
"crypto/x509"
"errors"
"fmt"
"io"
"net"
@@ -14,6 +16,18 @@ import (
"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.
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
rsaPrivateKey *rsa.PrivateKey
rsaPublicKey []byte
yggdrasil *yggdrasilVerifier
paddingSchedule []paddingTurn
packet *packetStream
deadlines *connectionDeadlines
@@ -216,27 +231,42 @@ func (c *serverConn) handshake() error {
return fmt.Errorf("new crypto writer: %w", err)
}
// 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)
if c.yggdrasil != nil {
// Online-mode login: verify the player through the session server
// instead of the pre-shared password and the static profile list.
if !bytes.Equal(decryptedVerifyToken, verifyToken) {
return fmt.Errorf("verify token mismatch")
}
serverID := minecraftServerID(string(serverId), sharedSecret, c.rsaPublicKey)
profile, err = c.verifyYggdrasilLogin(string(username), uuid, serverID)
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)
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 {
if err = writeLoginSuccess(c.writer, profile); err != nil {
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 {
if pkt.packetID != 0x03 {
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)
}
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn) (*serverConn, error) {
if len(profiles) == 0 {
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn, yggdrasil *yggdrasilVerifier) (*serverConn, error) {
if len(profiles) == 0 && yggdrasil == nil {
return nil, fmt.Errorf("empty profiles")
}
if len(rsaPrivateKeyDER) == 0 {
@@ -363,6 +437,7 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
password: password,
rsaPrivateKey: rsaPrivateKey,
rsaPublicKey: rsaPublicKey,
yggdrasil: yggdrasil,
paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c),
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)
if err != nil {
conn.Close()
return nil, err
}
@@ -123,6 +124,7 @@ func dialhttpUpgrade(ctx context.Context, dest net.Destination, streamSettings *
if transportConfiguration.Ed == 0 {
_, err = connRF.Read([]byte{})
if err != nil {
conn.Close()
return nil, err
}
}
+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. ")
}
content := new(session.Content)
content.SkipDNSResolve = true
content.SkipDNSResolve = tag != ""
ctx = session.ContextWithContent(ctx, content)
ctx = session.SetForcedOutboundTagToContext(ctx, tag)