NetHandlerLoginServer

Server login state machine (HELLO/KEY/AUTHENTICATING/READY): S01 encryption challenge, S02 success, S03 compression.

net/minecraft/server/network/NetHandlerLoginServer.java

Updated 2026-09-12

Deep Analysis

Login-state machine HELLO>KEY>AUTHENTICATING>READY>ACCEPTED. Validates C00 start and C01 encryption, verifies Mojang session off-thread, then hands to ServerConfigurationManager or disconnects.

Key Methods in Depth (6)

processLoginStart

Starts login or requests encryption.

processLoginStart handles C00 hello and branches online versus offline login. It validates state equals HELLO via Validate, throwing on duplicate hello. It stores the GameProfile from the packet. If online mode is enabled and the channel is not local, it moves to KEY state and sends S01 EncryptionRequest with empty serverId, server public key and four-byte verifyToken. Otherwise for offline or singleplayer it jumps directly to READY_TO_ACCEPT. No kick occurs here, errors throw IllegalStateException. The verifyToken nonce later proves the client holds the private key. Local channels skip encryption to reduce latency.

    public void processLoginStart(C00PacketLoginStart packetIn)
    {
        Validate.validState(this.currentLoginState == NetHandlerLoginServer.LoginState.HELLO, "Unexpected hello packet", new Object[0]);
        this.loginGameProfile = packetIn.getProfile();

        if (this.server.isServerInOnlineMode() && !this.networkManager.isLocalChannel())
        {
            this.currentLoginState = NetHandlerLoginServer.LoginState.KEY;
            this.networkManager.sendPacket(new S01PacketEncryptionRequest(this.serverId, this.server.getKeyPair().getPublic(), this.verifyToken));
        }
        else
        {
            this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT;
        }
    }

Validate.validState enforces the HELLO to KEY to AUTH state machine and rejects replays. Storing loginGameProfile preserves the requested name for later Mojang verification. The online-mode plus not-local gate selects encrypted versus instant accept. S01PacketEncryptionRequest carries serverId, public key and verifyToken nonce. The else moves offline logins straight to READY_TO_ACCEPT for tryAcceptPlayer.

processEncryptionResponse

Verifies nonce and enables crypto.

