aboutsummaryrefslogtreecommitdiffhomepage
path: root/patches/server/0835-Add-Velocity-IP-Forwarding-Support.patch
blob: 37a848e94f77258685dad1ad92225363769c5522 (plain)
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
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Andrew Steinborn <git@steinborn.me>
Date: Mon, 8 Oct 2018 14:36:14 -0400
Subject: [PATCH] Add Velocity IP Forwarding Support

While Velocity supports BungeeCord-style IP forwarding, it is not secure. Users
have a lot of problems setting up firewalls or setting up plugins like IPWhitelist.
Further, the BungeeCord IP forwarding protocol still retains essentially its original
form, when there is brand new support for custom login plugin messages in 1.13.

Velocity's modern IP forwarding uses an HMAC-SHA256 code to ensure authenticity
of messages, is packed into a binary format that is smaller than BungeeCord's
forwarding, and is integrated into the Minecraft login process by using the 1.13
login plugin message packet.

diff --git a/src/main/java/com/destroystokyo/paper/proxy/VelocityProxy.java b/src/main/java/com/destroystokyo/paper/proxy/VelocityProxy.java
new file mode 100644
index 0000000000000000000000000000000000000000..a34381122de53123169927e181df662814df4816
--- /dev/null
+++ b/src/main/java/com/destroystokyo/paper/proxy/VelocityProxy.java
@@ -0,0 +1,75 @@
+package com.destroystokyo.paper.proxy;
+
+import io.papermc.paper.configuration.GlobalConfiguration;
+import com.google.common.net.InetAddresses;
+import com.mojang.authlib.GameProfile;
+import com.mojang.authlib.properties.Property;
+import java.net.InetAddress;
+import java.security.InvalidKeyException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.UUID;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import net.minecraft.network.FriendlyByteBuf;
+import net.minecraft.network.protocol.login.custom.CustomQueryPayload;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.world.entity.player.ProfilePublicKey;
+
+public class VelocityProxy {
+    private static final int SUPPORTED_FORWARDING_VERSION = 1;
+    public static final int MODERN_FORWARDING_WITH_KEY = 2;
+    public static final int MODERN_FORWARDING_WITH_KEY_V2 = 3;
+    public static final int MODERN_LAZY_SESSION = 4;
+    public static final byte MAX_SUPPORTED_FORWARDING_VERSION = MODERN_LAZY_SESSION;
+    public static final ResourceLocation PLAYER_INFO_CHANNEL = new ResourceLocation("velocity", "player_info");
+
+    public static boolean checkIntegrity(final FriendlyByteBuf buf) {
+        final byte[] signature = new byte[32];
+        buf.readBytes(signature);
+
+        final byte[] data = new byte[buf.readableBytes()];
+        buf.getBytes(buf.readerIndex(), data);
+
+        try {
+            final Mac mac = Mac.getInstance("HmacSHA256");
+            mac.init(new SecretKeySpec(GlobalConfiguration.get().proxies.velocity.secret.getBytes(java.nio.charset.StandardCharsets.UTF_8), "HmacSHA256"));
+            final byte[] mySignature = mac.doFinal(data);
+            if (!MessageDigest.isEqual(signature, mySignature)) {
+                return false;
+            }
+        } catch (final InvalidKeyException | NoSuchAlgorithmException e) {
+            throw new AssertionError(e);
+        }
+
+        return true;
+    }
+
+    public static InetAddress readAddress(final FriendlyByteBuf buf) {
+        return InetAddresses.forString(buf.readUtf(Short.MAX_VALUE));
+    }
+
+    public static GameProfile createProfile(final FriendlyByteBuf buf) {
+        final GameProfile profile = new GameProfile(buf.readUUID(), buf.readUtf(16));
+        readProperties(buf, profile);
+        return profile;
+    }
+
+    private static void readProperties(final FriendlyByteBuf buf, final GameProfile profile) {
+        final int properties = buf.readVarInt();
+        for (int i1 = 0; i1 < properties; i1++) {
+            final String name = buf.readUtf(Short.MAX_VALUE);
+            final String value = buf.readUtf(Short.MAX_VALUE);
+            final String signature = buf.readBoolean() ? buf.readUtf(Short.MAX_VALUE) : null;
+            profile.getProperties().put(name, new Property(name, value, signature));
+        }
+    }
+
+    public static ProfilePublicKey.Data readForwardedKey(FriendlyByteBuf buf) {
+        return new ProfilePublicKey.Data(buf);
+    }
+
+    public static UUID readSignerUuidOrElse(FriendlyByteBuf buf, UUID orElse) {
+        return buf.readBoolean() ? buf.readUUID() : orElse;
+    }
+}
diff --git a/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java b/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java
index 5264235c1547c78b8123e2efb07dcb77486cc5bf..db363bca264e37c29fda58291246aba0d3759de0 100644
--- a/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java
+++ b/src/main/java/net/minecraft/server/dedicated/DedicatedServer.java
@@ -274,13 +274,20 @@ public class DedicatedServer extends MinecraftServer implements ServerInterface
         this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.STARTUP);
         // CraftBukkit end
 
