/
session_client_initial_login.go
373 lines (326 loc) · 10.4 KB
/
session_client_initial_login.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package proxy
import (
"bytes"
"context"
"crypto/rand"
"errors"
"go.minekube.com/gate/pkg/edition/java/proto/state"
"regexp"
"time"
"github.com/go-logr/logr"
"go.minekube.com/common/minecraft/color"
"go.minekube.com/common/minecraft/component"
"go.minekube.com/gate/pkg/edition/java/netmc"
"go.minekube.com/gate/pkg/edition/java/proto/util"
"go.minekube.com/gate/pkg/edition/java/proxy/crypto"
"go.minekube.com/gate/pkg/edition/java/proxy/crypto/keyrevision"
"go.minekube.com/gate/pkg/edition/java/profile"
"go.minekube.com/gate/pkg/edition/java/proto/packet"
"go.minekube.com/gate/pkg/edition/java/proto/version"
"go.minekube.com/gate/pkg/gate/proto"
"go.minekube.com/gate/pkg/util/netutil"
)
type initialLoginSessionHandler struct {
*sessionHandlerDeps
conn netmc.MinecraftConn
inbound *loginInboundConn
log logr.Logger
nopSessionHandler
currentState loginState
login *packet.ServerLogin
verify []byte
}
type loginState string
const (
loginPacketExpectedLoginState loginState = "loginPacketExpected"
loginPacketReceivedLoginState loginState = "loginPacketReceived"
encryptionRequestSentLoginState loginState = "encryptionRequestSent"
encryptionResponseReceivedLoginState loginState = "encryptionResponseReceived"
)
func newInitialLoginSessionHandler(
conn netmc.MinecraftConn,
inbound *loginInboundConn,
deps *sessionHandlerDeps,
) netmc.SessionHandler {
return &initialLoginSessionHandler{
sessionHandlerDeps: deps,
conn: conn,
inbound: inbound,
log: logr.FromContextOrDiscard(conn.Context()).WithName("loginSession"),
currentState: loginPacketExpectedLoginState,
}
}
var invalidPlayerName = &component.Text{
Content: "Your username has an invalid format.",
S: component.Style{Color: color.Red},
}
func (l *initialLoginSessionHandler) HandlePacket(p *proto.PacketContext) {
if !p.KnownPacket() {
// unknown packet, close connection
_ = l.conn.Close()
return
}
switch t := p.Packet.(type) {
case *packet.ServerLogin:
l.handleServerLogin(t)
case *packet.LoginPluginResponse:
_ = l.inbound.handleLoginPluginResponse(t)
case *packet.EncryptionResponse:
l.handleEncryptionResponse(t)
default:
// got unexpected packet, simply close
_ = l.conn.Close()
}
}
var playerNameRegex = regexp.MustCompile(`^[A-Za-z0-9_]{2,16}$`)
// GameProfileProvider provides the GameProfile for a player connection.
type GameProfileProvider interface {
GameProfile() (profile *profile.GameProfile)
}
func (l *initialLoginSessionHandler) handleServerLogin(login *packet.ServerLogin) {
if !l.assertState(loginPacketExpectedLoginState) {
return
}
l.currentState = loginPacketReceivedLoginState
// Validate username format
if !playerNameRegex.MatchString(login.Username) {
_ = l.inbound.disconnect(invalidPlayerName)
return
}
playerKey := login.PlayerKey
if playerKey != nil {
if playerKey.Expired() {
l.log.V(1).Info("expired player public key")
_ = l.inbound.disconnect(&component.Translation{
Key: "multiplayer.disconnect.invalid_public_key_signature",
})
return
}
var isKeyValid bool
if playerKey.KeyRevision() == keyrevision.LinkedV2 && crypto.CanSetHolder(playerKey) {
isKeyValid = crypto.SetHolder(playerKey, login.HolderID)
} else {
isKeyValid = playerKey.SignatureValid()
}
if !isKeyValid {
l.log.V(1).Info("invalid player public key signature")
_ = l.inbound.disconnect(&component.Translation{
Key: "multiplayer.disconnect.invalid_public_key",
})
return
}
} else if l.conn.Protocol().GreaterEqual(version.Minecraft_1_19) &&
l.config().ForceKeyAuthentication &&
l.conn.Protocol().Lower(version.Minecraft_1_19_3) {
_ = l.inbound.disconnect(&component.Translation{
Key: "multiplayer.disconnect.missing_public_key",
})
return
}
l.inbound.playerKey = playerKey
l.login = login
e := newPreLoginEvent(l.inbound, l.login.Username)
l.eventMgr.Fire(e)
if netmc.Closed(l.conn) {
return // Player was disconnected
}
if e.Result() == DeniedPreLogin {
_ = l.inbound.disconnect(e.Reason())
return
}
_ = l.inbound.loginEventFired(func() error {
if netmc.Closed(l.conn) {
return nil // Player was disconnected
}
if e.Result() != ForceOfflineModePreLogin &&
(e.Result() == ForceOnlineModePreLogin || l.config().OnlineMode) {
if p, ok := netmc.Assert[GameProfileProvider](l.conn); ok {
sh := l.newAuthSessionHandler(l.inbound, p.GameProfile(), false)
l.conn.SetActiveSessionHandler(state.Login, sh)
return nil
}
// Online mode login, send encryption request
request := l.generateEncryptionRequest()
l.verify = make([]byte, len(request.VerifyToken))
copy(l.verify, request.VerifyToken)
err := l.conn.WritePacket(request)
if err != nil {
return err
}
l.currentState = encryptionRequestSentLoginState
// Wait for EncryptionResponse packet
return nil
}
// Offline mode login
sh := l.newAuthSessionHandler(l.inbound, profile.NewOffline(l.login.Username), false)
l.conn.SetActiveSessionHandler(state.Login, sh)
return nil
})
}
func (l *initialLoginSessionHandler) newAuthSessionHandler(
inbound *loginInboundConn,
profile *profile.GameProfile,
onlineMode bool,
) netmc.SessionHandler {
return newAuthSessionHandler(
inbound,
profile,
onlineMode,
l.sessionHandlerDeps,
)
}
func (l *initialLoginSessionHandler) generateEncryptionRequest() *packet.EncryptionRequest {
verify := make([]byte, 4)
_, _ = rand.Read(verify)
return &packet.EncryptionRequest{
PublicKey: l.auth().PublicKey(),
VerifyToken: verify,
}
}
var unableAuthWithMojang = &component.Text{
Content: "Unable to authenticate you with Mojang.\nPlease try again!",
S: component.Style{Color: color.Red},
}
func (l *initialLoginSessionHandler) handleEncryptionResponse(resp *packet.EncryptionResponse) {
if !l.assertState(encryptionRequestSentLoginState) {
return
}
l.currentState = encryptionResponseReceivedLoginState
if l.login == nil {
l.log.V(1).Info("no ServerLogin packet received yet, disconnecting")
_ = l.conn.Close()
return
}
if len(l.verify) == 0 {
l.log.V(1).Info("no EncryptionRequest packet sent yet, disconnecting")
_ = l.conn.Close()
return
}
if playerKey := l.inbound.IdentifiedKey(); playerKey != nil {
if resp.Salt == nil {
l.log.V(1).Info("encryption response did not contain salt")
_ = l.conn.Close()
return
}
salt := new(bytes.Buffer)
_ = util.WriteInt64(salt, *resp.Salt)
valid := playerKey.VerifyDataSignature(resp.VerifyToken, l.verify, salt.Bytes())
if !valid {
l.log.Info("invalid client public signature")
_ = l.conn.Close()
return
}
} else {
valid, err := l.auth().Verify(resp.VerifyToken, l.verify)
if err != nil {
// Simply close the connection without much overhead.
_ = l.conn.Close()
return
}
if !valid {
l.log.Info("invalid verification token")
_ = l.conn.Close()
return
}
}
authn := l.auth()
decryptedSharedSecret, err := authn.DecryptSharedSecret(resp.SharedSecret)
if err != nil {
// Simple close the connection without much overhead.
_ = l.conn.Close()
return
}
// Enable encryption.
// Once the client sends EncryptionResponse, encryption is enabled.
if err = l.conn.EnableEncryption(decryptedSharedSecret); err != nil {
l.log.Error(err, "error enabling encryption for connecting player")
_ = netmc.CloseWith(l.conn, packet.NewDisconnect(internalServerConnectionError, l.conn.Protocol(), true))
return
}
var optionalUserIP string
if l.config().ShouldPreventClientProxyConnections {
optionalUserIP = netutil.Host(l.conn.RemoteAddr())
}
serverID, err := authn.GenerateServerID(decryptedSharedSecret)
if err != nil {
// Simple close the connection without much overhead.
_ = l.inbound.disconnect(unableAuthWithMojang)
return
}
log := l.log.WithName("authn")
ctx, cancel := context.WithTimeout(logr.NewContext(l.conn.Context(), log), 30*time.Second)
defer cancel()
authResp, err := authn.AuthenticateJoin(ctx, serverID, l.login.Username, optionalUserIP)
if err != nil {
if errors.Is(err, context.Canceled) {
// The player disconnected before receiving authentication response.
return
}
_ = netmc.CloseWith(l.conn, packet.NewDisconnect(unableAuthWithMojang, l.conn.Protocol(), true))
return
}
if !authResp.OnlineMode() {
log.Info("disconnect offline mode player")
// Apparently an offline-mode user logged onto this online-mode proxy.
_ = netmc.CloseWith(l.conn, packet.NewDisconnect(onlineModeOnly, l.conn.Protocol(), true))
return
}
// Extract game profile from response.
gameProfile, err := authResp.GameProfile()
if err != nil {
if netmc.CloseWith(l.conn, packet.NewDisconnect(unableAuthWithMojang, l.conn.Protocol(), true)) == nil {
log.Error(err, "unable get GameProfile from Mojang authentication response")
}
return
}
// All went well, initialize the session.
sh := l.newAuthSessionHandler(l.inbound, gameProfile, true)
l.conn.SetActiveSessionHandler(state.Login, sh)
}
var (
onlineModeOnly = &component.Text{
Content: `This server only accepts connections from online-mode clients.
Did you change your username?
Restart your game or sign out of Minecraft, sign back in, and try again.`,
S: component.Style{Color: color.Red},
}
)
// Temporary english messages until localization support
var (
alreadyConnected = &component.Text{
Content: "You are already connected to this server!",
}
alreadyInProgress = &component.Text{
Content: "You are already connecting to a server!",
}
noAvailableServers = &component.Text{
Content: "No available server.", S: component.Style{Color: color.Red},
}
internalServerConnectionError = &component.Text{
Content: "Internal server connection error",
}
// unexpectedDisconnect = &component.Text{
// Content: "Unexpectedly disconnected from remote server - crash?",
// }
movedToNewServer = &component.Text{
Content: "The server you were on kicked you: ",
S: component.Style{Color: color.Red},
}
illegalChatCharacters = &component.Text{
Content: "Illegal characters in chat",
S: component.Style{Color: color.Red},
}
)
func (l *initialLoginSessionHandler) Disconnected() {
l.inbound.cleanup()
}
func (l *initialLoginSessionHandler) assertState(expectedState loginState) bool {
if l.currentState == expectedState {
return true
}
l.log.Info("received an unexpected packet during initial login session",
"currentState", l.currentState,
"expectedState", expectedState)
_ = l.conn.Close()
return false
}