processEncryptionResponse handles C01 key exchange in KEY state. It validates KEY state, fetches the server private key and compares the decrypted verifyToken with Arrays equals, throwing Invalid nonce on mismatch to block replay. On match it decrypts the shared secret, moves to AUTHENTICATING and enables encryption on the channel. It then spawns User Authenticator thread with incrementing ID to avoid blocking netty. That thread hashes serverId, public key and secret via CryptManager, calls hasJoinedServer to verify the Mojang session, and on success sets READY_TO_ACCEPT. Singleplayer fallback generates offline profiles when verification fails or auth servers are down, otherwise it closes with Failed to verify username. No S packets are sent here directly.

    public void processEncryptionResponse(C01PacketEncryptionResponse packetIn)
    {
        Validate.validState(this.currentLoginState == NetHandlerLoginServer.LoginState.KEY, "Unexpected key packet", new Object[0]);
        PrivateKey privatekey = this.server.getKeyPair().getPrivate();

        if (!Arrays.equals(this.verifyToken, packetIn.getVerifyToken(privatekey)))
        {
            throw new IllegalStateException("Invalid nonce!");
        }
        else
        {
            this.secretKey = packetIn.getSecretKey(privatekey);
            this.currentLoginState = NetHandlerLoginServer.LoginState.AUTHENTICATING;
            this.networkManager.enableEncryption(this.secretKey);
            (new Thread("User Authenticator #" + AUTHENTICATOR_THREAD_ID.incrementAndGet())

The KEY state check rejects out-of-order C01 packets. Decrypting verifyToken with the private key and comparing to stored nonce detects tampering. Throwing Invalid nonce aborts the login without a graceful S00. Storing secretKey, setting AUTHENTICATING and enabling encryption switch the channel to ciphered mode. Spawning the authenticator thread offloads the blocking Mojang HTTPS check.

update

Advances ready/delayed accept and timeout.

update ticks the login state machine and enforces the 600-tick timeout. If state is READY_TO_ACCEPT it calls tryAcceptPlayer immediately to apply bans and compression. If state is DELAY_ACCEPT it polls for the duplicate old player by UUID, and when null it flips to READY_TO_ACCEPT, initializes the new player and clears the pending reference. It increments connectionTimer every tick and closes with Took too long to log in via S00 Disconnect at exactly 600. DELAY_ACCEPT exists because createPlayerForUser kicks the old session but the logout needs ticks to complete. No PLAY packets are sent here, only login S00, S02 and S03 via helpers. Stuck AUTHENTICATING threads eventually hit the same timeout.

    public void update()
    {
        if (this.currentLoginState == NetHandlerLoginServer.LoginState.READY_TO_ACCEPT)
        {
            this.tryAcceptPlayer();
        }
        else if (this.currentLoginState == NetHandlerLoginServer.LoginState.DELAY_ACCEPT)
        {
            EntityPlayerMP entityplayermp = this.server.getConfigurationManager().getPlayerByUUID(this.loginGameProfile.getId());

            if (entityplayermp == null)
            {
                this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT;
                this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, this.player);
                this.player = null;
            }
        }

        if (this.connectionTimer++ == 600)
        {
            this.closeConnection("Took too long to log in");
        }
    }

The READY_TO_ACCEPT branch drives immediate accept without waiting for network events. The DELAY_ACCEPT branch looks up the old UUID entry to detect when the kicked duplicate has logged out. Null means safe to initializeConnectionToPlayer with the staged player object. The connectionTimer post-increment equals 600 gate sends S00 Took too long to log in. That timeout bounds Mojang outages and stalled encryption handshakes.

tryAcceptPlayer

Applies bans, compression and success.

tryAcceptPlayer applies final login gates and switches to PLAY. It completes incomplete profiles with getOfflineProfile deriving OfflinePlayer UUIDs. It calls allowUserToConnect and closes with the ban, whitelist, IP or full reason when non-null. On success it sets ACCEPTED, and if compression threshold is non-negative on a remote channel it sends S03 EnableCompression then sets the threshold on future. It sends S02 LoginSuccess with the verified profile to trigger client PLAY switch. It checks for duplicate UUID sessions, staging a new player and entering DELAY_ACCEPT when found, otherwise initializing immediately via createPlayerForUser. No teleport occurs, the follow-up initializeConnectionToPlayer sends the S01 burst. Offline servers always take the instant path.

        String s = this.server.getConfigurationManager().allowUserToConnect(this.networkManager.getRemoteAddress(), this.loginGameProfile);

        if (s != null)
        {
            this.closeConnection(s);
        }
        else
        {
            this.currentLoginState = NetHandlerLoginServer.LoginState.ACCEPTED;

            if (this.server.getNetworkCompressionTreshold() >= 0 && !this.networkManager.isLocalChannel())
            {
                this.networkManager.sendPacket(new S03PacketEnableCompression(this.server.getNetworkCompressionTreshold()), new ChannelFutureListener()
                {
                    public void operationComplete(ChannelFuture p_operationComplete_1_) throws Exception
                    {
                        NetHandlerLoginServer.this.networkManager.setCompressionTreshold(NetHandlerLoginServer.this.server.getNetworkCompressionTreshold());
                    }
                }, new GenericFutureListener[0]);
            }

            this.networkManager.sendPacket(new S02PacketLoginSuccess(this.loginGameProfile));
            EntityPlayerMP entityplayermp = this.server.getConfigurationManager().getPlayerByUUID(this.loginGameProfile.getId());

            if (entityplayermp != null)
            {
                this.currentLoginState = NetHandlerLoginServer.LoginState.DELAY_ACCEPT;
                this.player = this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile);
            }
            else
            {
                this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile));
            }

allowUserToConnect returns null only when bans, whitelist, IP and capacity all pass. Non-null triggers closeConnection with S00 carrying that reason. Setting ACCEPTED plus S03 EnableCompression negotiates compression before LoginSuccess. S02PacketLoginSuccess carries the final UUID and name to switch the client to PLAY. The UUID duplicate check stages DELAY_ACCEPT versus immediate initializeConnectionToPlayer for overlap handling.

closeConnection

Sends kick and closes channel.

closeConnection terminates a login with S00 Disconnect and channel close. It logs the connection info plus reason for audit. It wraps the reason in ChatComponentText, sends S00PacketDisconnect, then closes the channel with the same component. Exceptions during send or close are caught and logged as Error whilst disconnecting player without rethrow. It is used for ban kicks, auth failures, duplicate handling and the 600-tick timeout. No PLAY packets are involved because the pipeline is still in LOGIN state. The client displays the text on the disconnected screen.

    public void closeConnection(String reason)
    {
        try
        {
            logger.info("Disconnecting " + this.getConnectionInfo() + ": " + reason);
            ChatComponentText chatcomponenttext = new ChatComponentText(reason);
            this.networkManager.sendPacket(new S00PacketDisconnect(chatcomponenttext));
            this.networkManager.closeChannel(chatcomponenttext);
        }
        catch (Exception exception)
        {
            logger.error((String)"Error whilst disconnecting player", (Throwable)exception);
        }
    }