+        // Paper start
+        boolean usingProxy = org.spigotmc.SpigotConfig.bungee || io.papermc.paper.configuration.GlobalConfiguration.get().proxies.velocity.enabled;
+        String proxyFlavor = (io.papermc.paper.configuration.GlobalConfiguration.get().proxies.velocity.enabled) ? "Velocity" : "BungeeCord";
+        String proxyLink = (io.papermc.paper.configuration.GlobalConfiguration.get().proxies.velocity.enabled) ? "https://docs.papermc.io/velocity/security" : "http://www.spigotmc.org/wiki/firewall-guide/";
+        // Paper end
         if (!this.usesAuthentication()) {
             DedicatedServer.LOGGER.warn("**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!");
             DedicatedServer.LOGGER.warn("The server will make no attempt to authenticate usernames. Beware.");
             // Spigot start
-            if (org.spigotmc.SpigotConfig.bungee) {
-                DedicatedServer.LOGGER.warn("Whilst this makes it possible to use BungeeCord, unless access to your server is properly restricted, it also opens up the ability for hackers to connect with any username they choose.");
-                DedicatedServer.LOGGER.warn("Please see http://www.spigotmc.org/wiki/firewall-guide/ for further information.");
+            // Paper start
+            if (usingProxy) {
+                DedicatedServer.LOGGER.warn("Whilst this makes it possible to use " + proxyFlavor + ", unless access to your server is properly restricted, it also opens up the ability for hackers to connect with any username they choose.");
+                DedicatedServer.LOGGER.warn("Please see " + proxyLink + " for further information.");
+            // Paper end
             } else {
                 DedicatedServer.LOGGER.warn("While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose.");
             }
diff --git a/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java b/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
index 5c767318ff3f589ecebb9608ce173fa578e330a5..83605748ca8cf68c0fc6d99c34f3091183c7a059 100644
--- a/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
+++ b/src/main/java/net/minecraft/server/network/ServerLoginPacketListenerImpl.java
@@ -64,6 +64,7 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener,
     private final String serverId;
     private ServerPlayer player; // CraftBukkit
     public boolean iKnowThisMayNotBeTheBestIdeaButPleaseDisableUsernameValidation = false; // Paper - username validation overriding
+    private int velocityLoginMessageId = -1; // Paper - Velocity support
 
     public ServerLoginPacketListenerImpl(MinecraftServer server, Connection connection) {
         this.state = ServerLoginPacketListenerImpl.State.HELLO;
@@ -177,6 +178,16 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener,
                 this.state = ServerLoginPacketListenerImpl.State.KEY;
                 this.connection.send(new ClientboundHelloPacket("", this.server.getKeyPair().getPublic().getEncoded(), this.challenge));
             } else {
+                // Paper start - Velocity support
+                if (io.papermc.paper.configuration.GlobalConfiguration.get().proxies.velocity.enabled) {
+                    this.velocityLoginMessageId = java.util.concurrent.ThreadLocalRandom.current().nextInt();
+                    net.minecraft.network.FriendlyByteBuf buf = new net.minecraft.network.FriendlyByteBuf(io.netty.buffer.Unpooled.buffer());
+                    buf.writeByte(com.destroystokyo.paper.proxy.VelocityProxy.MAX_SUPPORTED_FORWARDING_VERSION);
+                    net.minecraft.network.protocol.login.ClientboundCustomQueryPacket packet1 = new net.minecraft.network.protocol.login.ClientboundCustomQueryPacket(this.velocityLoginMessageId, new net.minecraft.network.protocol.login.ClientboundCustomQueryPacket.PlayerInfoChannelPayload(com.destroystokyo.paper.proxy.VelocityProxy.PLAYER_INFO_CHANNEL, buf));
+                    this.connection.send(packet1);
+                    return;
+                }
+                // Paper end
                 // Spigot start
             // Paper start - Cache authenticator threads
             authenticatorPool.execute(new Runnable() {
@@ -314,6 +325,12 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener,
     public class LoginHandler {
 
         public void fireEvents(GameProfile gameprofile) throws Exception {
+                        // Paper start - Velocity support
+                        if (ServerLoginPacketListenerImpl.this.velocityLoginMessageId == -1 && io.papermc.paper.configuration.GlobalConfiguration.get().proxies.velocity.enabled) {
+                            disconnect("This server requires you to connect with Velocity.");
+                            return;
+                        }
+                        // Paper end
                         String playerName = gameprofile.getName();
                         java.net.InetAddress address = ((java.net.InetSocketAddress) ServerLoginPacketListenerImpl.this.connection.getRemoteAddress()).getAddress();
                         java.net.InetAddress rawAddress = ((java.net.InetSocketAddress) ServerLoginPacketListenerImpl.this.connection.channel.remoteAddress()).getAddress(); // Paper
@@ -363,6 +380,49 @@ public class ServerLoginPacketListenerImpl implements ServerLoginPacketListener,
 
     @Override
     public void handleCustomQueryPacket(ServerboundCustomQueryAnswerPacket packet) {
+        // Paper start - Velocity support
+        if (io.papermc.paper.configuration.GlobalConfiguration.get().proxies.velocity.enabled && packet.transactionId() == this.velocityLoginMessageId) {
+            ServerboundCustomQueryAnswerPacket.QueryAnswerPayload payload = (ServerboundCustomQueryAnswerPacket.QueryAnswerPayload)packet.payload();
+            if (payload == null) {
+                this.disconnect("This server requires you to connect with Velocity.");
+                return;
+            }
+
+            net.minecraft.network.FriendlyByteBuf buf = payload.buffer;
+
+            if (!com.destroystokyo.paper.proxy.VelocityProxy.checkIntegrity(buf)) {
+                this.disconnect("Unable to verify player details");
+                return;
+            }
+
+            int version = buf.readVarInt();
+            if (version > com.destroystokyo.paper.proxy.VelocityProxy.MAX_SUPPORTED_FORWARDING_VERSION) {
+                throw new IllegalStateException("Unsupported forwarding version " + version + ", wanted upto " + com.destroystokyo.paper.proxy.VelocityProxy.MAX_SUPPORTED_FORWARDING_VERSION);
+            }
+
+            java.net.SocketAddress listening = this.connection.getRemoteAddress();
+            int port = 0;
+            if (listening instanceof java.net.InetSocketAddress) {
+                port = ((java.net.InetSocketAddress) listening).getPort();
+            }
+            this.connection.address = new java.net.InetSocketAddress(com.destroystokyo.paper.proxy.VelocityProxy.readAddress(buf), port);
+
+            this.authenticatedProfile = com.destroystokyo.paper.proxy.VelocityProxy.createProfile(buf);
+
+            //TODO Update handling for lazy sessions, might not even have to do anything?
+
+            // Proceed with login
+            authenticatorPool.execute(() -> {
+                try {
+                    new LoginHandler().fireEvents(this.authenticatedProfile);
+                } catch (Exception ex) {
+                    disconnect("Failed to verify username!");
+                    server.server.getLogger().log(java.util.logging.Level.WARNING, "Exception verifying " + this.authenticatedProfile.getName(), ex);
+                }
+            });
+            return;
+        }
+        // Paper end
         this.disconnect(ServerLoginPacketListenerImpl.DISCONNECT_UNEXPECTED_QUERY);
     }
 
diff --git a/src/main/java/org/bukkit/craftbukkit/CraftServer.java b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
index 7c8d21499d49aa88ad771e98a8e5302d1b3a3229..97a32d1d4bc4042c72c488eee92dff69f8336464 100644
--- a/src/main/java/org/bukkit/craftbukkit/CraftServer.java
+++ b/src/main/java/org/bukkit/craftbukkit/CraftServer.java
@@ -802,7 +802,7 @@ public final class CraftServer implements Server {
     @Override
     public long getConnectionThrottle() {
         // Spigot Start - Automatically set connection throttle for bungee configurations
-        if (org.spigotmc.SpigotConfig.bungee) {
+        if (org.spigotmc.SpigotConfig.bungee || io.papermc.paper.configuration.GlobalConfiguration.get().proxies.velocity.enabled) { // Paper - Velocity support
             return -1;
         } else {
             return this.configuration.getInt("settings.connection-throttle");