| 1 | package net.minecraft.server.jsonrpc.security;
|
| 2 |
|
| 3 | import com.google.common.collect.Sets;
|
| 4 | import com.mojang.logging.LogUtils;
|
| 5 | import io.netty.buffer.Unpooled;
|
| 6 | import io.netty.channel.ChannelDuplexHandler;
|
| 7 | import io.netty.channel.ChannelHandlerContext;
|
| 8 | import io.netty.channel.ChannelPromise;
|
| 9 | import io.netty.channel.ChannelHandler.Sharable;
|
| 10 | import io.netty.handler.codec.http.DefaultFullHttpResponse;
|
| 11 | import io.netty.handler.codec.http.HttpHeaderNames;
|
| 12 | import io.netty.handler.codec.http.HttpRequest;
|
| 13 | import io.netty.handler.codec.http.HttpResponse;
|
| 14 | import io.netty.handler.codec.http.HttpResponseStatus;
|
| 15 | import io.netty.handler.codec.http.HttpVersion;
|
| 16 | import io.netty.util.AttributeKey;
|
| 17 | import java.net.InetSocketAddress;
|
| 18 | import java.nio.charset.StandardCharsets;
|
| 19 | import java.security.MessageDigest;
|
| 20 | import java.util.Set;
|
| 21 | import org.jspecify.annotations.Nullable;
|
| 22 | import org.slf4j.Logger;
|
| 23 |
|
| 24 | @Sharable
|
| 25 | public class AuthenticationHandler extends ChannelDuplexHandler {
|
| 26 | private final Logger LOGGER = LogUtils.getLogger();
|
| 27 | private static final AttributeKey<Boolean> AUTHENTICATED_KEY = AttributeKey.valueOf("authenticated");
|
| 28 | private static final AttributeKey<Boolean> ATTR_WEBSOCKET_ALLOWED = AttributeKey.valueOf("websocket_auth_allowed");
|
| 29 | private static final String SUBPROTOCOL_VALUE = "minecraft-v1";
|
| 30 | private static final String SUBPROTOCOL_HEADER_PREFIX = "minecraft-v1,";
|
| 31 | public static final String BEARER_PREFIX = "Bearer ";
|
| 32 | private final SecurityConfig securityConfig;
|
| 33 | private final Set<String> allowedOrigins;
|
| 34 |
|
| 35 | public AuthenticationHandler(final SecurityConfig securityConfig, final String allowedOrigins) {
|
| 36 | this.securityConfig = securityConfig;
|
| 37 | this.allowedOrigins = Sets.newHashSet(allowedOrigins.split(","));
|
| 38 | }
|
| 39 |
|
| 40 | @Override
|
| 41 | public void channelRead(final ChannelHandlerContext context, final Object msg) throws Exception {
|
| 42 | String clientIp = this.getClientIp(context);
|
| 43 | if (msg instanceof HttpRequest request) {
|
| 44 | AuthenticationHandler.SecurityCheckResult result = this.performSecurityChecks(request);
|
| 45 | if (!result.isAllowed()) {
|
| 46 | this.LOGGER.debug("Authentication rejected for connection with ip {}: {}", clientIp, result.getReason());
|
| 47 | context.channel().attr(AUTHENTICATED_KEY).set(false);
|
| 48 | this.sendUnauthorizedResponse(context, result.getReason());
|
| 49 | return;
|
| 50 | }
|
| 51 |
|
| 52 | context.channel().attr(AUTHENTICATED_KEY).set(true);
|
| 53 | if (result.isTokenSentInSecWebsocketProtocol()) {
|
| 54 | context.channel().attr(ATTR_WEBSOCKET_ALLOWED).set(Boolean.TRUE);
|
| 55 | }
|
| 56 | }
|
| 57 |
|
| 58 | Boolean isAuthenticated = context.channel().attr(AUTHENTICATED_KEY).get();
|
| 59 | if (Boolean.TRUE.equals(isAuthenticated)) {
|
| 60 | super.channelRead(context, msg);
|
| 61 | } else {
|
| 62 | this.LOGGER.debug("Dropping unauthenticated connection with ip {}", clientIp);
|
| 63 | context.close();
|
| 64 | }
|
| 65 | }
|
| 66 |
|
| 67 | @Override
|
| 68 | public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {
|
| 69 | if (msg instanceof HttpResponse response
|
| 70 | && response.status().code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code()
|
| 71 | && ctx.channel().attr(ATTR_WEBSOCKET_ALLOWED).get() != null
|
| 72 | && ctx.channel().attr(ATTR_WEBSOCKET_ALLOWED).get().equals(Boolean.TRUE)) {
|
| 73 | response.headers().set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, "minecraft-v1");
|
| 74 | }
|
| 75 |
|
| 76 | super.write(ctx, msg, promise);
|
| 77 | }
|
| 78 |
|
| 79 | private AuthenticationHandler.SecurityCheckResult performSecurityChecks(final HttpRequest request) {
|
| 80 | String tokenInAuthorizationHeader = this.parseTokenInAuthorizationHeader(request);
|
| 81 | if (tokenInAuthorizationHeader != null) {
|
| 82 | return this.isValidApiKey(tokenInAuthorizationHeader)
|
| 83 | ? AuthenticationHandler.SecurityCheckResult.allowed()
|
| 84 | : AuthenticationHandler.SecurityCheckResult.denied("Invalid API key");
|
| 85 | }
|
| 86 |
|
| 87 | String tokenInSecWebsocketProtocolHeader = this.parseTokenInSecWebsocketProtocolHeader(request);
|
| 88 | if (tokenInSecWebsocketProtocolHeader != null) {
|
| 89 | if (!this.isAllowedOriginHeader(request)) {
|
| 90 | return AuthenticationHandler.SecurityCheckResult.denied("Origin Not Allowed");
|
| 91 | } else {
|
| 92 | return this.isValidApiKey(tokenInSecWebsocketProtocolHeader)
|
| 93 | ? AuthenticationHandler.SecurityCheckResult.allowed(true)
|
| 94 | : AuthenticationHandler.SecurityCheckResult.denied("Invalid API key");
|
| 95 | }
|
| 96 | } else {
|
| 97 | return AuthenticationHandler.SecurityCheckResult.denied("Missing API key");
|
| 98 | }
|
| 99 | }
|
| 100 |
|
| 101 | private boolean isAllowedOriginHeader(final HttpRequest request) {
|
| 102 | String originHeader = request.headers().get(HttpHeaderNames.ORIGIN);
|
| 103 | return originHeader != null && !originHeader.isEmpty() ? this.allowedOrigins.contains(originHeader) : false;
|
| 104 | }
|
| 105 |
|
| 106 | private @Nullable String parseTokenInAuthorizationHeader(final HttpRequest request) {
|
| 107 | String authHeader = request.headers().get(HttpHeaderNames.AUTHORIZATION);
|
| 108 | return authHeader != null && authHeader.startsWith("Bearer ") ? authHeader.substring("Bearer ".length()).trim() : null;
|
| 109 | }
|
| 110 |
|
| 111 | private @Nullable String parseTokenInSecWebsocketProtocolHeader(final HttpRequest request) {
|
| 112 | String authHeader = request.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
|
| 113 | return authHeader != null && authHeader.startsWith("minecraft-v1,") ? authHeader.substring("minecraft-v1,".length()).trim() : null;
|
| 114 | }
|
| 115 |
|
| 116 | public boolean isValidApiKey(final String suppliedKey) {
|
| 117 | if (suppliedKey.isEmpty()) {
|
| 118 | return false;
|
| 119 | }
|
| 120 |
|
| 121 | byte[] suppliedKeyBytes = suppliedKey.getBytes(StandardCharsets.UTF_8);
|
| 122 | byte[] configuredKeyBytes = this.securityConfig.secretKey().getBytes(StandardCharsets.UTF_8);
|
| 123 | return MessageDigest.isEqual(suppliedKeyBytes, configuredKeyBytes);
|
| 124 | }
|
| 125 |
|
| 126 | private String getClientIp(final ChannelHandlerContext context) {
|
| 127 | InetSocketAddress remoteAddress = (InetSocketAddress)context.channel().remoteAddress();
|
| 128 | return remoteAddress.getAddress().getHostAddress();
|
| 129 | }
|
| 130 |
|
| 131 | private void sendUnauthorizedResponse(final ChannelHandlerContext context, final String reason) {
|
| 132 | String responseBody = "{\"error\":\"Unauthorized\",\"message\":\"" + reason + "\"}";
|
| 133 | byte[] content = responseBody.getBytes(StandardCharsets.UTF_8);
|
| 134 | DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED, Unpooled.wrappedBuffer(content));
|
| 135 | response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
|
| 136 | response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.length);
|
| 137 | response.headers().set(HttpHeaderNames.CONNECTION, "close");
|
| 138 | context.writeAndFlush(response).addListener(future -> context.close());
|
| 139 | }
|
| 140 |
|
| 141 | private static class SecurityCheckResult {
|
| 142 | private final boolean allowed;
|
| 143 | private final String reason;
|
| 144 | private final boolean tokenSentInSecWebsocketProtocol;
|
| 145 |
|
| 146 | private SecurityCheckResult(final boolean allowed, final String reason, final boolean tokenSentInSecWebsocketProtocol) {
|
| 147 | this.allowed = allowed;
|
| 148 | this.reason = reason;
|
| 149 | this.tokenSentInSecWebsocketProtocol = tokenSentInSecWebsocketProtocol;
|
| 150 | }
|
| 151 |
|
| 152 | public static AuthenticationHandler.SecurityCheckResult allowed() {
|
| 153 | return new AuthenticationHandler.SecurityCheckResult(true, null, false);
|
| 154 | }
|
| 155 |
|
| 156 | public static AuthenticationHandler.SecurityCheckResult allowed(final boolean tokenSentInSecWebsocketProtocol) {
|
| 157 | return new AuthenticationHandler.SecurityCheckResult(true, null, tokenSentInSecWebsocketProtocol);
|
| 158 | }
|
| 159 |
|
| 160 | public static AuthenticationHandler.SecurityCheckResult denied(final String reason) {
|
| 161 | return new AuthenticationHandler.SecurityCheckResult(false, reason, false);
|
| 162 | }
|
| 163 |
|
| 164 | public boolean isAllowed() {
|
| 165 | return this.allowed;
|
| 166 | }
|
| 167 |
|
| 168 | public String getReason() {
|
| 169 | return this.reason;
|
| 170 | }
|
| 171 |
|
| 172 | public boolean isTokenSentInSecWebsocketProtocol() {
|
| 173 | return this.tokenSentInSecWebsocketProtocol;
|
| 174 | }
|
| 175 | }
|
| 176 | }
|
| 177 |
|