The try block ensures logging and packet send happen atomically. getConnectionInfo includes profile and remote address for forensics. S00PacketDisconnect carries the human-readable kick reason to the client. closeChannel with the same component tears down the netty pipeline. The catch prevents disconnect-path exceptions from crashing the server tick.

getOfflineProfile

Derives offline UUID profile.

getOfflineProfile derives deterministic offline UUIDs for cracked and singleplayer logins. It concatenates OfflinePlayer colon plus original name, encodes as UTF-8 bytes and hashes with nameUUIDFromBytes version three. It returns a new GameProfile with that UUID and the original name preserving case. It is called by tryAcceptPlayer for incomplete profiles and by the auth thread when Mojang verification fails on singleplayer or auth servers are down. Online verified logins never use this path. No packets are sent here, the UUID feeds allowUserToConnect and S02 LoginSuccess. The deterministic mapping lets offline servers keep consistent inventories by name.

    protected GameProfile getOfflineProfile(GameProfile original)
    {
        UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + original.getName()).getBytes(Charsets.UTF_8));
        return new GameProfile(uuid, original.getName());
    }

    static enum LoginState
    {
        HELLO,
        KEY,

The OfflinePlayer prefix plus name string is the canonical offline seed. getBytes with UTF_8 ensures cross-platform UUID stability. nameUUIDFromBytes produces a version-three UUID from that seed. Returning a GameProfile with that UUID and original name lets bans and NBT key by stable id. The following LoginState enum defines HELLO, KEY and later states for the handshake.

Packet Usage

PacketDirTrigger
C00handledClient hello with GameProfile
C01handledEncrypted secret and verify token
S00sentLogin disconnect with reason
S01sentEncryption request in online mode
S02sentLogin success before PLAY switch
S03sentEnable compression if threshold set

Internal State

currentLoginStateHELLO/KEY/AUTH/READY/DELAY/ACCEPTED enum
verifyToken4-byte nonce to prevent replay
loginGameProfilePending profile, completed after auth
connectionTimerTicks since construct; 600 timeout
secretKeyShared secret enabling encryption

Related Vanilla Internals

Full Source

NetHandlerLoginServer.java248 lines · MCP 1.8.9 · verbatimOriginal ↗
1
package net.minecraft.server.network;
2
3
import com.google.common.base.Charsets;
4
import com.mojang.authlib.GameProfile;
5
import com.mojang.authlib.exceptions.AuthenticationUnavailableException;
6
import io.netty.channel.ChannelFuture;
7
import io.netty.channel.ChannelFutureListener;
8
import io.netty.util.concurrent.GenericFutureListener;
9
import java.math.BigInteger;
10
import java.security.PrivateKey;
11
import java.util.Arrays;
12
import java.util.Random;
13
import java.util.UUID;
14
import java.util.concurrent.atomic.AtomicInteger;
15
import javax.crypto.SecretKey;
16
import net.minecraft.entity.player.EntityPlayerMP;
17
import net.minecraft.network.NetworkManager;
18
import net.minecraft.network.login.INetHandlerLoginServer;
19
import net.minecraft.network.login.client.C00PacketLoginStart;
20
import net.minecraft.network.login.client.C01PacketEncryptionResponse;
21
import net.minecraft.network.login.server.S00PacketDisconnect;
22
import net.minecraft.network.login.server.S01PacketEncryptionRequest;
23
import net.minecraft.network.login.server.S02PacketLoginSuccess;
24
import net.minecraft.network.login.server.S03PacketEnableCompression;
25
import net.minecraft.server.MinecraftServer;
26
import net.minecraft.util.ChatComponentText;
27
import net.minecraft.util.CryptManager;
28
import net.minecraft.util.IChatComponent;
29
import net.minecraft.util.ITickable;
30
import org.apache.commons.lang3.Validate;
31
import org.apache.logging.log4j.LogManager;
32
import org.apache.logging.log4j.Logger;
33
34
public class NetHandlerLoginServer implements INetHandlerLoginServer, ITickable
35
{
36
    private static final AtomicInteger AUTHENTICATOR_THREAD_ID = new AtomicInteger(0);
37
    private static final Logger logger = LogManager.getLogger();
38
    private static final Random RANDOM = new Random();
39
    private final byte[] verifyToken = new byte[4];
40
    private final MinecraftServer server;
41
    public final NetworkManager networkManager;
42
    private NetHandlerLoginServer.LoginState currentLoginState = NetHandlerLoginServer.LoginState.HELLO;
43
44
    /** How long has player been trying to login into the server. */
45
    private int connectionTimer;
46
    private GameProfile loginGameProfile;
47
    private String serverId = "";
48
    private SecretKey secretKey;
49
    private EntityPlayerMP player;
50
51
    public NetHandlerLoginServer(MinecraftServer serverIn, NetworkManager networkManagerIn)
52
    {
53
        this.server = serverIn;
54
        this.networkManager = networkManagerIn;
55
        RANDOM.nextBytes(this.verifyToken);
56
    }
57
58
    /**
59
     * Like the old updateEntity(), except more generic.
60
     */
61
    public void update()
62
    {
63
        if (this.currentLoginState == NetHandlerLoginServer.LoginState.READY_TO_ACCEPT)
64
        {
65
            this.tryAcceptPlayer();
66
        }
67
        else if (this.currentLoginState == NetHandlerLoginServer.LoginState.DELAY_ACCEPT)
68
        {
69
            EntityPlayerMP entityplayermp = this.server.getConfigurationManager().getPlayerByUUID(this.loginGameProfile.getId());
70
71
            if (entityplayermp == null)
72
            {
73
                this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT;
74
                this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, this.player);
75
                this.player = null;
76
            }
77
        }
78
79
        if (this.connectionTimer++ == 600)
80
        {
81
            this.closeConnection("Took too long to log in");
82
        }
83
    }
84
85
    public void closeConnection(String reason)
86
    {
87
        try
88
        {
89
            logger.info("Disconnecting " + this.getConnectionInfo() + ": " + reason);
90
            ChatComponentText chatcomponenttext = new ChatComponentText(reason);
91
            this.networkManager.sendPacket(new S00PacketDisconnect(chatcomponenttext));
92
            this.networkManager.closeChannel(chatcomponenttext);
93
        }
94
        catch (Exception exception)
95
        {
96
            logger.error((String)"Error whilst disconnecting player", (Throwable)exception);
97
        }
98
    }
99
100
    public void tryAcceptPlayer()
101
    {
102
        if (!this.loginGameProfile.isComplete())
103
        {
104
            this.loginGameProfile = this.getOfflineProfile(this.loginGameProfile);
105
        }
106
107
        String s = this.server.getConfigurationManager().allowUserToConnect(this.networkManager.getRemoteAddress(), this.loginGameProfile);
108
109
        if (s != null)
110
        {
111
            this.closeConnection(s);
112
        }
113
        else
114
        {
115
            this.currentLoginState = NetHandlerLoginServer.LoginState.ACCEPTED;
116
117
            if (this.server.getNetworkCompressionTreshold() >= 0 && !this.networkManager.isLocalChannel())
118
            {
119
                this.networkManager.sendPacket(new S03PacketEnableCompression(this.server.getNetworkCompressionTreshold()), new ChannelFutureListener()
120
                {
121
                    public void operationComplete(ChannelFuture p_operationComplete_1_) throws Exception
122
                    {
123
                        NetHandlerLoginServer.this.networkManager.setCompressionTreshold(NetHandlerLoginServer.this.server.getNetworkCompressionTreshold());
124
                    }
125
                }, new GenericFutureListener[0]);
126
            }
127
128
            this.networkManager.sendPacket(new S02PacketLoginSuccess(this.loginGameProfile));
129
            EntityPlayerMP entityplayermp = this.server.getConfigurationManager().getPlayerByUUID(this.loginGameProfile.getId());
130
131
            if (entityplayermp != null)
132
            {
133
                this.currentLoginState = NetHandlerLoginServer.LoginState.DELAY_ACCEPT;
134
                this.player = this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile);
135
            }
136
            else
137
            {
138
                this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile));
139
            }
140
        }
141
    }
142
143
    /**
144
     * Invoked when disconnecting, the parameter is a ChatComponent describing the reason for termination
145
     */
146
    public void onDisconnect(IChatComponent reason)
147
    {
148
        logger.info(this.getConnectionInfo() + " lost connection: " + reason.getUnformattedText());
149
    }
150
151
    public String getConnectionInfo()
152
    {
153
        return this.loginGameProfile != null ? this.loginGameProfile.toString() + " (" + this.networkManager.getRemoteAddress().toString() + ")" : String.valueOf((Object)this.networkManager.getRemoteAddress());
154
    }
155
156
    public void processLoginStart(C00PacketLoginStart packetIn)
157
    {
158
        Validate.validState(this.currentLoginState == NetHandlerLoginServer.LoginState.HELLO, "Unexpected hello packet", new Object[0]);
159
        this.loginGameProfile = packetIn.getProfile();
160
161
        if (this.server.isServerInOnlineMode() && !this.networkManager.isLocalChannel())
162
        {
163
            this.currentLoginState = NetHandlerLoginServer.LoginState.KEY;
164
            this.networkManager.sendPacket(new S01PacketEncryptionRequest(this.serverId, this.server.getKeyPair().getPublic(), this.verifyToken));
165
        }
166
        else
167
        {
168
            this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT;
169
        }
170
    }
171
172
    public void processEncryptionResponse(C01PacketEncryptionResponse packetIn)
173
    {
174
        Validate.validState(this.currentLoginState == NetHandlerLoginServer.LoginState.KEY, "Unexpected key packet", new Object[0]);
175
        PrivateKey privatekey = this.server.getKeyPair().getPrivate();
176
177
        if (!Arrays.equals(this.verifyToken, packetIn.getVerifyToken(privatekey)))
178
        {
179
            throw new IllegalStateException("Invalid nonce!");
180
        }
181
        else
182
        {
183
            this.secretKey = packetIn.getSecretKey(privatekey);
184
            this.currentLoginState = NetHandlerLoginServer.LoginState.AUTHENTICATING;
185
            this.networkManager.enableEncryption(this.secretKey);
186
            (new Thread("User Authenticator #" + AUTHENTICATOR_THREAD_ID.incrementAndGet())
187
            {
188
                public void run()
189
                {
190
                    GameProfile gameprofile = NetHandlerLoginServer.this.loginGameProfile;
191
192
                    try
193
                    {
194
                        String s = (new BigInteger(CryptManager.getServerIdHash(NetHandlerLoginServer.this.serverId, NetHandlerLoginServer.this.server.getKeyPair().getPublic(), NetHandlerLoginServer.this.secretKey))).toString(16);
195
                        NetHandlerLoginServer.this.loginGameProfile = NetHandlerLoginServer.this.server.getMinecraftSessionService().hasJoinedServer(new GameProfile((UUID)null, gameprofile.getName()), s);
196
197
                        if (NetHandlerLoginServer.this.loginGameProfile != null)
198
                        {
199
                            NetHandlerLoginServer.logger.info("UUID of player " + NetHandlerLoginServer.this.loginGameProfile.getName() + " is " + NetHandlerLoginServer.this.loginGameProfile.getId());
200
                            NetHandlerLoginServer.this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT;
201
                        }
202
                        else if (NetHandlerLoginServer.this.server.isSinglePlayer())
203
                        {
204
                            NetHandlerLoginServer.logger.warn("Failed to verify username but will let them in anyway!");
205
                            NetHandlerLoginServer.this.loginGameProfile = NetHandlerLoginServer.this.getOfflineProfile(gameprofile);
206
                            NetHandlerLoginServer.this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT;
207
                        }
208
                        else
209
                        {
210
                            NetHandlerLoginServer.this.closeConnection("Failed to verify username!");
211
                            NetHandlerLoginServer.logger.error("Username \'" + NetHandlerLoginServer.this.loginGameProfile.getName() + "\' tried to join with an invalid session");
212
                        }
213
                    }
214
                    catch (AuthenticationUnavailableException var3)
215
                    {
216
                        if (NetHandlerLoginServer.this.server.isSinglePlayer())
217
                        {
218
                            NetHandlerLoginServer.logger.warn("Authentication servers are down but will let them in anyway!");
219
                            NetHandlerLoginServer.this.loginGameProfile = NetHandlerLoginServer.this.getOfflineProfile(gameprofile);
220
                            NetHandlerLoginServer.this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT;
221
                        }
222
                        else
223
                        {
224
                            NetHandlerLoginServer.this.closeConnection("Authentication servers are down. Please try again later, sorry!");
225
                            NetHandlerLoginServer.logger.error("Couldn\'t verify username because servers are unavailable");
226
                        }
227
                    }
228
                }
229
            }).start();
230
        }
231
    }
232
233
    protected GameProfile getOfflineProfile(GameProfile original)
234
    {
235
        UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + original.getName()).getBytes(Charsets.UTF_8));
236
        return new GameProfile(uuid, original.getName());
237
    }
238
239
    static enum LoginState
240
    {
241
        HELLO,
242
        KEY,
243
        AUTHENTICATING,
244
        READY_TO_ACCEPT,
245
        DELAY_ACCEPT,
246
        ACCEPTED;
247
    }
248
}

Deobfuscated MCP 1.8.9 source of NetHandlerLoginServer from Marcelektro/MavenMCP-1.8.9 (net/minecraft/server/network/NetHandlerLoginServer.java), stored verbatim.