Compare commits

...
22 Commits
Author SHA1 Message Date
Jones e9c212b9e4 Release 2.0.10 (#126) 2023-12-15 16:02:44 +01:00
Jones 42da141f2b Remove lockdown mode (#125)
* https://discord.com/channels/923308209769426994/1180500530896842832
2023-12-15 15:49:50 +01:00
Jones e0bc83f8ef Implement Minecraft 1.20.4 support (#124)
* feat: implement GameEvent packet

* fix: make Chat & Disconnect packet work on 1.20.3+

* fix: don't send ChunkData twice

* fix: invalid serverbound PositionLook packet id on 1.20.3+

* fix: remove custom read-timeout value

* fix: trigger channel read after Fallback packet decode

* fix: only expect 10 unique kick packets instead of 16

* fix: map item id mapping

* feat: 1.20.3 barrier block mappings
2023-12-15 15:44:14 +01:00
Jones 59822ef541 Optimize in-class performance during verification (#123)
* style: use Getter for the entire class instead of a single field

* style: reformat code using IntelliSense

* fix: optimize IP address connection ratelimiter
2023-12-07 21:16:20 +01:00
Jones 38fbfff896 Fix README badge line separator not displaying (#122) 2023-12-07 21:00:18 +01:00
Jones 6725975cf1 Add CodeFactor rating to README (#121)
* feat: add 1.20.3 protocol version to allowed protocols

* feat: update packet ids for 1.20.3

* chore: add code factor rating to README
2023-12-07 20:57:41 +01:00
Jones d59fd4b431 Avoid using custom exceptions in the decoder (#119) 2023-12-04 16:48:28 +01:00
Jones a76ca2f91d Add optional map captcha check to verification (#118)
* feat: change field type "encodedFlags" of Abilities packet to int

* feat: add MapData packet
feat: add SetSlot packet

* feat: implement map captcha state

* feat: [wip] implement simple map captcha

* feat: cache captcha spawn position packet

* feat: add a chat message when you verify and enter the captcha

* fix: Chat packet error on 1.7

* feat: make map prepared amount and dictionary customizable

* fix: SetSlot packet error on 1.7

* fix: make map data work on 1.7

* feat: randomize font size & font style

* fix: implement KeepAlive during captcha and add timer

* feat: add color and x/y randomization to map captcha

* feat: add green and red color palette

* feat: implement captcha validation

* fix: chat packet not working on 1.7-1.18.2

* fix: only draw important used pixels

* feat: optimize color palette

* feat: set map image dimensions to 86x86

* feat: set background color of image to white/light gray

* feat: recode map info preparing and map data packet sending

* fix: x/y offset for 1.8+ in map info

* fix: add prefix to translated messages for the map captcha

* feat: make some map captcha options changeable

* fix: set the default font size to the average (instead of max)

* fix: Chat packet not working on 1.17-1.18.1

* fix: only send DefaultSpawnPosition to >=1.18.2 clients

* fix: return if captcha is correct to prevent further code execution

* feat: cache dynamic DefaultSpawnPosition packet
2023-12-02 14:13:30 +01:00
Jones 30803ba6e4 Fix permanent "Loading terrain" screen on 1.18.2+ (#117)
* feat: remove unused Chat packet

* feat: set JoinGame entityId to 0

* fix: add DefaultSpawnPosition to fix "Loading terrain" screen

* fix: 1.20.2 barrier block state id
2023-11-28 17:30:12 +01:00
Jones 194232804b Remove unnecessary metadata in the compilation process (#116)
* build: exclude unnecessary version information

* build: remove unnecessary file timestamps
2023-11-25 16:48:28 +01:00
Jones 19c97b26b6 Relocate some packages of net.kyori (#115)
* build(deps): relocate cappuccino

* build(deps): relocate net.kyori (except for text and audience)
2023-11-25 16:23:31 +01:00
Jones d66719b3e0 Fix state checks in verification not being handled properly (#114) 2023-11-24 21:06:19 +01:00
Michel Elkenwaat 9226908002 style: add copyright header to UpdateChecker.java 2023-11-24 19:37:35 +01:00
Jones ac74f14dc0 Make RegistrySync packet use the implemented nbt writing method (#112) 2023-11-23 17:54:53 +01:00
Michel Elkenwaat 8f11a53b38 fix: use ByteBufOutputStream in an AutoClosable statement 2023-11-23 17:54:21 +01:00
Jones 0b4394624f Release 2.0.9 (#111) 2023-11-22 15:56:26 +01:00
Michel Elkenwaat d8f7e288e8 build(deps): bump gradle from 8.3 to 8.4 2023-11-21 18:18:35 +01:00
Jones 3f3411ca9d Implement nameless compound tag for 1.20.2+ chunks (#110) 2023-11-21 17:41:59 +01:00
Jones 14ae85384a Optimize verification by using different data types (#109)
* fix: optimize ConcurrentHashMap usage in Fallback

* feat: remove max-verifying-players option from config

* fix: use hashset for whitelist and blacklisted protocol ids

* fix: yaml configuration formatting error on empty collections
2023-11-16 16:58:30 +01:00
Jones 8204477eb6 Implement protocol version whitelist and blacklist (#108)
* feat: allow certain protocol Ids to be exempt from verification

* fix(bungee): run blacklist check even if verification is disabled

* fix: run Geyser check before creating a new GameProfile

* feat: the blacklist should cache the InetAddress and not a String

* fix: support IPv6 (and more) in all subcommand arguments

* feat: add blacklisted protocol versions
2023-11-16 16:39:35 +01:00
Jones 44754e5027 Use correct values for webhook attack statistics (#107) 2023-11-14 12:01:05 +01:00
dependabot[bot] 847936ed08 Bump io.netty:netty-all from 4.1.100.Final to 4.1.101.Final (#105)
Bumps [io.netty:netty-all](https://github.com/netty/netty) from 4.1.100.Final to 4.1.101.Final.
- [Commits](https://github.com/netty/netty/compare/netty-4.1.100.Final...netty-4.1.101.Final)

---
updated-dependencies:
- dependency-name: io.netty:netty-all
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-13 14:06:47 +01:00
43 changed files with 1507 additions and 488 deletions

No files matched your search

+1
View File
@@ -9,6 +9,7 @@
<!-- Badges & icons -->
[![](https://github.com/jonesdevelopment/sonar/actions/workflows/gradle.yml/badge.svg)](https://github.com/jonesdevelopment/sonar/actions/workflows/gradle.yml)
[![](https://www.codefactor.io/repository/github/jonesdevelopment/sonar/badge/main)](https://www.codefactor.io/repository/github/jonesdevelopment/sonar/overview/main)
[![](https://img.shields.io/github/v/release/jonesdevelopment/sonar)](https://github.com/jonesdevelopment/sonar/releases)
[![](https://img.shields.io/github/issues/jonesdevelopment/sonar)](https://github.com/jonesdevelopment/sonar/issues)
[![](https://img.shields.io/discord/923308209769426994.svg?logo=discord)](https://jonesdev.xyz/discord)
+14 -2
View File
@@ -46,7 +46,7 @@ allprojects {
implementation("com.j256.ormlite:ormlite-jdbc:6.1") // ORM
implementation("xyz.jonesdev:cappuccino:0.1.6-SNAPSHOT") // expiring cache
compileOnly("io.netty:netty-all:4.1.100.Final") // netty
compileOnly("io.netty:netty-all:4.1.101.Final") // netty
}
}
@@ -71,16 +71,28 @@ tasks {
// Set the file name of the shadowed jar
archiveFileName.set("Sonar.jar")
// Remove file timestamps
isPreserveFileTimestamps = false
// bStats has to be relocated to the Sonar package otherwise it throws an exception
// https://github.com/Bastian/bstats-metrics/blob/master/base/src/main/java/org/bstats/MetricsBase.java#L251
relocate("org.bstats", "xyz.jonesdev.sonar.libs.bstats")
// https://github.com/jonesdevelopment/sonar/issues/46
// Relocate some packages, so we don't run into issues where we accidentally use Velocity's classes
relocate("net.kyori.adventure.nbt", "xyz.jonesdev.sonar.libs.nbt")
relocate("org.simpleyaml", "xyz.jonesdev.sonar.libs.yaml")
relocate("com.google.gson", "xyz.jonesdev.sonar.libs.gson")
relocate("com.j256.ormlite", "xyz.jonesdev.sonar.libs.ormlite")
relocate("xyz.jonesdev.cappuccino", "xyz.jonesdev.sonar.libs.cappuccino")
relocate("net.kyori.examination", "xyz.jonesdev.sonar.libs.examination")
// We have to be careful here, so we don't accidentally break adventure
relocate("net.kyori.adventure", "xyz.jonesdev.sonar.libs.adventure") {
exclude("net.kyori.adventure.text.**")
exclude("net.kyori.adventure.audience.**")
}
// Exclude unnecessary metadata information
exclude("META-INF/versions/**")
}
compileJava {
+1 -1
View File
@@ -1,3 +1,3 @@
group=xyz.jonesdev.sonar
version=2.0.8
version=2.0.10
description=Effective Anti-bot plugin for Velocity, BungeeCord, and Bukkit (1.7-latest)
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
@@ -45,6 +45,8 @@ public final class AttackTracker implements JVMProfiler {
private int peakJoinsPerSecond;
private double peakProcessCPUUsage;
private long peakProcessMemoryUsage;
// Calculate during-attack-statistics using their deltas
private int successfulVerifications, failedVerifications;
}
public void checkIfUnderAttack() {
@@ -62,6 +64,8 @@ public final class AttackTracker implements JVMProfiler {
// An attack has been detected
if (currentAttack == null) {
currentAttack = new AttackStatistics();
currentAttack.successfulVerifications = Sonar.get().getVerifiedPlayerController().estimatedSize();
currentAttack.failedVerifications = Statistics.FAILED_VERIFICATIONS.get();
Sonar.get().getEventManager().publish(new AttackDetectedEvent());
} else {
// Reset attack timer if we're still under attack
@@ -101,8 +105,11 @@ public final class AttackTracker implements JVMProfiler {
final String startTimestamp = String.valueOf(currentAttack.duration.getStart() / 1000L);
final String endTimestamp = String.valueOf(System.currentTimeMillis() / 1000L);
final long blacklisted = Sonar.get().getFallback().getBlacklisted().estimatedSize();
final long verified = Sonar.get().getVerifiedPlayerController().estimatedSize();
final long failed = Statistics.FAILED_VERIFICATIONS.get();
// Calculate during-attack-statistics using their deltas
final long totalVerified = Sonar.get().getVerifiedPlayerController().estimatedSize();
final long verified = Math.max(totalVerified - currentAttack.successfulVerifications, 0);
final long totalFailed = Statistics.FAILED_VERIFICATIONS.get();
final long failed = Math.max(totalFailed - currentAttack.failedVerifications, 0);
// Post webhook to Discord
Optional.ofNullable(Sonar.get().getConfig().getDiscordWebhook()).ifPresent(webhook -> webhook.post(() -> {
@@ -28,8 +28,6 @@ import xyz.jonesdev.sonar.api.command.subcommand.argument.Argument;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Getter
@@ -51,18 +49,7 @@ public abstract class Subcommand {
.collect(Collectors.joining(", "));
}
// https://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp
private static final Pattern IP_PATTERN = Pattern.compile("^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$");
protected static @Nullable InetAddress getInetAddressIfValid(final InvocationSource source, final String rawIP) {
// We perform a regex check beforehand,
// so we don't have to create a new InetAddress,
// therefore, potentially saving some performance.
if (!IP_PATTERN.matcher(Objects.requireNonNull(rawIP)).matches()) {
source.sendMessage(SONAR.getConfig().getCommands().getIncorrectIpAddress());
return null;
}
final InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(rawIP);
@@ -72,7 +59,7 @@ public abstract class Subcommand {
return null;
}
} catch (UnknownHostException exception) {
source.sendMessage(SONAR.getConfig().getCommands().getUnknownIpAddress());
source.sendMessage(SONAR.getConfig().getCommands().getIncorrectIpAddress());
return null;
}
return inetAddress;
@@ -112,4 +112,9 @@ public final class SimpleYamlConfig {
yaml.addDefault(path, def);
return yaml.getStringList(path);
}
public List<Integer> getIntList(final String path, final List<Integer> def) {
yaml.addDefault(path, def);
return yaml.getIntegerList(path);
}
}
@@ -29,10 +29,7 @@ import xyz.jonesdev.sonar.api.webhook.DiscordWebhook;
import java.io.File;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.*;
import java.util.regex.Pattern;
import static xyz.jonesdev.sonar.api.Sonar.LINE_SEPARATOR;
@@ -51,8 +48,6 @@ public final class SonarConfiguration {
@Getter
private final Verification verification = new Verification();
@Getter
private final Lockdown lockdown = new Lockdown();
@Getter
private final Database database = new Database();
@Getter
private final Webhook webhook = new Webhook();
@@ -101,12 +96,49 @@ public final class SonarConfiguration {
private Timing timing;
@Getter
@RequiredArgsConstructor
public enum Timing {
ALWAYS, DURING_ATTACK, NEVER
}
private boolean checkGravity;
private final Map map = new Map();
private final Gravity gravity = new Gravity();
@Getter
public static final class Map {
private boolean enabled;
private boolean drawBackgroundNoise;
private boolean randomizePositions;
private boolean randomizeFontSize;
private int precomputeAmount;
private int maxDuration;
private int maxTries;
private String dictionary;
private Component enterCode;
private Component failedCaptcha;
private String enterCodeActionBar;
}
@Getter
public static final class Gravity {
private boolean enabled;
private Gamemode gamemode;
private int maxMovementTicks;
private int maxIgnoredTicks;
private Component youAreBeingChecked;
@Getter
@RequiredArgsConstructor
public enum Gamemode {
SURVIVAL(0),
CREATIVE(1),
ADVENTURE(2),
// Keep this for backwards compatibility
SPECTATOR(2);
private final int id;
}
}
private boolean logConnections;
private boolean logDuringAttack;
private boolean debugXYZPositions;
@@ -118,27 +150,13 @@ public final class SonarConfiguration {
private String successLog;
private String blacklistLog;
private Gamemode gamemode;
@Getter
@RequiredArgsConstructor
public enum Gamemode {
SURVIVAL(0),
CREATIVE(1),
ADVENTURE(2),
SPECTATOR(3);
private final int id;
}
private int maxBrandLength;
private int maxMovementTicks;
private int maxIgnoredTicks;
private int maxVerifyingPlayers;
private int maxLoginPackets;
private int maxPing;
private int readTimeout;
private int reconnectDelay;
private final Collection<Integer> whitelistedProtocols = new HashSet<>(0);
private final Collection<Integer> blacklistedProtocols = new HashSet<>(0);
private Component tooManyPlayers;
private Component tooFastReconnect;
@@ -150,6 +168,7 @@ public final class SonarConfiguration {
private Component alreadyVerifying;
private Component alreadyQueued;
private Component blacklisted;
private Component protocolBlacklisted;
}
@Getter
@@ -158,7 +177,6 @@ public final class SonarConfiguration {
private String incorrectCommandUsage;
private String incorrectIpAddress;
private String illegalIpAddress;
private String unknownIpAddress;
private String subCommandNoPerm;
private String playersOnly;
private String consoleOnly;
@@ -220,21 +238,6 @@ public final class SonarConfiguration {
private String password;
}
@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static final class Lockdown {
@Setter
private boolean enabled;
private boolean notifyAdmins;
private boolean logAttempts;
private Component disconnect;
private String bypassPermission;
private String activated;
private String deactivated;
private String notification;
private String consoleLog;
}
@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static final class Webhook {
@@ -368,27 +371,6 @@ public final class SonarConfiguration {
"Password for authenticating with the SQL database");
database.password = generalConfig.getString("database.password", "");
// Lockdown
generalConfig.getYaml().setComment("lockdown",
"You can lock your server down using '/sonar lockdown' if, for example,"
+ LINE_SEPARATOR + "bots are bypassing the verification or any other reason");
generalConfig.getYaml().setComment("lockdown.enabled",
"Should Sonar prevent all players from joining the server?");
lockdown.enabled = generalConfig.getBoolean("lockdown.enabled", false);
generalConfig.getYaml().setComment("lockdown.log-attempts",
"Should Sonar log new login attempts during lockdown?");
lockdown.logAttempts = generalConfig.getBoolean("lockdown.log-attempts", true);
generalConfig.getYaml().setComment("lockdown.notify-admins",
"Should Sonar notify admins when they join the server during lockdown?");
lockdown.notifyAdmins = generalConfig.getBoolean("lockdown.notify-admins", true);
generalConfig.getYaml().setComment("lockdown.bypass-permission",
"Which permission does a player need in order to bypass the lockdown mode?"
+ LINE_SEPARATOR + "Players with this permission will also receive admin notifications when joining");
lockdown.bypassPermission = generalConfig.getString("lockdown.bypass-permission", "sonar.lockdown.bypass");
// Queue
generalConfig.getYaml().setComment("queue",
"Every new login request will be queued to avoid spam join attacks"
@@ -415,17 +397,65 @@ public final class SonarConfiguration {
+ LINE_SEPARATOR + "All predicted motions are precalculated in order to save performance");
generalConfig.getYaml().setComment("verification.checks.gravity.enabled",
"Should Sonar check for valid client gravity? (Recommended)");
verification.checkGravity = generalConfig.getBoolean("verification.checks.gravity.enabled", true);
verification.gravity.enabled = generalConfig.getBoolean("verification.checks.gravity.enabled", true);
generalConfig.getYaml().setComment("verification.checks.gravity.max-movement-ticks",
"Maximum number of ticks the player has to fall in order to be allowed to hit the platform");
verification.maxMovementTicks = clamp(generalConfig.getInt("verification.checks.gravity.max-movement-ticks", 8),
verification.gravity.maxMovementTicks = clamp(generalConfig.getInt("verification.checks.gravity" +
".max-movement-ticks", 8),
2, 100);
generalConfig.getYaml().setComment("verification.checks.gravity.max-ignored-ticks",
"Maximum number of ignored Y movement changes before a player fails verification");
verification.maxIgnoredTicks = clamp(generalConfig.getInt("verification.checks.gravity.max-ignored-ticks", 5), 1,
128);
verification.gravity.maxIgnoredTicks = clamp(generalConfig.getInt("verification.checks.gravity.max-ignored-ticks"
, 5),
1, 128);
generalConfig.getYaml().setComment("verification.checks.gravity.gamemode",
"The gamemode of the player during verification"
+ LINE_SEPARATOR + "Possible types: SURVIVAL, CREATIVE, ADVENTURE, SPECTATOR"
+ LINE_SEPARATOR + "- SURVIVAL: all UI components are visible"
+ LINE_SEPARATOR + "- CREATIVE: health and hunger are hidden"
+ LINE_SEPARATOR + "- ADVENTURE: all UI components are visible");
verification.gravity.gamemode = Verification.Gravity.Gamemode.valueOf(
generalConfig.getString("verification.checks.gravity.gamemode", Verification.Gravity.Gamemode.ADVENTURE.name()).toUpperCase());
generalConfig.getYaml().setComment("verification.checks.map-captcha",
"Make the player type a code from a virtual map in chat after the gravity check");
generalConfig.getYaml().setComment("verification.checks.map-captcha.enabled",
"Should Sonar make the player pass a captcha?");
verification.map.enabled = generalConfig.getBoolean("verification.checks.map-captcha.enabled", false);
generalConfig.getYaml().setComment("verification.checks.map-captcha.background-noise",
"Should Sonar draw a white/light gray rectangle behind the captcha?");
verification.map.drawBackgroundNoise = generalConfig.getBoolean("verification.checks.map-captcha" +
".background-noise", true);
generalConfig.getYaml().setComment("verification.checks.map-captcha.random-position",
"Should Sonar randomize the X and Y position of the captcha?");
verification.map.randomizePositions = generalConfig.getBoolean("verification.checks.map-captcha.random-position",
true);
generalConfig.getYaml().setComment("verification.checks.map-captcha.random-font-size",
"Should Sonar randomize the size of the font used for rendering the captcha?");
verification.map.randomizeFontSize = generalConfig.getBoolean("verification.checks.map-captcha.random-font-size",
true);
generalConfig.getYaml().setComment("verification.checks.map-captcha.precompute",
"How many answers should Sonar precompute (prepare)?");
verification.map.precomputeAmount = generalConfig.getInt("verification.checks.map-captcha.precompute", 1000);
generalConfig.getYaml().setComment("verification.checks.map-captcha.max-duration",
"How long should Sonar wait until the player fails the captcha?");
verification.map.maxDuration = generalConfig.getInt("verification.checks.map-captcha.max-duration", 45000);
generalConfig.getYaml().setComment("verification.checks.map-captcha.max-tries",
"How many times must a player fail the captcha before failing the verification?");
verification.map.maxTries = generalConfig.getInt("verification.checks.map-captcha.max-tries", 3);
generalConfig.getYaml().setComment("verification.checks.map-captcha.dictionary",
"Characters (letters and numbers) that are allowed to appear in the answer to the captcha");
verification.map.dictionary = generalConfig.getString("verification.checks.map-captcha.dictionary", "123456789");
generalConfig.getYaml().setComment("verification.checks.valid-name-regex",
"Regex for validating usernames during verification");
@@ -454,16 +484,6 @@ public final class SonarConfiguration {
"Maximum number of login packets the player has to send in order to be kicked");
verification.maxLoginPackets = clamp(generalConfig.getInt("verification.checks.max-login-packets", 256), 128, 8192);
generalConfig.getYaml().setComment("verification.gamemode",
"The gamemode of the player during verification"
+ LINE_SEPARATOR + "Possible types: SURVIVAL, CREATIVE, ADVENTURE, SPECTATOR"
+ LINE_SEPARATOR + "- SURVIVAL: all UI components are visible"
+ LINE_SEPARATOR + "- CREATIVE: health and hunger are hidden"
+ LINE_SEPARATOR + "- ADVENTURE: all UI components are visible"
+ LINE_SEPARATOR + "- SPECTATOR: all UI components are hidden (Recommended)");
verification.gamemode = Verification.Gamemode.valueOf(
generalConfig.getString("verification.gamemode", Verification.Gamemode.SPECTATOR.name()).toUpperCase());
generalConfig.getYaml().setComment("verification.log-connections",
"Should Sonar log new verification attempts?");
verification.logConnections = generalConfig.getBoolean("verification.log-connections", true);
@@ -481,16 +501,25 @@ public final class SonarConfiguration {
"Amount of time that has to pass before a player times out");
verification.readTimeout = clamp(generalConfig.getInt("verification.read-timeout", 3500), 500, 30000);
generalConfig.getYaml().setComment("verification.max-players",
"Maximum number of players verifying at the same time");
verification.maxVerifyingPlayers = clamp(generalConfig.getInt("verification.max-players", 1024), 1,
Short.MAX_VALUE);
generalConfig.getYaml().setComment("verification.rejoin-delay",
"Minimum number of rejoin delay during verification");
verification.reconnectDelay = clamp(generalConfig.getInt("verification.rejoin-delay", 8000), 0, 100000);
// Webhooks
generalConfig.getYaml().setComment("verification.whitelisted-protocols",
"List of protocol IDs which are not checked by Sonar (verification bypass)"
+ LINE_SEPARATOR + "You can find the full list of all protocol IDs here:"
+ LINE_SEPARATOR + "https://wiki.vg/Protocol_version_numbers"
+ LINE_SEPARATOR + "For example, Minecraft 1.20 has the ID 763.");
verification.whitelistedProtocols.clear();
verification.whitelistedProtocols.addAll(generalConfig.getIntList("verification.whitelisted-protocols",
new ArrayList<>(0)));
generalConfig.getYaml().setComment("verification.blacklisted-protocols",
"List of protocol IDs which are unable to join the server at all");
verification.blacklistedProtocols.clear();
verification.blacklistedProtocols.addAll(generalConfig.getIntList("verification.blacklisted-protocols",
new ArrayList<>(0)));
generalConfig.getYaml().setComment("webhook",
"Bot attack notifications can also be sent to your Discord server using webhooks");
generalConfig.getYaml().setComment("webhook.url",
@@ -605,7 +634,7 @@ public final class SonarConfiguration {
"%prefix%<red>Usage: /sonar %usage%"));
messagesConfig.getYaml().setComment("commands.invalid-ip-address",
"Message that is shown when someone provides an invalid IP address (Invalid characters)");
"Message that is shown when someone provides an invalid IP address (Invalid format)");
commands.incorrectIpAddress = formatString(messagesConfig.getString("commands.invalid-ip-address",
"%prefix%The IP address you provided seems to be invalid."));
@@ -614,11 +643,6 @@ public final class SonarConfiguration {
commands.illegalIpAddress = formatString(messagesConfig.getString("commands.illegal-ip-address",
"%prefix%The IP address you provided seems to be either a local or loopback IP."));
messagesConfig.getYaml().setComment("commands.unknown-ip-address",
"Message that is shown when someone provides an unknown IP address (Unknown Host)");
commands.unknownIpAddress = formatString(messagesConfig.getString("commands.unknown-ip-address",
"%prefix%The IP address you provided seems to be unknown."));
messagesConfig.getYaml().setComment("commands.player-only",
"Message that is shown when the console runs a command that is player-only");
commands.playersOnly = formatString(messagesConfig.getString("commands.player-only",
@@ -641,29 +665,6 @@ public final class SonarConfiguration {
commands.subCommandNoPerm = formatString(messagesConfig.getString("commands.subcommand-no-permission",
"%prefix%<red>You do not have permission to execute this subcommand. <gray>(%permission%)"));
messagesConfig.getYaml().setComment("lockdown",
"Translations for '/sonar lockdown'");
messagesConfig.getYaml().setComment("lockdown.notification",
"Message that is shown when an admin joins the server during lockdown");
lockdown.notification = formatString(messagesConfig.getString("lockdown.notification",
"%prefix%<green>Hey, the server is currently in lockdown mode. If you want to disable the lockdown mode,"
+ " type <white>/sonar lockdown<green>."
));
messagesConfig.getYaml().setComment("lockdown.console-log",
"Message that is shown to console when a normal player tries joining the server during lockdown");
lockdown.consoleLog = messagesConfig.getString("lockdown.console-log",
"%player% (%ip%, %protocol%) tried to join during lockdown mode.");
messagesConfig.getYaml().setComment("lockdown.disconnect-message",
"Message that is shown to a normal player when they try joining the server during lockdown");
lockdown.disconnect = deserialize(fromList(messagesConfig.getStringList("lockdown.disconnect-message",
Arrays.asList(
"%header%",
"<red>The server is currently locked down, please try again later.",
"%footer%"
))));
messagesConfig.getYaml().setComment("commands.main",
"Translations for '/sonar'");
messagesConfig.getYaml().setComment("commands.main.header",
@@ -703,18 +704,6 @@ public final class SonarConfiguration {
commands.reloaded = formatString(messagesConfig.getString("commands.reload.finish",
"%prefix%<green>Successfully reloaded <gray>(%taken%ms)"));
messagesConfig.getYaml().setComment("commands.lockdown",
"Translations for '/sonar lockdown'");
messagesConfig.getYaml().setComment("commands.lockdown.enabled",
"Message that is shown when a player enables server lockdown");
lockdown.activated = formatString(messagesConfig.getString("commands.lockdown.enabled",
"%prefix%The server is now in lockdown mode."));
messagesConfig.getYaml().setComment("commands.lockdown.disabled",
"Message that is shown when a player disables server lockdown");
lockdown.deactivated = formatString(messagesConfig.getString("commands.lockdown.disabled",
"%prefix%The server is no longer in lockdown mode."));
messagesConfig.getYaml().setComment("commands.verbose",
"Translations for '/sonar verbose'");
messagesConfig.getYaml().setComment("commands.verbose.subscribed",
@@ -883,6 +872,25 @@ public final class SonarConfiguration {
verification.successLog = formatString(messagesConfig.getString("verification.logs.successful",
"%name% has been verified successfully (%time%s!)."));
messagesConfig.getYaml().setComment("verification.welcome",
"Message that is shown to the player when they are being checked for valid gravity");
verification.gravity.youAreBeingChecked = deserialize(formatString(messagesConfig.getString("verification.welcome",
"%prefix%<gray>Please wait a moment for the verification to finish...")));
messagesConfig.getYaml().setComment("verification.captcha.enter-code",
"Message that is shown to the player when they have to enter the answer to the captcha");
verification.map.enterCode = deserialize(formatString(messagesConfig.getString("verification.captcha.enter-code",
"%prefix%<green>Please enter the code in chat that is displayed on the map.")));
messagesConfig.getYaml().setComment("verification.captcha.action-bar",
"Timer that is shown to the player when they have to enter the answer to the captcha"
+ LINE_SEPARATOR + "(Set this to '' to disable the action bar message)");
verification.map.enterCodeActionBar = formatString(messagesConfig.getString("verification.captcha.action-bar",
"%prefix%<green>You have %time-left% seconds left to enter the code in chat"));
messagesConfig.getYaml().setComment("verification.captcha.incorrect",
"Message that is shown to the player when they enter the wrong answer in chat");
verification.map.failedCaptcha = deserialize(formatString(messagesConfig.getString("verification.captcha.incorrect",
"%prefix%<red>You have entered the wrong code. Please try again.")));
messagesConfig.getYaml().setComment("verification.too-many-players",
"Disconnect message that is shown when too many players are verifying at the same time");
verification.tooManyPlayers = deserialize(fromList(messagesConfig.getStringList("verification.too-many-players",
@@ -952,6 +960,17 @@ public final class SonarConfiguration {
"%footer%"
))));
messagesConfig.getYaml().setComment("verification.blacklisted-protocol",
"Disconnect message that is shown when someone joins with a blacklisted version");
verification.protocolBlacklisted = deserialize(fromList(messagesConfig.getStringList("verification" +
".blacklisted-protocol",
Arrays.asList(
"%header%",
"<red>You are using a version that is not allowed on our server.",
"<gold>Need help logging in? <gray>%support-url%",
"%footer%"
))));
messagesConfig.getYaml().setComment("verification.already-online",
"Disconnect message that is shown when someone tries verifying with an account that is online");
verification.alreadyConnected = deserialize(fromList(messagesConfig.getStringList("verification.already-online",
@@ -40,11 +40,10 @@ public final class Fallback {
public static final Fallback INSTANCE = new Fallback();
private static final @NotNull Sonar SONAR = Objects.requireNonNull(Sonar.get());
private final Map<String, InetAddress> connected = new ConcurrentHashMap<>();
private final Map<String, InetAddress> connected = new ConcurrentHashMap<>(64, 0.75f);
// Only block the player for a few minutes to avoid issues
private final ExpiringCache<String> blacklisted = Cappuccino.buildExpiring(
10L, TimeUnit.MINUTES, 5000L
);
private final ExpiringCache<InetAddress> blacklisted = Cappuccino.buildExpiring(
10L, TimeUnit.MINUTES, 5000L);
private final @NotNull FallbackQueue queue = FallbackQueue.INSTANCE;
private final @NotNull FallbackRatelimiter ratelimiter = FallbackRatelimiter.INSTANCE;
@@ -69,5 +69,7 @@ public final class FallbackQueue {
// Run the attack check task
Sonar.get().getAttackTracker().checkIfUnderAttack();
// Clean up the cache of rate-limited IPs
Sonar.get().getFallback().getRatelimiter().cleanUpCache();
}
}
@@ -31,6 +31,15 @@ public final class FallbackRatelimiter {
@Setter
private ExpiringCache<InetAddress> expiringCache;
/**
* We don't want to clean up the cache in the
* {@link #attempt(InetAddress)} method because
* it would take up too many resources.
*/
public void cleanUpCache() {
expiringCache.cleanUp(false);
}
/**
* Checks if the player has tried verifying too fast
*
@@ -39,11 +48,9 @@ public final class FallbackRatelimiter {
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean attempt(final @NotNull InetAddress inetAddress) {
// Clean up the cache
expiringCache.cleanUp(false);
// Cache the IP address if it's not already cached
if (!expiringCache.has(inetAddress)) {
// Cache the IP address
expiringCache.put(inetAddress);
return true;
}
@@ -115,7 +115,7 @@ public interface FallbackUser<X, Y> {
// Call the BotBlacklistedEvent for external API usage
Sonar.get().getEventManager().publish(new UserBlacklistedEvent(this));
getFallback().getBlacklisted().put(getInetAddress().toString());
getFallback().getBlacklisted().put(getInetAddress());
getFallback().getLogger().info(Sonar.get().getConfig().getVerification().getBlacklistLog()
.replace("%ip%", Sonar.get().getConfig().formatAddress(getInetAddress()))
.replace("%protocol%", String.valueOf(getProtocolVersion().getProtocol())));
@@ -22,6 +22,7 @@ import lombok.RequiredArgsConstructor;
import java.util.*;
@Getter
@RequiredArgsConstructor
public enum ProtocolVersion {
UNKNOWN(-1),
@@ -64,9 +65,9 @@ public enum ProtocolVersion {
MINECRAFT_1_19_3(761),
MINECRAFT_1_19_4(762),
MINECRAFT_1_20(763),
MINECRAFT_1_20_2(764);
MINECRAFT_1_20_2(764),
MINECRAFT_1_20_3(765);
@Getter
private final int protocol;
public static final ProtocolVersion MINIMUM_VERSION = MINECRAFT_1_7_2;
@@ -95,7 +96,7 @@ public enum ProtocolVersion {
}
SUPPORTED_VERSIONS = Collections.unmodifiableSet(versions);
LATEST_VERSION = new ArrayList<>(versions).get(versions.size() - 1);
LATEST_VERSION = (ProtocolVersion) versions.toArray()[versions.size() - 1];
}
}
@@ -18,12 +18,14 @@
package xyz.jonesdev.sonar.bungee.fallback;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.connection.DownstreamBridge;
import net.md_5.bungee.connection.UpstreamBridge;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.HandlerBoss;
import net.md_5.bungee.netty.PacketHandler;
import net.md_5.bungee.protocol.PacketWrapper;
import org.jetbrains.annotations.NotNull;
public final class FallbackHandlerBoss extends HandlerBoss {
@@ -60,6 +62,13 @@ public final class FallbackHandlerBoss extends HandlerBoss {
}
}
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
if (msg instanceof HAProxyMessage || msg instanceof PacketWrapper) {
super.channelRead(ctx, msg);
}
}
@Override
public void exceptionCaught(final @NotNull ChannelHandlerContext ctx, final Throwable throwable) throws Exception {
if (ctx.channel().isActive()) {
@@ -20,6 +20,7 @@ package xyz.jonesdev.sonar.bungee.fallback;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.DecoderException;
import lombok.Getter;
import lombok.val;
@@ -94,7 +95,7 @@ public final class FallbackInitialHandler extends InitialHandler {
public void handle(final StatusRequest statusRequest) throws Exception {
// Fix status packet spam exploit
if (receivedStatusPacket) {
throw new ConditionFailedException("Duplicate status packet");
throw new CorruptedFrameException("Duplicate status packet");
}
receivedStatusPacket = true;
// Run the rest of the method asynchronously
@@ -102,7 +103,7 @@ public final class FallbackInitialHandler extends InitialHandler {
// The channel always stays open because the client sends
// a StatusRequest and a Ping packet after one another
if (!isConnected()) {
throw new ConditionFailedException("Not connected anymore");
throw new CorruptedFrameException("Not connected anymore");
}
try {
super.handle(statusRequest);
@@ -119,11 +120,12 @@ public final class FallbackInitialHandler extends InitialHandler {
// Fix login packet spam exploit
if (receivedLoginPacket || user != null) {
throw new ConditionFailedException("Duplicate login packet");
throw new CorruptedFrameException("Duplicate login packet");
}
receivedLoginPacket = true;
// Cache protocol version so other handlers don't throw NPEs
protocolVersion = ProtocolVersion.fromId(getHandshake().getProtocolVersion());
final int protocolId = getHandshake().getProtocolVersion();
protocolVersion = ProtocolVersion.fromId(protocolId);
final Channel channel = channelWrapper.getHandle();
// Run in the channel's event loop
@@ -135,26 +137,19 @@ public final class FallbackInitialHandler extends InitialHandler {
// Increase total traffic statistic
Statistics.TOTAL_TRAFFIC.increment();
final InetAddress inetAddress = getAddress().getAddress();
// Check the blacklist here since we cannot let the player "ghost join"
if (FALLBACK.getBlacklisted().has(inetAddress)) {
closeWith(getKickPacket(Sonar.get().getConfig().getVerification().getBlacklisted()));
return;
}
// Check if the verification is enabled
if (!Sonar.get().getFallback().shouldVerifyNewPlayers()) {
super.handle(loginRequest);
return;
}
final InetAddress inetAddress = getAddress().getAddress();
val uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + loginRequest.getData()).getBytes(StandardCharsets.UTF_8));
// Check if the player is already verified
if (Sonar.get().getVerifiedPlayerController().has(inetAddress, uuid)) {
super.handle(loginRequest);
return;
}
// Check the blacklist here since we cannot let the player "ghost join"
if (FALLBACK.getBlacklisted().has(inetAddress.toString())) {
closeWith(getKickPacket(Sonar.get().getConfig().getVerification().getBlacklisted()));
return;
}
// Completely skip Geyser connections
if (isGeyserConnection(channel)) {
FALLBACK.getLogger().info("Skipping Geyser player: {}{}",
@@ -163,6 +158,25 @@ public final class FallbackInitialHandler extends InitialHandler {
return;
}
// Check if the protocol ID of the player is not allowed to enter the server
if (Sonar.get().getConfig().getVerification().getBlacklistedProtocols().contains(protocolId)) {
closeWith(getKickPacket(Sonar.get().getConfig().getVerification().getProtocolBlacklisted()));
return;
}
val uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + loginRequest.getData()).getBytes(StandardCharsets.UTF_8));
// Check if the player is already verified
if (Sonar.get().getVerifiedPlayerController().has(inetAddress, uuid)) {
super.handle(loginRequest);
return;
}
// Check if the protocol ID of the player is allowed to bypass verification
if (Sonar.get().getConfig().getVerification().getWhitelistedProtocols().contains(protocolId)) {
super.handle(loginRequest);
return;
}
// Create wrapped Fallback user
user = new FallbackUserWrapper(
FALLBACK, channelWrapper, this,
@@ -202,13 +216,6 @@ public final class FallbackInitialHandler extends InitialHandler {
return;
}
// We cannot allow too many players on our Fallback server
// There's technically no reason for limiting this, but we'll better stay safe.
if (FALLBACK.getConnected().size() > Sonar.get().getConfig().getVerification().getMaxVerifyingPlayers()) {
closeWith(getKickPacket(Sonar.get().getConfig().getVerification().getTooManyPlayers()));
return;
}
// Check if the IP address is currently being rate-limited
if (!FALLBACK.getRatelimiter().attempt(inetAddress)) {
closeWith(getKickPacket(Sonar.get().getConfig().getVerification().getTooFastReconnect()));
@@ -234,12 +241,9 @@ public final class FallbackInitialHandler extends InitialHandler {
// Add better timeout handler to avoid known exploits or issues
// We also want to timeout bots quickly to avoid flooding
pipeline.replace(
TIMEOUT_HANDLER,
TIMEOUT_HANDLER,
new FallbackTimeoutHandler(Sonar.get().getConfig().getVerification().getReadTimeout(),
TimeUnit.MILLISECONDS)
);
final int readTimeout = Sonar.get().getConfig().getVerification().getReadTimeout();
pipeline.replace(TIMEOUT_HANDLER, TIMEOUT_HANDLER,
new FallbackTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
// Disconnect if the protocol version could not be resolved
if (user.getProtocolVersion().isUnknown()) {
@@ -298,10 +302,8 @@ public final class FallbackInitialHandler extends InitialHandler {
? FallbackPacketRegistry.CONFIG : FallbackPacketRegistry.GAME);
// Replace normal decoder to allow custom packets
user.getPipeline().replace(
PACKET_DECODER, FALLBACK_PACKET_DECODER, new FallbackPacketDecoder(user,
new FallbackVerificationHandler(user, loginRequest.getData(), uuid)
));
user.getPipeline().replace(PACKET_DECODER, FALLBACK_PACKET_DECODER,
new FallbackPacketDecoder(user, new FallbackVerificationHandler(user, loginRequest.getData(), uuid)));
}));
} catch (Throwable throwable) {
throw new ReflectiveOperationException(throwable);
@@ -309,7 +311,7 @@ public final class FallbackInitialHandler extends InitialHandler {
});
}
private static final Map<Component, Kick> CACHED_KICK_PACKETS = new ConcurrentHashMap<>(16);
private static final Map<Component, Kick> CACHED_KICK_PACKETS = new ConcurrentHashMap<>(10);
public static @NotNull Kick getKickPacket(final @NotNull Component component) {
Kick cachedKickPacket = CACHED_KICK_PACKETS.get(component);
@@ -18,12 +18,8 @@
package xyz.jonesdev.sonar.bungee.fallback;
import lombok.RequiredArgsConstructor;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.event.LoginEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import org.jetbrains.annotations.NotNull;
@@ -59,41 +55,4 @@ public final class FallbackListener implements Listener {
}
}
}
@EventHandler
@SuppressWarnings("deprecation")
public void handle(final @NotNull PostLoginEvent event) {
if (Sonar.get().getConfig().getLockdown().isEnabled()) {
if (!event.getPlayer().hasPermission(Sonar.get().getConfig().getLockdown().getBypassPermission())) {
final PendingConnection pendingConnection = event.getPlayer().getPendingConnection();
// Try to close the channel with a custom serialized disconnect component
if (pendingConnection instanceof FallbackInitialHandler) {
final FallbackInitialHandler fallbackInitialHandler = (FallbackInitialHandler) pendingConnection;
final Component component = Sonar.get().getConfig().getLockdown().getDisconnect();
fallbackInitialHandler.closeWith(FallbackInitialHandler.getKickPacket(component));
} else {
// Fallback by disconnecting without a message
pendingConnection.disconnect();
Sonar.get().getLogger().warn("Fallback handler of {} is missing", event.getPlayer().getName());
return;
}
if (Sonar.get().getConfig().getLockdown().isLogAttempts()) {
Sonar.get().getLogger().info(Sonar.get().getConfig().getLockdown().getConsoleLog()
.replace("%player%", event.getPlayer().getName())
.replace("%ip%", Sonar.get().getConfig()
.formatAddress(event.getPlayer().getAddress().getAddress()))
.replace("%protocol%",
String.valueOf(event.getPlayer().getPendingConnection().getVersion())));
}
} else if (Sonar.get().getConfig().getLockdown().isNotifyAdmins()) {
final Audience audience = Sonar.get().getVerboseHandler().getAudiences().get(event.getPlayer().getName());
if (audience != null) {
final String notification = Sonar.get().getConfig().getLockdown().getNotification();
final Component deserialized = MiniMessage.miniMessage().deserialize(notification);
audience.sendMessage(deserialized);
}
}
}
}
}
@@ -20,20 +20,25 @@ package xyz.jonesdev.sonar.common.fallback;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.DecoderException;
import lombok.Setter;
import lombok.val;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import xyz.jonesdev.sonar.api.Sonar;
import xyz.jonesdev.sonar.api.event.impl.UserVerifySuccessEvent;
import xyz.jonesdev.sonar.api.fallback.FallbackUser;
import xyz.jonesdev.sonar.api.model.VerifiedPlayer;
import xyz.jonesdev.sonar.api.timer.SystemTimer;
import xyz.jonesdev.sonar.common.fallback.protocol.*;
import xyz.jonesdev.sonar.common.fallback.protocol.map.ItemMapType;
import xyz.jonesdev.sonar.common.fallback.protocol.map.MapInfoPreparer;
import xyz.jonesdev.sonar.common.fallback.protocol.map.PreparedMapInfo;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.config.FinishConfiguration;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.login.LoginAcknowledged;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.play.*;
import xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Pattern;
@@ -44,22 +49,28 @@ import static xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion.*;
import static xyz.jonesdev.sonar.common.fallback.protocol.FallbackPreparer.*;
public final class FallbackVerificationHandler implements FallbackPacketListener {
private static final Random RANDOM = new Random();
// General
private final SystemTimer login = new SystemTimer();
private final @NotNull FallbackUser<?, ?> user;
private final String username;
private final UUID playerUuid;
private @NotNull State state = State.LOGIN_ACK; // 1.20.2
// Checks
private short expectedTransactionId;
private long expectedKeepAliveId;
private int expectedTeleportId = -1;
private int tick, totalReceivedPackets;
private int ignoredMovementTicks;
private int expectedKeepAliveId, expectedTeleportId = -1;
private int tick, totalReceivedPackets, ignoredMovementTicks;
private double posX, posY, posZ, lastY;
private boolean resolvedClientBrand, resolvedClientSettings;
@Setter
private @NotNull State state = State.LOGIN_ACK;
private boolean listenForMovements;
private final SystemTimer login = new SystemTimer();
private static final Random RANDOM = new Random();
// Map captcha
private final SystemTimer keepAlive = new SystemTimer();
private final SystemTimer actionBar = new SystemTimer();
private @Nullable PreparedMapInfo captcha;
private int captchaTriesLeft;
public enum State {
// 1.20.2 configuration state
@@ -70,6 +81,8 @@ public final class FallbackVerificationHandler implements FallbackPacketListener
CLIENT_SETTINGS, PLUGIN_MESSAGE, TRANSACTION,
// PLAY checks
TELEPORT, POSITION,
// Captcha
MAP_CAPTCHA,
// Done
SUCCESS
}
@@ -142,10 +155,11 @@ public final class FallbackVerificationHandler implements FallbackPacketListener
final boolean v1_20_2 = user.getProtocolVersion().compareTo(MINECRAFT_1_20_2) >= 0;
if (!v1_20_2) {
// Set the state to CLIENT_SETTINGS to avoid false positives
// and go on with the flow of the verification.
// (1.20.2 needs the LOGIN_ACK state) and go on with
// the flow of the verification.
state = State.CLIENT_SETTINGS;
}
// Select the JoinGame packet for the respective protocol version
// Send the JoinGame packet so we can continue the verification
user.write(joinGame);
if (v1_20_2) {
// Perform the transaction check since the ClientSettings
@@ -165,21 +179,37 @@ public final class FallbackVerificationHandler implements FallbackPacketListener
// Teleport the player to the spawn position
user.delayedWrite(new PositionLook(
SPAWN_X_POSITION, dynamicSpawnYPosition, SPAWN_Z_POSITION,
0f, 0f, expectedTeleportId, false
));
0f, -90f, expectedTeleportId, false));
// Make sure the player escapes the 1.18.2+ "Loading terrain" screen
if (user.getProtocolVersion().compareTo(MINECRAFT_1_18_2) >= 0) {
user.delayedWrite(dynamicSpawnPosition);
}
}
private void sendChunkData() {
// Set the state to POSITION to avoid false positives
// and go on with the flow of the verification.
state = State.POSITION;
// 1.20.3 packets introduced game events
if (user.getProtocolVersion().compareTo(MINECRAFT_1_20_3) >= 0) {
// Make sure the client knows that we're sending chunks next
user.delayedWrite(START_WRITING_CHUNKS);
}
// Teleport player into the fake lobby by sending an empty chunk
user.delayedWrite(EMPTY_CHUNK_DATA);
// Send an UpdateSectionBlocks packet with a platform of blocks
// to check if the player collides with the solid platform.
user.delayedWrite(updateSectionBlocks);
// Send all packets in one flush
user.getChannel().flush();
// Checking gravity is disabled, just finish verification
if (!Sonar.get().getConfig().getVerification().getGravity().isEnabled()) {
// Switch to captcha state if needed
captchaOrFinish();
} else {
// Make sure the player knows we are checking them
user.delayedWrite(youAreBeingChecked);
// Send all packets in one flush
user.getChannel().flush();
}
}
private static boolean validateClientLocale(final @SuppressWarnings("unused") @NotNull FallbackUser<?, ?> user,
@@ -216,13 +246,60 @@ public final class FallbackVerificationHandler implements FallbackPacketListener
public void handle(final @NotNull FallbackPacket packet) {
// The player has already been verified, drop all other packets
if (state == State.SUCCESS) return;
// Check for timeout since the player could be sending packets but not important ones
final long timeout = Sonar.get().getConfig().getVerification().getMaxPing();
// We are expecting a captcha code in chat, drop all other packets
if (state == State.MAP_CAPTCHA) {
// Check if the player took too long to enter the captcha
final int maxDuration = Sonar.get().getConfig().getVerification().getMap().getMaxDuration();
checkFrame(!login.elapsed(maxDuration), "took too long to enter captcha");
// Handle incoming chat messages
if (packet instanceof Chat) {
final Chat chat = (Chat) packet;
Objects.requireNonNull(captcha);
if (!chat.getMessage().equals(captcha.getInfo().getAnswer())) {
// Captcha is incorrect
checkFrame(captchaTriesLeft-- > 0, "failed captcha too often");
user.write(incorrectCaptcha);
return;
}
// Captcha is correct
finish();
return;
}
// Every second
if (actionBar.elapsed(1000L)) {
final String actionBarMessage = Sonar.get().getConfig().getVerification().getMap().getEnterCodeActionBar();
// Only send action bar if the message is actually supposed to be sent
if (!actionBarMessage.isEmpty()) {
final String timeLeft = String.format("%.0f", (maxDuration - login.delay()) / 1000D);
user.write(new Chat(MiniMessage.miniMessage().deserialize(
actionBarMessage.replace("%time-left%", timeLeft)), Chat.GAME_INFO_TYPE));
// Make sure to reset the timer
actionBar.reset();
}
}
// Every about 10 seconds
if (keepAlive.elapsed(timeout)) {
// Send the message again to remind the player
user.delayedWrite(enterCodeMessage);
// Send a KeepAlive packet to prevent timeout
user.delayedWrite(CAPTCHA_KEEP_ALIVE);
// Send both packets in one flush
user.getChannel().flush();
// Make sure to reset the timer
keepAlive.reset();
}
return;
}
// Check if the player is not sending a ton of packets to the server
final int maxPackets = Sonar.get().getConfig().getVerification().getMaxLoginPackets() + maxMovementTick;
checkFrame(++totalReceivedPackets < maxPackets, "too many packets");
// Check for timeout since the player could be sending packets but not important ones
final long timeout = Sonar.get().getConfig().getVerification().getMaxPing();
// Check if the time limit has exceeded
if (login.elapsed(timeout)) {
user.getChannel().close();
@@ -321,18 +398,6 @@ public final class FallbackVerificationHandler implements FallbackPacketListener
// Check if the transaction ID is valid
checkFrame(transaction.getId() == expectedTransactionId, "invalid transaction id");
// Checking gravity is disabled, just finish verification
if (!Sonar.get().getConfig().getVerification().isCheckGravity()) {
finish();
return;
}
// TODO: implement ChunkData packet for 1.20.2
if (user.getProtocolVersion().compareTo(MINECRAFT_1_20_2) >= 0) {
finish();
return;
}
// First, send an Abilities packet to the client to make
// sure the player falls even in spectator mode.
// Then, teleport the player to the spawn position.
@@ -422,7 +487,7 @@ public final class FallbackVerificationHandler implements FallbackPacketListener
// We have to account for this or the player will fail the verification.
if (deltaY == 0) {
// Check for too many ignored Y ticks
final int maxIgnoredTicks = Sonar.get().getConfig().getVerification().getMaxIgnoredTicks();
final int maxIgnoredTicks = Sonar.get().getConfig().getVerification().getGravity().getMaxIgnoredTicks();
checkFrame(++ignoredMovementTicks < maxIgnoredTicks, "too many ignored ticks");
return;
}
@@ -443,7 +508,7 @@ public final class FallbackVerificationHandler implements FallbackPacketListener
// The player is colliding to blocks, finish verification
if (ground) {
finish();
captchaOrFinish();
return;
}
} else {
@@ -471,17 +536,41 @@ public final class FallbackVerificationHandler implements FallbackPacketListener
tick++;
}
private void assertState(final @NotNull State expectedState) {
if (expectedState != state) {
user.fail("expected " + expectedState + ", got " + state);
private void captchaOrFinish() {
if (Sonar.get().getConfig().getVerification().getMap().isEnabled()) {
// Set the state to MAP_CAPTCHA, so we don't handle any unnecessary packets
state = State.MAP_CAPTCHA;
if (!Sonar.get().getConfig().getVerification().getGravity().isEnabled()
&& user.getProtocolVersion().compareTo(MINECRAFT_1_18_2) >= 0) {
// Make sure the player escapes the 1.18.2+ "Loading terrain" screen
user.delayedWrite(CAPTCHA_SPAWN_POSITION);
}
// Initialize the map captcha
handleMapCaptcha();
} else {
// Finish the verification
finish();
}
}
private void checkFrame(final boolean condition, final String message) {
if (!condition) {
user.fail(message);
throw new CorruptedFrameException(message);
}
private void handleMapCaptcha() {
// Reset max tries
captchaTriesLeft = Sonar.get().getConfig().getVerification().getMap().getMaxTries();
// Set slot to map
user.delayedWrite(new SetSlot(0, 36, 1, 0,
ItemMapType.FILLED_MAP.getId(user.getProtocolVersion()), SetSlot.MAP_NBT));
// Send random captcha to the player
captcha = MapInfoPreparer.getRandomCaptcha();
Objects.requireNonNull(captcha).write(user);
// Teleport the player to the position above the platform
user.delayedWrite(CAPTCHA_POSITION);
// Make sure the player cannot move
user.delayedWrite(CAPTCHA_ABILITIES);
// Make sure the player knows what to do
user.delayedWrite(enterCodeMessage);
// Send all packets in one flush
user.getChannel().flush();
}
private void finish() {
@@ -504,4 +593,26 @@ public final class FallbackVerificationHandler implements FallbackPacketListener
.replace("%name%", username)
.replace("%time%", login.toString()));
}
/**
* Fails the verification if a certain state is unexpected.
*
* @param expectedState Expected state
*/
private void assertState(final @NotNull State expectedState) {
checkFrame(state == expectedState, "expected " + expectedState + ", got " + state);
}
/**
* Checks if a certain condition is met, fails the verification if not.
*
* @param condition Condition to fail if it's false
* @param message Messages displayed in the stacktrace
*/
private void checkFrame(final boolean condition, final String message) {
if (!condition) {
user.fail(message);
throw new CorruptedFrameException(message);
}
}
}
@@ -33,14 +33,13 @@ import static xyz.jonesdev.sonar.common.utility.protocol.VarIntUtil.readVarInt;
public final class FallbackPacketDecoder extends ChannelInboundHandlerAdapter {
private final FallbackUser<?, ?> user;
private final FallbackPacketListener listener;
private @NotNull FallbackPacketRegistry.ProtocolRegistry registry;
private FallbackPacketRegistry.ProtocolRegistry registry;
public FallbackPacketDecoder(final @NotNull FallbackUser<?, ?> user,
final @NotNull FallbackPacketListener listener) {
this.user = user;
this.registry = (user.getProtocolVersion().compareTo(MINECRAFT_1_20_2) >= 0 ? LOGIN : GAME)
.getProtocolRegistry(SERVERBOUND, user.getProtocolVersion());
this.listener = listener;
updateRegistry(user.getProtocolVersion().compareTo(MINECRAFT_1_20_2) >= 0 ? LOGIN : GAME);
}
public void updateRegistry(final @NotNull FallbackPacketRegistry registry) {
@@ -66,8 +65,7 @@ public final class FallbackPacketDecoder extends ChannelInboundHandlerAdapter {
final int packetId = readVarInt(byteBuf);
final FallbackPacket packet = registry.createPacket(packetId);
// If the packet hasn't been found, skip it
// TODO: Can we fail the verification afterwards?
// If the packet isn't found, skip it
if (packet == null) {
byteBuf.readerIndex(originalReaderIndex);
return;
@@ -93,6 +91,9 @@ public final class FallbackPacketDecoder extends ChannelInboundHandlerAdapter {
// Let our verification handler process the packet
listener.handle(packet);
// Fire channel read to avoid timeout
ctx.fireChannelRead(packet);
} finally {
// Release the ByteBuf to avoid memory leaks
byteBuf.release();
@@ -23,7 +23,7 @@ import lombok.Data;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.config.FinishConfiguration;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.config.RegistrySync;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.config.RegistryData;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.login.LoginAcknowledged;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.login.LoginSuccess;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.play.*;
@@ -48,13 +48,13 @@ public enum FallbackPacketRegistry {
CONFIG {
{
clientbound.register(Disconnect.class, Disconnect::new,
map(0x01, MINECRAFT_1_20_2, false));
map(0x01, MINECRAFT_1_20_2, true));
clientbound.register(FinishConfiguration.class, FinishConfiguration::new,
map(0x02, MINECRAFT_1_20_2, false));
clientbound.register(KeepAlive.class, KeepAlive::new,
map(0x03, MINECRAFT_1_20_2, false));
clientbound.register(RegistrySync.class, RegistrySync::new,
map(0x05, MINECRAFT_1_20_2, false));
clientbound.register(RegistryData.class, RegistryData::new,
map(0x05, MINECRAFT_1_20_2, true));
serverbound.register(ClientSettings.class, ClientSettings::new,
map(0x00, MINECRAFT_1_20_2, false));
@@ -166,7 +166,8 @@ public enum FallbackPacketRegistry {
map(0x40, MINECRAFT_1_19_1, true),
map(0x3F, MINECRAFT_1_19_3, true),
map(0x43, MINECRAFT_1_19_4, true),
map(0x45, MINECRAFT_1_20_2, true));
map(0x45, MINECRAFT_1_20_2, true),
map(0x47, MINECRAFT_1_20_3, true));
clientbound.register(Transaction.class, Transaction::new,
map(0x32, MINECRAFT_1_7_2, true),
map(0x11, MINECRAFT_1_9, true),
@@ -180,19 +181,73 @@ public enum FallbackPacketRegistry {
map(0x2E, MINECRAFT_1_19_3, true),
map(0x32, MINECRAFT_1_19_4, true),
map(0x33, MINECRAFT_1_20_2, true));
clientbound.register(DefaultSpawnPosition.class, DefaultSpawnPosition::new,
map(0x05, MINECRAFT_1_7_2, true),
map(0x43, MINECRAFT_1_9, true),
map(0x45, MINECRAFT_1_12, true),
map(0x46, MINECRAFT_1_12_1, true),
map(0x49, MINECRAFT_1_13, true),
map(0x4D, MINECRAFT_1_14, true),
map(0x4E, MINECRAFT_1_15, true),
map(0x42, MINECRAFT_1_16, true),
map(0x4B, MINECRAFT_1_17, true),
map(0x4A, MINECRAFT_1_19, true),
map(0x4D, MINECRAFT_1_19_1, true),
map(0x4C, MINECRAFT_1_19_3, true),
map(0x50, MINECRAFT_1_19_4, true),
map(0x52, MINECRAFT_1_20_2, true),
map(0x54, MINECRAFT_1_20_3, true));
clientbound.register(MapData.class, MapData::new,
map(0x34, MINECRAFT_1_7_2, true),
map(0x24, MINECRAFT_1_9, true),
map(0x26, MINECRAFT_1_13, true),
map(0x27, MINECRAFT_1_15, true),
map(0x26, MINECRAFT_1_16, true),
map(0x25, MINECRAFT_1_16_2, true),
map(0x27, MINECRAFT_1_17, true),
map(0x24, MINECRAFT_1_19, true),
map(0x26, MINECRAFT_1_19_1, true),
map(0x25, MINECRAFT_1_19_3, true),
map(0x29, MINECRAFT_1_19_4, true),
map(0x2A, MINECRAFT_1_20_2, true));
clientbound.register(SetSlot.class, SetSlot::new,
map(0x2F, MINECRAFT_1_7_2, true),
map(0x16, MINECRAFT_1_9, true),
map(0x17, MINECRAFT_1_13, true),
map(0x16, MINECRAFT_1_14, true),
map(0x17, MINECRAFT_1_15, true),
map(0x16, MINECRAFT_1_16, true),
map(0x15, MINECRAFT_1_16_2, true),
map(0x16, MINECRAFT_1_17, true),
map(0x13, MINECRAFT_1_19, true),
map(0x12, MINECRAFT_1_19_3, true),
map(0x14, MINECRAFT_1_19_4, true),
map(0x15, MINECRAFT_1_20_2, true));
clientbound.register(Chat.class, Chat::new,
map(0x02, MINECRAFT_1_7_2, true),
map(0x0F, MINECRAFT_1_9, true),
map(0x0E, MINECRAFT_1_13, true),
map(0x0F, MINECRAFT_1_15, true),
map(0x0E, MINECRAFT_1_16, true),
map(0x0F, MINECRAFT_1_18_2, true),
map(0x5F, MINECRAFT_1_19, true),
map(0x62, MINECRAFT_1_19_1, true),
map(0x60, MINECRAFT_1_19_3, true),
map(0x64, MINECRAFT_1_19_4, true),
map(0x67, MINECRAFT_1_20_2, true));
map(0x02, MINECRAFT_1_7_2, false),
map(0x0F, MINECRAFT_1_9, false),
map(0x0E, MINECRAFT_1_13, false),
map(0x0F, MINECRAFT_1_15, false),
map(0x0E, MINECRAFT_1_16, false),
map(0x0F, MINECRAFT_1_17, false),
map(0x5F, MINECRAFT_1_19, false),
map(0x62, MINECRAFT_1_19_1, false),
map(0x60, MINECRAFT_1_19_3, false),
map(0x64, MINECRAFT_1_19_4, false),
map(0x67, MINECRAFT_1_20_2, false),
map(0x69, MINECRAFT_1_20_2, false));
clientbound.register(GameEvent.class, GameEvent::new,
map(0x20, MINECRAFT_1_20_3, true));
serverbound.register(Chat.class, Chat::new,
map(0x01, MINECRAFT_1_7_2, false),
map(0x02, MINECRAFT_1_9, false),
map(0x03, MINECRAFT_1_12, false),
map(0x02, MINECRAFT_1_12_1, false),
map(0x03, MINECRAFT_1_14, false),
map(0x04, MINECRAFT_1_19, false),
map(0x05, MINECRAFT_1_19_1, false),
map(0x05, MINECRAFT_1_19_3, false));
serverbound.register(KeepAlive.class, KeepAlive::new,
map(0x00, MINECRAFT_1_7_2, false),
map(0x0B, MINECRAFT_1_9, false),
@@ -206,7 +261,8 @@ public enum FallbackPacketRegistry {
map(0x12, MINECRAFT_1_19_1, false),
map(0x11, MINECRAFT_1_19_3, false),
map(0x12, MINECRAFT_1_19_4, false),
map(0x14, MINECRAFT_1_20_2, false));
map(0x14, MINECRAFT_1_20_2, false),
map(0x15, MINECRAFT_1_20_3, false));
serverbound.register(ClientSettings.class, ClientSettings::new,
map(0x15, MINECRAFT_1_7_2, false),
map(0x04, MINECRAFT_1_9, false),
@@ -244,7 +300,8 @@ public enum FallbackPacketRegistry {
map(0x15, MINECRAFT_1_19_1, false),
map(0x14, MINECRAFT_1_19_3, false),
map(0x15, MINECRAFT_1_19_4, false),
map(0x17, MINECRAFT_1_20_2, false));
map(0x17, MINECRAFT_1_20_2, false),
map(0x18, MINECRAFT_1_20_3, false));
serverbound.register(TeleportConfirm.class, TeleportConfirm::new,
map(0x00, MINECRAFT_1_9, false));
serverbound.register(Position.class, Position::new,
@@ -260,7 +317,8 @@ public enum FallbackPacketRegistry {
map(0x14, MINECRAFT_1_19_1, false),
map(0x13, MINECRAFT_1_19_3, false),
map(0x14, MINECRAFT_1_19_4, false),
map(0x16, MINECRAFT_1_20_2, false));
map(0x16, MINECRAFT_1_20_2, false),
map(0x17, MINECRAFT_1_20_3, false));
serverbound.register(Player.class, Player::new,
map(0x03, MINECRAFT_1_7_2, false),
map(0x0F, MINECRAFT_1_9, false),
@@ -274,7 +332,8 @@ public enum FallbackPacketRegistry {
map(0x17, MINECRAFT_1_19_1, false),
map(0x16, MINECRAFT_1_19_3, false),
map(0x17, MINECRAFT_1_19_4, false),
map(0x19, MINECRAFT_1_20_2, false));
map(0x19, MINECRAFT_1_20_2, false),
map(0x1A, MINECRAFT_1_20_3, false));
serverbound.register(Transaction.class, Transaction::new,
map(0x0F, MINECRAFT_1_7_2, false),
map(0x05, MINECRAFT_1_9, false),
@@ -287,7 +346,8 @@ public enum FallbackPacketRegistry {
map(0x20, MINECRAFT_1_19_1, false),
map(0x1F, MINECRAFT_1_19_3, false),
map(0x20, MINECRAFT_1_19_4, false),
map(0x23, MINECRAFT_1_20_2, false));
map(0x23, MINECRAFT_1_20_2, false),
map(0x24, MINECRAFT_1_20_3, false));
}
};
@@ -308,14 +368,13 @@ public enum FallbackPacketRegistry {
private final Map<ProtocolVersion, ProtocolRegistry> versions;
PacketRegistry() {
Map<ProtocolVersion, ProtocolRegistry> mutableVersions = new EnumMap<>(ProtocolVersion.class);
for (ProtocolVersion version : ProtocolVersion.values()) {
final Map<ProtocolVersion, ProtocolRegistry> mutableVersions = new EnumMap<>(ProtocolVersion.class);
for (final ProtocolVersion version : ProtocolVersion.values()) {
if (!version.isLegacy() && !version.isUnknown()) {
mutableVersions.put(version, new ProtocolRegistry(version));
}
}
versions = Collections.unmodifiableMap(mutableVersions);
this.versions = Collections.unmodifiableMap(mutableVersions);
}
ProtocolRegistry getProtocolRegistry(final ProtocolVersion version) {
@@ -345,7 +404,7 @@ public enum FallbackPacketRegistry {
break;
}
final ProtocolRegistry registry = this.versions.get(protocol);
final ProtocolRegistry registry = versions.get(protocol);
if (registry == null) {
throw new IllegalArgumentException("Unknown protocol version "
+ current.protocolVersion);
@@ -374,14 +433,7 @@ public enum FallbackPacketRegistry {
private static ProtocolVersion getProtocolVersion(final @NotNull PacketMapping current,
final @NotNull PacketMapping next,
final @NotNull ProtocolVersion from) {
final ProtocolVersion last = (ProtocolVersion) SUPPORTED_VERSIONS.toArray()[SUPPORTED_VERSIONS.size() - 1];
final ProtocolVersion to = current == next ? last : next.protocolVersion;
if (from.compareTo(to) >= 0 && from != last) {
throw new IllegalArgumentException(String.format(
"Next mapping version (%s) should be lower then current (%s)", to, from));
}
return to;
return current == next ? LATEST_VERSION : next.protocolVersion;
}
}
@@ -19,31 +19,41 @@ package xyz.jonesdev.sonar.common.fallback.protocol;
import lombok.experimental.UtilityClass;
import xyz.jonesdev.sonar.api.Sonar;
import xyz.jonesdev.sonar.api.timer.SystemTimer;
import xyz.jonesdev.sonar.common.fallback.protocol.block.BlockPosition;
import xyz.jonesdev.sonar.common.fallback.protocol.block.BlockType;
import xyz.jonesdev.sonar.common.fallback.protocol.block.ChangedBlock;
import xyz.jonesdev.sonar.common.fallback.protocol.map.MapInfoPreparer;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.config.FinishConfiguration;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.config.RegistrySync;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.play.Abilities;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.play.EmptyChunkData;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.play.JoinGame;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.play.UpdateSectionBlocks;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.config.RegistryData;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.play.*;
@UtilityClass
public class FallbackPreparer {
// Abilities
public final FallbackPacket DEFAULT_ABILITIES = new Abilities((byte) 0, 0f, 0f);
public final FallbackPacket DEFAULT_ABILITIES = new Abilities(0x00, 0f, 0f);
public final FallbackPacket CAPTCHA_ABILITIES = new Abilities(0x02, 0f, 0f);
// Chunks
public final FallbackPacket EMPTY_CHUNK_DATA = new EmptyChunkData(0, 0);
// Finish Configuration
public final FallbackPacket FINISH_CONFIGURATION = new FinishConfiguration();
// Synchronize Registry
public final FallbackPacket REGISTRY_SYNC = new RegistrySync();
public final FallbackPacket REGISTRY_SYNC = new RegistryData();
// Keep Alive
public final FallbackPacket CAPTCHA_KEEP_ALIVE = new KeepAlive(0L);
// Game Event (1.20.3+)
public final FallbackPacket START_WRITING_CHUNKS = new GameEvent(13, 0);
// Chat
public FallbackPacket enterCodeMessage;
public FallbackPacket youAreBeingChecked;
public FallbackPacket incorrectCaptcha;
// JoinGame
public FallbackPacket joinGame;
// Update Section Blocks
public FallbackPacket updateSectionBlocks;
// Default Spawn Position
public FallbackPacket dynamicSpawnPosition;
// Collisions
public final int BLOCKS_PER_ROW = 8; // 8 * 8 = 64 (protocol maximum)
@@ -51,6 +61,13 @@ public class FallbackPreparer {
public final int SPAWN_Z_POSITION = 16 / 2; // middle of the chunk
public final int DEFAULT_Y_COLLIDE_POSITION = 255; // 255 is the maximum Y position allowed
// Captcha position
public final FallbackPacket CAPTCHA_POSITION = new PositionLook(
SPAWN_X_POSITION, 1337, SPAWN_Z_POSITION, 0f, 90f, 0, false);
public final FallbackPacket CAPTCHA_SPAWN_POSITION = new DefaultSpawnPosition(
SPAWN_X_POSITION, 1337, SPAWN_Z_POSITION);
// Blocks
private final ChangedBlock[] CHANGED_BLOCKS = new ChangedBlock[BLOCKS_PER_ROW * BLOCKS_PER_ROW];
public int maxMovementTick, dynamicSpawnYPosition;
@@ -58,8 +75,8 @@ public class FallbackPreparer {
public double maxFallDistance;
public void prepare() {
joinGame = new JoinGame(5,
Sonar.get().getConfig().getVerification().getGamemode().getId(),
joinGame = new JoinGame(0,
Sonar.get().getConfig().getVerification().getGravity().getGamemode().getId(),
0,
false,
0,
@@ -70,7 +87,7 @@ public class FallbackPreparer {
"minecraft:overworld");
maxFallDistance = 0;
maxMovementTick = Sonar.get().getConfig().getVerification().getMaxMovementTicks();
maxMovementTick = Sonar.get().getConfig().getVerification().getGravity().getMaxMovementTicks();
preparedCachedYMotions = new double[maxMovementTick + 8];
for (int i = 0; i < preparedCachedYMotions.length; i++) {
@@ -81,6 +98,7 @@ public class FallbackPreparer {
// Set the dynamic block and collide Y position based on the maximum fall distance
dynamicSpawnYPosition = DEFAULT_Y_COLLIDE_POSITION + (int) Math.ceil(maxFallDistance);
dynamicSpawnPosition = new DefaultSpawnPosition(SPAWN_X_POSITION, dynamicSpawnYPosition, SPAWN_Z_POSITION);
// Prepare collision platform positions
int index = 0;
@@ -90,13 +108,28 @@ public class FallbackPreparer {
x + (BLOCKS_PER_ROW / 2),
DEFAULT_Y_COLLIDE_POSITION,
z + (BLOCKS_PER_ROW / 2),
0, 0
);
0, 0);
CHANGED_BLOCKS[index++] = new ChangedBlock(position, BlockType.BARRIER);
}
}
// Prepare UpdateSectionBlocks packet
updateSectionBlocks = new UpdateSectionBlocks(0, 0, CHANGED_BLOCKS);
// "You are being checked" message
if (Sonar.get().getConfig().getVerification().getGravity().isEnabled()) {
youAreBeingChecked = new Chat(Sonar.get().getConfig().getVerification().getGravity().getYouAreBeingChecked());
}
if (Sonar.get().getConfig().getVerification().getMap().isEnabled()) {
enterCodeMessage = new Chat(Sonar.get().getConfig().getVerification().getMap().getEnterCode());
incorrectCaptcha = new Chat(Sonar.get().getConfig().getVerification().getMap().getFailedCaptcha());
final SystemTimer timer = new SystemTimer();
Sonar.get().getLogger().info("Precomputing map captcha answers...");
// Precompute captcha answers
MapInfoPreparer.prepare();
Sonar.get().getLogger().info("Successfully precomputed captcha answers in {}s!", timer);
}
}
}
@@ -28,7 +28,10 @@ import java.util.function.Function;
public enum BlockType {
STONE(protocolVersion -> 1),
BARRIER(protocolVersion -> {
// Link: https://github.com/PrismarineJS/minecraft-data/blob/master/data/pc/1.20/blocks.json
// Useful resources:
// - https://github.com/PrismarineJS/minecraft-data/blob/master/data/pc/
// - https://pokechu22.github.io/Burger/1.20.4.html
// - https://github.com/ViaVersion/Mappings/tree/main/mappings
switch (protocolVersion) {
case MINECRAFT_1_7_2:
case MINECRAFT_1_7_6:
@@ -73,7 +76,8 @@ public enum BlockType {
case MINECRAFT_1_20:
return 10225;
case MINECRAFT_1_20_2:
return 10365;
case MINECRAFT_1_20_3:
return 10366;
}
});
@@ -24,18 +24,15 @@ import org.jetbrains.annotations.NotNull;
public final class ChangedBlock {
private final @NotNull BlockPosition position;
private final BlockType type;
private final int legacyChunkPosCrammed;
private final int modernChunkPosCrammed;
private final int legacyBlockState, blockState;
public ChangedBlock(final @NotNull BlockPosition position, final BlockType type) {
this.position = position;
this.type = type;
this.legacyChunkPosCrammed = position.getX()
- (position.getChunkX() << 4) << 12 | position.getZ()
- (position.getChunkZ() << 4) << 8 | position.getY();
this.modernChunkPosCrammed = position.getX()
- (position.getChunkX() << 4) << 8 | position.getZ()
- (position.getChunkZ() << 4) << 4 | position.getY()
- ((position.getY() >> 4) << 4);
final int x = position.getX() - (position.getChunkX() << 4);
final int y = position.getY();
final int z = position.getZ() - (position.getChunkZ() << 4);
this.legacyBlockState = x << 12 | z << 8 | y;
this.blockState = x << 8 | z << 4 | y - ((y >> 4) << 4);
}
}
@@ -0,0 +1,83 @@
/*
* Copyright (C) 2023 Sonar Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.common.fallback.protocol.map;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion;
import java.util.function.Function;
@SuppressWarnings("unused")
@RequiredArgsConstructor
public enum ItemMapType {
FILLED_MAP(protocolVersion -> {
// Useful resources:
// - https://github.com/PrismarineJS/minecraft-data/blob/master/data/pc/
// - https://pokechu22.github.io/Burger/1.20.4.html
// - https://github.com/ViaVersion/Mappings/tree/main/mappings
switch (protocolVersion) {
default:
// 1.7-1.12.2
return 358;
case MINECRAFT_1_13:
case MINECRAFT_1_13_1:
return 608;
case MINECRAFT_1_13_2:
return 613;
case MINECRAFT_1_14:
case MINECRAFT_1_14_1:
case MINECRAFT_1_14_2:
case MINECRAFT_1_14_3:
case MINECRAFT_1_14_4:
case MINECRAFT_1_15:
case MINECRAFT_1_15_1:
case MINECRAFT_1_15_2:
return 671;
case MINECRAFT_1_16:
case MINECRAFT_1_16_1:
case MINECRAFT_1_16_2:
case MINECRAFT_1_16_3:
case MINECRAFT_1_16_4:
return 733;
case MINECRAFT_1_17:
case MINECRAFT_1_17_1:
case MINECRAFT_1_18:
case MINECRAFT_1_18_2:
return 847;
case MINECRAFT_1_19:
case MINECRAFT_1_19_1:
return 886;
case MINECRAFT_1_19_3:
return 914;
case MINECRAFT_1_19_4:
return 937;
case MINECRAFT_1_20:
case MINECRAFT_1_20_2:
return 941;
case MINECRAFT_1_20_3:
return 979;
}
});
private final Function<ProtocolVersion, Integer> function;
public int getId(final @NotNull ProtocolVersion protocolVersion) {
return function.apply(protocolVersion);
}
}
@@ -15,12 +15,16 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.bungee.fallback;
package xyz.jonesdev.sonar.common.fallback.protocol.map;
import io.netty.handler.codec.DecoderException;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
final class ConditionFailedException extends DecoderException {
public ConditionFailedException(final String message) {
super(message);
}
@Getter
@RequiredArgsConstructor
public final class MapInfo {
private final String answer;
private final int columns, rows;
private final int x, y;
private final byte[] buffer;
}
@@ -0,0 +1,154 @@
/*
* Copyright (C) 2023 Sonar Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.common.fallback.protocol.map;
import lombok.experimental.UtilityClass;
import xyz.jonesdev.sonar.api.Sonar;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
@UtilityClass
public class MapInfoPreparer {
private final Random RANDOM = new Random();
private final String[] FONT_TYPES = new String[]{
Font.DIALOG_INPUT,
Font.DIALOG,
Font.SANS_SERIF,
Font.SERIF
};
private final int[] FONT_STYLES = new int[]{
Font.PLAIN,
Font.BOLD,
Font.ITALIC,
Font.ITALIC | Font.BOLD
};
private final int[][] COLOR_PALETTE = new int[][]{
new int[]{ // Blue
48,
49,
50,
51
},
new int[]{ // Black
27,
45,
46,
47,
},
new int[]{ // Green
4,
28,
29,
30,
},
new int[]{ // Red
16,
17,
18,
19
}
};
private PreparedMapInfo[] cached;
public void prepare() {
cached = new PreparedMapInfo[Sonar.get().getConfig().getVerification().getMap().getPrecomputeAmount()];
final String dictionary = Sonar.get().getConfig().getVerification().getMap().getDictionary();
for (int i = 0; i < cached.length; i++) {
// Create image
final BufferedImage image = new BufferedImage(PreparedMapInfo.DIMENSIONS, PreparedMapInfo.DIMENSIONS,
BufferedImage.TYPE_3BYTE_BGR);
final Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.WHITE);
// Create random font
final String fontType = FONT_TYPES[RANDOM.nextInt(FONT_TYPES.length)];
final int fontStyle = FONT_STYLES[RANDOM.nextInt(FONT_STYLES.length)];
final int fontSize = 30
+ (Sonar.get().getConfig().getVerification().getMap().isRandomizeFontSize() ? RANDOM.nextInt(11) : 5);
@SuppressWarnings("all") final Font answerFont = new Font(fontType, fontStyle, fontSize);
graphics.setFont(answerFont);
// Build answer to the captcha
final StringBuilder answerBuilder = new StringBuilder();
for (int _i = 0; _i < 4; _i++) {
answerBuilder.append(dictionary.charAt(RANDOM.nextInt(dictionary.length())));
}
final String answer = answerBuilder.toString();
// Calculate text position
final int stringWidth = graphics.getFontMetrics().stringWidth(answer);
int _x = image.getWidth() / 2 - stringWidth / 2;
int _y = image.getHeight() / 2 + fontSize / 3;
int randomOffsetX = 0, randomOffsetY = 3;
final int firstPixelX = _x, firstPixelY = _y;
// Draw each character one by one
final FontMetrics fontMetrics = graphics.getFontMetrics();
for (final char c : answer.toCharArray()) {
if (Sonar.get().getConfig().getVerification().getMap().isRandomizePositions()) {
_x += randomOffsetX;
_y += randomOffsetY;
randomOffsetX = randomOffsetX < 0 ? 1 + RANDOM.nextInt(2) : -1 - RANDOM.nextInt(2);
randomOffsetY = randomOffsetY < 0 ? 1 + RANDOM.nextInt(4) : -1 - RANDOM.nextInt(4);
}
final String character = String.valueOf(c);
graphics.drawString(character, _x, _y);
_x += fontMetrics.stringWidth(character);
}
// Select random color palette
final int[] colorPalette = COLOR_PALETTE[i % COLOR_PALETTE.length];
// Calculate y and height
final int pixelY = firstPixelY - fontSize;
final int height = firstPixelY + fontSize / 3;
// Store image in buffer
final byte[] buffer = new byte[PreparedMapInfo.SCALE];
for (int x = firstPixelX; x < _x; x++) {
for (int y = pixelY; y < height; y++) {
final int index = y * image.getWidth() + x;
final int pixel = image.getRGB(x, y);
// If the pixel has no color set, set it to white/light gray (if enabled in the config)
if (pixel == -16777216) {
if (Sonar.get().getConfig().getVerification().getMap().isDrawBackgroundNoise()) {
buffer[index] = (byte) (RANDOM.nextInt(100) < 70 ? 14 : 26);
}
continue;
}
// Set color of pixel to random color from the palette
buffer[index] = (byte) colorPalette[RANDOM.nextInt(colorPalette.length)];
}
}
// Cache buffer to map
cached[i] = new PreparedMapInfo(answer, image.getWidth(), image.getHeight(), buffer);
}
}
public PreparedMapInfo getRandomCaptcha() {
return cached[RANDOM.nextInt(cached.length)];
}
}
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2023 Sonar Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.common.fallback.protocol.map;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.fallback.FallbackUser;
import xyz.jonesdev.sonar.common.fallback.protocol.packets.play.MapData;
import static xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion.MINECRAFT_1_8;
@Getter
public final class PreparedMapInfo {
public static final int DIMENSIONS = (int) Math.pow(2, 7);
public static final int SCALE = DIMENSIONS * DIMENSIONS;
private final MapInfo info;
private final MapData[] legacy;
private final MapData modern;
public PreparedMapInfo(final String answer,
final int columns, final int rows,
final byte @NotNull [] buffer) {
this.info = new MapInfo(answer, columns, rows, 0, 0, buffer);
// Prepare 1.7 map data using a grid
final byte[][] grid = new byte[DIMENSIONS][DIMENSIONS];
for (int i = 0; i < buffer.length; i++) {
final byte buf = buffer[i];
grid[i & Byte.MAX_VALUE][i >> 7] = buf;
}
this.legacy = new MapData[grid.length];
for (int i = 0; i < grid.length; i++) {
this.legacy[i] = new MapData(new MapInfo(answer, DIMENSIONS, DIMENSIONS, i, 0, grid[i]));
}
// Prepare 1.8+ map data
this.modern = new MapData(info);
}
public void write(final @NotNull FallbackUser<?, ?> user) {
if (user.getProtocolVersion().compareTo(MINECRAFT_1_8) < 0) {
for (final MapData data : legacy) {
user.delayedWrite(data);
}
} else {
user.delayedWrite(modern);
}
}
}
@@ -18,33 +18,26 @@
package xyz.jonesdev.sonar.common.fallback.protocol.packets.config;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.handler.codec.EncoderException;
import lombok.Getter;
import lombok.ToString;
import net.kyori.adventure.nbt.BinaryTagTypes;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion;
import xyz.jonesdev.sonar.common.fallback.protocol.FallbackPacket;
import xyz.jonesdev.sonar.common.fallback.protocol.dimension.DimensionRegistry;
import java.io.IOException;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.writeNamelessCompoundTag;
@Getter
@ToString
public final class RegistrySync implements FallbackPacket {
public final class RegistryData implements FallbackPacket {
@Override
public void encode(final @NotNull ByteBuf byteBuf, final ProtocolVersion protocolVersion) {
try (final ByteBufOutputStream stream = new ByteBufOutputStream(byteBuf)) {
stream.writeByte(10); // CompoundTag ID
BinaryTagTypes.COMPOUND.write(DimensionRegistry.CODEC_1_20, stream);
} catch (IOException exception) {
throw new EncoderException("Cannot write NBT CompoundTag");
}
writeNamelessCompoundTag(byteBuf, DimensionRegistry.CODEC_1_20);
}
@Override
public void decode(final ByteBuf byteBuf, final ProtocolVersion protocolVersion) {
throw new UnsupportedOperationException();
}
}
@@ -31,7 +31,7 @@ import xyz.jonesdev.sonar.common.fallback.protocol.FallbackPacket;
@NoArgsConstructor
@AllArgsConstructor
public class Abilities implements FallbackPacket {
private byte encodedFlags;
private int encodedFlags;
private float flySpeed, walkSpeed;
@Override
@@ -17,48 +17,88 @@
package xyz.jonesdev.sonar.common.fallback.protocol.packets.play;
import com.google.gson.JsonParser;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.CorruptedFrameException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import net.kyori.adventure.nbt.BinaryTag;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.json.JSONComponentSerializer;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion;
import xyz.jonesdev.sonar.common.fallback.protocol.FallbackPacket;
import java.time.Instant;
import java.util.UUID;
import static xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion.*;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.writeString;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.writeUUID;
import static xyz.jonesdev.sonar.common.utility.nbt.NBTMessageUtil.fromJson;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.*;
import static xyz.jonesdev.sonar.common.utility.protocol.VarIntUtil.readVarInt;
import static xyz.jonesdev.sonar.common.utility.protocol.VarIntUtil.writeVarInt;
@Getter
@ToString
@Data
@NoArgsConstructor
@AllArgsConstructor
public final class Chat implements FallbackPacket {
private static final UUID PLACEHOLDER_UUID = new UUID(0L, 0L);
private static final int DIV_FLOOR = -Math.floorDiv(-20, 8);
public static final byte CHAT_TYPE = (byte) 0;
public static final byte SYSTEM_TYPE = (byte) 1;
public static final byte GAME_INFO_TYPE = (byte) 2;
private Component component;
private byte position;
private String message;
private byte type;
private boolean signedPreview;
private boolean unsigned = false;
private Instant timestamp;
private Instant expiry;
private long salt;
private boolean signed;
private byte[] signature;
// 1.20.3
private BinaryTag nbtMessage;
// Clientbound LegacyChat
public Chat(final Component component) {
this(component, SYSTEM_TYPE);
}
// Clientbound LegacyChat
public Chat(final Component component, final byte type) {
this(component, JSONComponentSerializer.json().serialize(component), type);
}
public Chat(final Component component, final String message, final byte type) {
this(component, message, type,
false, false, null, null,
0L, false, null, fromJson(new JsonParser().parse(message)));
}
@Override
public void encode(final ByteBuf byteBuf, final @NotNull ProtocolVersion protocolVersion) {
final String serialized = JSONComponentSerializer.json().serialize(component);
writeString(byteBuf, serialized);
// Message type
if (protocolVersion.compareTo(MINECRAFT_1_19_1) >= 0) {
byteBuf.writeBoolean(position == 2);
} else if (protocolVersion.compareTo(MINECRAFT_1_19) >= 0) {
writeVarInt(byteBuf, position);
// Serialized message
if (protocolVersion.compareTo(MINECRAFT_1_20_3) >= 0) {
writeNamelessCompoundTag(byteBuf, nbtMessage);
} else {
byteBuf.writeByte(this.position);
writeString(byteBuf, message);
}
// UUID
// Type
if (protocolVersion.compareTo(MINECRAFT_1_19_1) >= 0) {
byteBuf.writeBoolean(type == GAME_INFO_TYPE);
} else if (protocolVersion.compareTo(MINECRAFT_1_19) >= 0) {
writeVarInt(byteBuf, type);
} else if (protocolVersion.compareTo(MINECRAFT_1_8) >= 0) {
byteBuf.writeByte(type);
}
// Sender
if (protocolVersion.compareTo(MINECRAFT_1_16) >= 0
&& protocolVersion.compareTo(MINECRAFT_1_19) < 0) {
writeUUID(byteBuf, PLACEHOLDER_UUID);
@@ -66,7 +106,62 @@ public final class Chat implements FallbackPacket {
}
@Override
public void decode(final ByteBuf byteBuf, final ProtocolVersion protocolVersion) {
throw new UnsupportedOperationException();
public void decode(final ByteBuf byteBuf, final @NotNull ProtocolVersion protocolVersion) {
message = readString(byteBuf, 256);
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_19) >= 0) {
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_19_1) <= 0) {
final long expiresAt = byteBuf.readLong();
final long saltLong = byteBuf.readLong();
final byte[] signatureBytes = readByteArray(byteBuf);
if (saltLong != 0L && signatureBytes.length > 0) {
signature = signatureBytes;
expiry = Instant.ofEpochMilli(expiresAt);
} else if ((protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_19_1) >= 0
|| saltLong == 0L) && signatureBytes.length == 0) {
unsigned = true;
} else {
throw new CorruptedFrameException("Invalid signature");
}
signedPreview = byteBuf.readBoolean();
if (signedPreview && unsigned) {
throw new CorruptedFrameException("Signature missing");
}
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_19_1) >= 0) {
final int size = readVarInt(byteBuf);
if (size < 0 || size > 5) {
throw new CorruptedFrameException("Invalid previous messages");
}
for (int i = 0; i < size; i++) {
readUUID(byteBuf);
readByteArray(byteBuf);
}
if (byteBuf.readBoolean()) {
readUUID(byteBuf);
readByteArray(byteBuf);
}
}
} else {
timestamp = Instant.ofEpochMilli(byteBuf.readLong());
salt = byteBuf.readLong();
signed = byteBuf.readBoolean();
if (signed) {
byte[] sign = new byte[256];
byteBuf.readBytes(sign);
signature = sign;
} else {
signature = new byte[0];
}
readVarInt(byteBuf);
byte[] bytes = new byte[DIV_FLOOR];
byteBuf.readBytes(bytes);
}
}
}
}
@@ -0,0 +1,62 @@
/*
* Copyright (C) 2023 Sonar Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.common.fallback.protocol.packets.play;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion;
import xyz.jonesdev.sonar.common.fallback.protocol.FallbackPacket;
import static xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion.MINECRAFT_1_14;
import static xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion.MINECRAFT_1_17;
@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public final class DefaultSpawnPosition implements FallbackPacket {
private int x, y, z;
@Override
public void encode(final ByteBuf byteBuf, final @NotNull ProtocolVersion protocolVersion) {
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_8) < 0) {
byteBuf.writeInt(x);
byteBuf.writeInt(y);
byteBuf.writeInt(z);
} else {
final long encoded = protocolVersion.compareTo(MINECRAFT_1_14) < 0
? ((x & 0x3FFFFFFL) << 38) | ((y & 0xFFFL) << 26) | (z & 0x3FFFFFFL)
: ((x & 0x3FFFFFFL) << 38) | ((y & 0x3FFFFFFL) << 12) | (z & 0xFFFL);
byteBuf.writeLong(encoded);
if (protocolVersion.compareTo(MINECRAFT_1_17) >= 0) {
byteBuf.writeFloat(0f);
}
}
}
@Override
public void decode(final ByteBuf byteBuf, final ProtocolVersion protocolVersion) {
throw new UnsupportedOperationException();
}
}
@@ -17,11 +17,13 @@
package xyz.jonesdev.sonar.common.fallback.protocol.packets.play;
import com.google.gson.JsonParser;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import net.kyori.adventure.nbt.BinaryTag;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.serializer.json.JSONComponentSerializer;
import org.jetbrains.annotations.NotNull;
@@ -29,8 +31,8 @@ import org.jetbrains.annotations.Nullable;
import xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion;
import xyz.jonesdev.sonar.common.fallback.protocol.FallbackPacket;
import java.util.Objects;
import static xyz.jonesdev.sonar.common.utility.nbt.NBTMessageUtil.fromJson;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.writeNamelessCompoundTag;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.writeString;
@Getter
@@ -39,10 +41,15 @@ import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.writeStrin
@AllArgsConstructor
public final class Disconnect implements FallbackPacket {
private @Nullable String reason;
private BinaryTag binaryTag;
@Override
public void encode(final ByteBuf byteBuf, final ProtocolVersion protocolVersion) {
writeString(byteBuf, Objects.requireNonNull(reason));
public void encode(final ByteBuf byteBuf, final @NotNull ProtocolVersion protocolVersion) {
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_20_3) >= 0) {
writeNamelessCompoundTag(byteBuf, binaryTag);
} else {
writeString(byteBuf, reason);
}
}
@Override
@@ -51,6 +58,8 @@ public final class Disconnect implements FallbackPacket {
}
public static @NotNull Disconnect create(final Component component) {
return new Disconnect(JSONComponentSerializer.json().serialize(component));
final String serialized = JSONComponentSerializer.json().serialize(component);
final BinaryTag binaryTag = fromJson(new JsonParser().parse(serialized));
return new Disconnect(serialized, binaryTag);
}
}
@@ -29,8 +29,7 @@ import xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion;
import xyz.jonesdev.sonar.common.fallback.protocol.FallbackPacket;
import static xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion.*;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.writeArray;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.writeCompoundTag;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.*;
import static xyz.jonesdev.sonar.common.utility.protocol.VarIntUtil.writeVarInt;
@Getter
@@ -92,7 +91,11 @@ public final class EmptyChunkData implements FallbackPacket {
}
if (protocolVersion.compareTo(MINECRAFT_1_14) >= 0) {
writeCompoundTag(byteBuf, protocolVersion.compareTo(MINECRAFT_1_18) < 0 ? LEGACY_TAG : MODERN_TAG);
if (protocolVersion.compareTo(MINECRAFT_1_20_2) >= 0) {
writeNamelessCompoundTag(byteBuf, MODERN_TAG);
} else {
writeCompoundTag(byteBuf, protocolVersion.compareTo(MINECRAFT_1_18) < 0 ? LEGACY_TAG : MODERN_TAG);
}
if (protocolVersion.compareTo(MINECRAFT_1_15) >= 0 && protocolVersion.compareTo(MINECRAFT_1_18) < 0) {
if (protocolVersion.compareTo(MINECRAFT_1_16_2) >= 0) {
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2023 Sonar Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.common.fallback.protocol.packets.play;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion;
import xyz.jonesdev.sonar.common.fallback.protocol.FallbackPacket;
@Data
@NoArgsConstructor
@AllArgsConstructor
public final class GameEvent implements FallbackPacket {
private int type;
private float value;
@Override
public void encode(final @NotNull ByteBuf byteBuf, final ProtocolVersion protocolVersion) {
byteBuf.writeByte(type);
byteBuf.writeFloat(value);
}
@Override
public void decode(final ByteBuf byteBuf, final ProtocolVersion protocolVersion) {
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,82 @@
/*
* Copyright (C) 2023 Sonar Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.common.fallback.protocol.packets.play;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion;
import xyz.jonesdev.sonar.common.fallback.protocol.FallbackPacket;
import xyz.jonesdev.sonar.common.fallback.protocol.map.MapInfo;
import static xyz.jonesdev.sonar.common.utility.protocol.VarIntUtil.writeVarInt;
@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public final class MapData implements FallbackPacket {
private MapInfo mapInfo;
@Override
public void encode(final @NotNull ByteBuf byteBuf, final @NotNull ProtocolVersion protocolVersion) {
writeVarInt(byteBuf, 0);
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_8) < 0) {
byteBuf.writeShort(mapInfo.getBuffer().length + 3);
byteBuf.writeByte(0); // scaling
byteBuf.writeByte(mapInfo.getX());
byteBuf.writeByte(mapInfo.getY());
byteBuf.writeBytes(mapInfo.getBuffer());
} else {
byteBuf.writeByte(0); // scaling
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_9) >= 0
&& protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_17) < 0) {
byteBuf.writeBoolean(false);
}
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_14) >= 0) {
byteBuf.writeBoolean(false);
}
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_17) >= 0) {
byteBuf.writeBoolean(false);
} else {
writeVarInt(byteBuf, 0);
}
byteBuf.writeByte(mapInfo.getColumns());
byteBuf.writeByte(mapInfo.getRows());
byteBuf.writeByte(mapInfo.getX());
byteBuf.writeByte(mapInfo.getY());
writeVarInt(byteBuf, mapInfo.getBuffer().length);
byteBuf.writeBytes(mapInfo.getBuffer());
}
}
@Override
public void decode(final ByteBuf byteBuf, final ProtocolVersion protocolVersion) {
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,95 @@
/*
* Copyright (C) 2023 Sonar Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.common.fallback.protocol.packets.play;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import net.kyori.adventure.nbt.CompoundBinaryTag;
import net.kyori.adventure.nbt.IntBinaryTag;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion;
import xyz.jonesdev.sonar.common.fallback.protocol.FallbackPacket;
import static xyz.jonesdev.sonar.api.fallback.protocol.ProtocolVersion.*;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.writeCompoundTag;
import static xyz.jonesdev.sonar.common.utility.protocol.ProtocolUtil.writeNamelessCompoundTag;
import static xyz.jonesdev.sonar.common.utility.protocol.VarIntUtil.writeVarInt;
@Getter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public final class SetSlot implements FallbackPacket {
private int windowId;
private int slot;
private int count;
private int data;
private int itemId;
private CompoundBinaryTag compoundBinaryTag;
public static final CompoundBinaryTag MAP_NBT = CompoundBinaryTag.builder()
.put("map", IntBinaryTag.intBinaryTag(0)) // map type
.build();
@Override
public void decode(final @NotNull ByteBuf byteBuf, final ProtocolVersion protocolVersion) {
throw new UnsupportedOperationException();
}
@Override
public void encode(final @NotNull ByteBuf byteBuf, final @NotNull ProtocolVersion protocolVersion) {
byteBuf.writeByte(windowId);
if (protocolVersion.compareTo(MINECRAFT_1_17_1) >= 0) {
writeVarInt(byteBuf, 0);
}
byteBuf.writeShort(slot);
if (protocolVersion.compareTo(MINECRAFT_1_13_2) >= 0) {
byteBuf.writeBoolean(true);
}
if (protocolVersion.compareTo(MINECRAFT_1_13_2) < 0) {
byteBuf.writeShort(itemId);
} else {
writeVarInt(byteBuf, itemId);
}
byteBuf.writeByte(count);
if (protocolVersion.compareTo(MINECRAFT_1_13) < 0) {
byteBuf.writeShort(data);
}
if (protocolVersion.compareTo(MINECRAFT_1_17) < 0) {
if (protocolVersion.compareTo(ProtocolVersion.MINECRAFT_1_8) < 0) {
byteBuf.writeShort(-1);
} else {
byteBuf.writeByte(0);
}
} else {
if (protocolVersion.compareTo(MINECRAFT_1_20_2) >= 0) {
writeNamelessCompoundTag(byteBuf, compoundBinaryTag);
} else {
writeCompoundTag(byteBuf, compoundBinaryTag);
}
}
}
}
@@ -53,12 +53,12 @@ public final class UpdateSectionBlocks implements FallbackPacket {
}
for (final ChangedBlock block : changedBlocks) {
byteBuf.writeShort(block.getLegacyChunkPosCrammed());
final int id = block.getType().getId(protocolVersion);
byteBuf.writeShort(block.getLegacyBlockState());
final int blockId = block.getType().getId(protocolVersion);
if (protocolVersion.compareTo(MINECRAFT_1_13) >= 0) {
writeVarInt(byteBuf, id);
writeVarInt(byteBuf, blockId);
} else {
final int shiftedBlockId = id << 4;
final int shiftedBlockId = blockId << 4;
if (protocolVersion.compareTo(MINECRAFT_1_8) < 0) {
byteBuf.writeShort(shiftedBlockId);
} else {
@@ -67,8 +67,10 @@ public final class UpdateSectionBlocks implements FallbackPacket {
}
}
} else {
// We only need one Y position
final int sectionY = changedBlocks[0].getPosition().getY() >> 4;
// https://wiki.vg/Protocol#Update_Section_Blocks
byteBuf.writeLong(((sectionX & 0x3FFFFFL) << 42) | (sectionY & 0xFFFFF) | ((sectionZ & 0x3FFFFFL) << 20));
// 1.20+ don't have light update suppression
@@ -79,8 +81,9 @@ public final class UpdateSectionBlocks implements FallbackPacket {
writeVarInt(byteBuf, changedBlocks.length);
for (final ChangedBlock block : changedBlocks) {
// https://wiki.vg/Protocol#Update_Section_Blocks
final int shiftedBlockId = block.getType().getId(protocolVersion) << 12;
final long positionIdValue = shiftedBlockId | block.getModernChunkPosCrammed();
final long positionIdValue = shiftedBlockId | block.getBlockState();
writeVarLong(byteBuf, positionIdValue);
}
}
@@ -26,7 +26,6 @@ public final class SubcommandRegistryHolder implements SubcommandRegistry {
new BlacklistCommand(),
new VerifiedCommand(),
new StatisticsCommand(),
new LockdownCommand(),
new VerboseCommand(),
new ReloadCommand(),
new DumpCommand()
@@ -54,7 +54,7 @@ public final class BlacklistCommand extends Subcommand {
if (inetAddress == null) return;
// Make sure the IP is not blacklisted already
if (SONAR.getFallback().getBlacklisted().has(inetAddress.toString())) {
if (SONAR.getFallback().getBlacklisted().has(inetAddress)) {
invocation.getSender().sendMessage(SONAR.getConfig().getCommands().getBlacklistDuplicate());
return;
}
@@ -66,7 +66,7 @@ public final class BlacklistCommand extends Subcommand {
}
// Blacklist the given IP address
SONAR.getFallback().getBlacklisted().put(inetAddress.toString());
SONAR.getFallback().getBlacklisted().put(inetAddress);
invocation.getSender().sendMessage(SONAR.getConfig().getCommands().getBlacklistAdd()
.replace("%ip%", rawInetAddress));
break;
@@ -85,13 +85,13 @@ public final class BlacklistCommand extends Subcommand {
if (inetAddress == null) return;
// Make sure the IP is blacklisted
if (!SONAR.getFallback().getBlacklisted().has(inetAddress.toString())) {
if (!SONAR.getFallback().getBlacklisted().has(inetAddress)) {
invocation.getSender().sendMessage(SONAR.getConfig().getCommands().getBlacklistNotFound());
return;
}
// Invalidate the cache entry of the blacklisted IP address
SONAR.getFallback().getBlacklisted().invalidate(inetAddress.toString());
SONAR.getFallback().getBlacklisted().invalidate(inetAddress);
invocation.getSender().sendMessage(SONAR.getConfig().getCommands().getBlacklistRemove()
.replace("%ip%", rawInetAddress));
break;
@@ -1,41 +0,0 @@
/*
* Copyright (C) 2023 Sonar Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.common.subcommand.impl;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.command.CommandInvocation;
import xyz.jonesdev.sonar.api.command.subcommand.Subcommand;
import xyz.jonesdev.sonar.api.command.subcommand.SubcommandInfo;
@SubcommandInfo(
name = "lockdown",
description = "Prevent all players from joining"
)
public final class LockdownCommand extends Subcommand {
@Override
protected void execute(final @NotNull CommandInvocation invocation) {
final boolean newState = !SONAR.getConfig().getLockdown().isEnabled();
SONAR.getConfig().getLockdown().setEnabled(newState);
SONAR.getConfig().getGeneralConfig().set("lockdown.enabled", newState);
SONAR.getConfig().getGeneralConfig().save();
invocation.getSender().sendMessage(newState
? SONAR.getConfig().getLockdown().getActivated() : SONAR.getConfig().getLockdown().getDeactivated());
}
}
@@ -1,3 +1,20 @@
/*
* Copyright (C) 2023 Sonar Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.common.update;
import com.google.gson.JsonObject;
@@ -0,0 +1,115 @@
/*
* Copyright (C) 2023 Sonar Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package xyz.jonesdev.sonar.common.utility.nbt;
import com.google.gson.*;
import lombok.experimental.UtilityClass;
import net.kyori.adventure.nbt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
// Taken from
// https://github.com/Nan1t/NanoLimbo/pull/79/files#diff-0e355ffd4eb0e15e2c2e628227debc9b6ccefeb167d7b9619311cdc7db2645ec
@UtilityClass
public class NBTMessageUtil {
public static BinaryTag fromJson(final JsonElement json) {
if (json instanceof JsonPrimitive) {
JsonPrimitive jsonPrimitive = (JsonPrimitive) json;
if (jsonPrimitive.isNumber()) {
Number number = json.getAsNumber();
if (number instanceof Byte) {
return ByteBinaryTag.byteBinaryTag((Byte) number);
} else if (number instanceof Short) {
return ShortBinaryTag.shortBinaryTag((Short) number);
} else if (number instanceof Integer) {
return IntBinaryTag.intBinaryTag((Integer) number);
} else if (number instanceof Long) {
return LongBinaryTag.longBinaryTag((Long) number);
} else if (number instanceof Float) {
return FloatBinaryTag.floatBinaryTag((Float) number);
} else if (number instanceof Double) {
return DoubleBinaryTag.doubleBinaryTag((Double) number);
}
} else if (jsonPrimitive.isString()) {
return StringBinaryTag.stringBinaryTag(jsonPrimitive.getAsString());
} else if (jsonPrimitive.isBoolean()) {
return ByteBinaryTag.byteBinaryTag(jsonPrimitive.getAsBoolean() ? (byte) 1 : (byte) 0);
} else {
throw new IllegalArgumentException("Unknown JSON primitive: " + jsonPrimitive);
}
} else if (json instanceof JsonObject) {
final CompoundBinaryTag.Builder builder = CompoundBinaryTag.builder();
for (Map.Entry<String, JsonElement> property : ((JsonObject) json).entrySet()) {
builder.put(property.getKey(), fromJson(property.getValue()));
}
return builder.build();
} else if (json instanceof JsonArray) {
final JsonArray jsonArray = ((JsonArray) json);
if (jsonArray.size() == 0) {
return ListBinaryTag.listBinaryTag(EndBinaryTag.endBinaryTag().type(), Collections.emptyList());
}
final BinaryTagType<?> tagByteType = ByteBinaryTag.ZERO.type();
final BinaryTagType<?> tagIntType = IntBinaryTag.intBinaryTag(0).type();
final BinaryTagType<?> tagLongType = LongBinaryTag.longBinaryTag(0).type();
final BinaryTag listTag;
final BinaryTagType<?> listType = fromJson(jsonArray.get(0)).type();
if (listType.equals(tagByteType)) {
byte[] bytes = new byte[jsonArray.size()];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (Byte) jsonArray.get(i).getAsNumber();
}
listTag = ByteArrayBinaryTag.byteArrayBinaryTag(bytes);
} else if (listType.equals(tagIntType)) {
int[] ints = new int[jsonArray.size()];
for (int i = 0; i < ints.length; i++) {
ints[i] = (Integer) jsonArray.get(i).getAsNumber();
}
listTag = IntArrayBinaryTag.intArrayBinaryTag(ints);
} else if (listType.equals(tagLongType)) {
long[] longs = new long[jsonArray.size()];
for (int i = 0; i < longs.length; i++) {
longs[i] = (Long) jsonArray.get(i).getAsNumber();
}
listTag = LongArrayBinaryTag.longArrayBinaryTag(longs);
} else {
final List<BinaryTag> tagItems = new ArrayList<>(jsonArray.size());
for (final JsonElement jsonEl : jsonArray) {
final BinaryTag subTag = fromJson(jsonEl);
if (subTag.type() != listType) {
throw new IllegalArgumentException("Cannot convert mixed JsonArray to Tag");
}
tagItems.add(subTag);
}
listTag = ListBinaryTag.listBinaryTag(listType, tagItems);
}
return listTag;
} else if (json instanceof JsonNull) {
return EndBinaryTag.endBinaryTag();
}
throw new IllegalArgumentException("Unknown JSON element: " + json);
}
}
@@ -24,8 +24,7 @@ import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.EncoderException;
import lombok.experimental.UtilityClass;
import net.kyori.adventure.nbt.BinaryTagIO;
import net.kyori.adventure.nbt.CompoundBinaryTag;
import net.kyori.adventure.nbt.*;
import org.jetbrains.annotations.NotNull;
import java.io.DataOutput;
@@ -34,6 +33,8 @@ import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.regex.Pattern;
import static xyz.jonesdev.sonar.common.utility.protocol.VarIntUtil.readVarInt;
// Taken from
// https://github.com/PaperMC/Velocity/blob/dev/3.0.0/proxy/src/main/java/com/velocitypowered/proxy/protocol/ProtocolUtils.java
@UtilityClass
@@ -48,6 +49,24 @@ public class ProtocolUtil {
private static final String UNREGISTER_CHANNEL = "minecraft:unregister";
private static final Pattern INVALID_IDENTIFIER_REGEX = Pattern.compile("[^a-z0-9\\-_]*");
public static @NotNull UUID readUUID(final @NotNull ByteBuf byteBuf) {
return new UUID(byteBuf.readLong(), byteBuf.readLong());
}
public static byte @NotNull [] readByteArray(final ByteBuf byteBuf) {
return readByteArray(byteBuf, Short.MAX_VALUE);
}
public static byte @NotNull [] readByteArray(final ByteBuf byteBuf, final int cap) {
int length = readVarInt(byteBuf);
checkFrame(length >= 0, "Got a negative-length array");
checkFrame(length <= cap, "Bad array size");
checkFrame(byteBuf.isReadable(length), "Trying to read an array that is too long");
byte[] array = new byte[length];
byteBuf.readBytes(array);
return array;
}
public static @NotNull String readBrandMessage(final @NotNull ByteBuf content) throws DecoderException {
final ByteBuf slice = content.slice();
try {
@@ -113,7 +132,46 @@ public class ProtocolUtil {
public static void writeCompoundTag(final ByteBuf byteBuf, final CompoundBinaryTag compoundTag) {
try {
BinaryTagIO.writer().write(compoundTag, (DataOutput) new ByteBufOutputStream(byteBuf));
} catch (IOException e) {
} catch (IOException exception) {
throw new EncoderException("Unable to encode NBT CompoundTag");
}
}
// Taken from
// https://github.com/Nan1t/NanoLimbo/pull/79/files#diff-4aa8208044741102c6326c7e85086e6fa8fcc7c064f7df6fd0411baf5f2b4504
public static void writeNamelessCompoundTag(final @NotNull ByteBuf byteBuf, final @NotNull BinaryTag binaryTag) {
try (final ByteBufOutputStream output = new ByteBufOutputStream(byteBuf)) {
// TODO: Find a way to improve this...
output.writeByte(binaryTag.type().id());
if (binaryTag instanceof CompoundBinaryTag) {
CompoundBinaryTag tag = (CompoundBinaryTag) binaryTag;
tag.type().write(tag, output);
} else if (binaryTag instanceof ByteBinaryTag) {
ByteBinaryTag tag = (ByteBinaryTag) binaryTag;
tag.type().write(tag, output);
} else if (binaryTag instanceof ShortBinaryTag) {
ShortBinaryTag tag = (ShortBinaryTag) binaryTag;
tag.type().write(tag, output);
} else if (binaryTag instanceof IntBinaryTag) {
IntBinaryTag tag = (IntBinaryTag) binaryTag;
tag.type().write(tag, output);
} else if (binaryTag instanceof LongBinaryTag) {
LongBinaryTag tag = (LongBinaryTag) binaryTag;
tag.type().write(tag, output);
} else if (binaryTag instanceof DoubleBinaryTag) {
DoubleBinaryTag tag = (DoubleBinaryTag) binaryTag;
tag.type().write(tag, output);
} else if (binaryTag instanceof StringBinaryTag) {
StringBinaryTag tag = (StringBinaryTag) binaryTag;
tag.type().write(tag, output);
} else if (binaryTag instanceof ListBinaryTag) {
ListBinaryTag tag = (ListBinaryTag) binaryTag;
tag.type().write(tag, output);
} else if (binaryTag instanceof EndBinaryTag) {
EndBinaryTag tag = (EndBinaryTag) binaryTag;
tag.type().write(tag, output);
}
} catch (IOException exception) {
throw new EncoderException("Unable to encode NBT CompoundTag");
}
}
@@ -20,7 +20,6 @@ package xyz.jonesdev.sonar.velocity.fallback;
import com.velocitypowered.api.event.PostOrder;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.LoginEvent;
import com.velocitypowered.api.event.connection.PostLoginEvent;
import com.velocitypowered.api.event.connection.PreLoginEvent;
import com.velocitypowered.api.proxy.crypto.IdentifiedKey;
import com.velocitypowered.api.util.GameProfile;
@@ -36,8 +35,6 @@ import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import lombok.RequiredArgsConstructor;
import lombok.val;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.jetbrains.annotations.NotNull;
import xyz.jonesdev.sonar.api.ReflectiveOperationException;
import xyz.jonesdev.sonar.api.Sonar;
@@ -155,7 +152,8 @@ public final class FallbackListener {
val activeSessionHandler = (MinecraftSessionHandler) SESSION_HANDLER_FIELD.get(mcConnection);
// Check the blacklist here since we cannot let the player "ghost join"
if (fallback.getBlacklisted().has(inetAddress.toString())) {
if (fallback.getBlacklisted().has(inetAddress)) {
// Mark the connection as dead to avoid unnecessary console logs
markConnectionAsDead(activeSessionHandler);
initialConnection.getConnection().closeWith(Disconnect.create(
Sonar.get().getConfig().getVerification().getBlacklisted(),
@@ -167,17 +165,32 @@ public final class FallbackListener {
// Don't continue the verification process if the verification is disabled
if (!Sonar.get().getFallback().shouldVerifyNewPlayers()) return;
// Completely skip Geyser connections
if (isGeyserConnection(channel)) {
fallback.getLogger().info("Skipping Geyser player: {}{}",
event.getUsername(), Sonar.get().getConfig().formatAddress(inetAddress));
return;
}
// Check if the protocol ID of the player is not allowed to enter the server
final int protocolId = inboundConnection.getProtocolVersion().getProtocol();
if (Sonar.get().getConfig().getVerification().getBlacklistedProtocols().contains(protocolId)) {
// Mark the connection as dead to avoid unnecessary console logs
markConnectionAsDead(activeSessionHandler);
initialConnection.getConnection().closeWith(Disconnect.create(
Sonar.get().getConfig().getVerification().getProtocolBlacklisted(),
inboundConnection.getProtocolVersion()
));
return;
}
// Check if the player is already verified.
// No one wants to be verified over and over again.
final GameProfile gameProfile = GameProfile.forOfflinePlayer(event.getUsername());
if (Sonar.get().getVerifiedPlayerController().has(inetAddress, gameProfile.getId())) return;
// Completely skip Geyser connections
if (isGeyserConnection(channel)) {
fallback.getLogger().info("Skipping Geyser player: {}{}",
gameProfile.getName(), Sonar.get().getConfig().formatAddress(inetAddress));
return;
}
// Check if the protocol ID of the player is allowed to bypass verification
if (Sonar.get().getConfig().getVerification().getWhitelistedProtocols().contains(protocolId)) return;
// We now mark the connection as dead by using our fake connection
markConnectionAsDead(activeSessionHandler);
@@ -204,16 +217,6 @@ public final class FallbackListener {
return;
}
// We cannot allow too many players on our Fallback server
// There's technically no reason for limiting this, but we'll better stay safe.
if (fallback.getConnected().size() > Sonar.get().getConfig().getVerification().getMaxVerifyingPlayers()) {
initialConnection.getConnection().closeWith(Disconnect.create(
Sonar.get().getConfig().getVerification().getTooManyPlayers(),
inboundConnection.getProtocolVersion()
));
return;
}
// Check if the IP address is currently being rate-limited
if (!fallback.getRatelimiter().attempt(inetAddress)) {
initialConnection.getConnection().closeWith(Disconnect.create(
@@ -243,12 +246,8 @@ public final class FallbackListener {
// Add better timeout handler to avoid known exploits or issues
// We also want to timeout bots quickly to avoid flooding
pipeline.replace(
READ_TIMEOUT,
READ_TIMEOUT,
new FallbackTimeoutHandler(Sonar.get().getConfig().getVerification().getReadTimeout(),
TimeUnit.MILLISECONDS)
);
final int readTimeout = Sonar.get().getConfig().getVerification().getReadTimeout();
pipeline.replace(READ_TIMEOUT, READ_TIMEOUT, new FallbackTimeoutHandler(readTimeout, TimeUnit.MILLISECONDS));
// We need to determine if the player is premium before we handle the connection,
// so we can create a ConnectedPlayer instance without having to spoof this
@@ -278,7 +277,7 @@ public final class FallbackListener {
final FallbackUserWrapper user = new FallbackUserWrapper(
fallback, connectedPlayer, mcConnection, mcConnection.getChannel(),
mcConnection.getChannel().pipeline(), inetAddress,
ProtocolVersion.fromId(connectedPlayer.getProtocolVersion().getProtocol())
ProtocolVersion.fromId(protocolId)
);
// Disconnect if the protocol version could not be resolved
@@ -334,10 +333,8 @@ public final class FallbackListener {
? FallbackPacketRegistry.CONFIG : FallbackPacketRegistry.GAME);
// Replace normal decoder to allow custom packets
user.getPipeline().replace(
MINECRAFT_DECODER, FALLBACK_PACKET_DECODER, new FallbackPacketDecoder(user,
new FallbackVerificationHandler(user, gameProfile.getName(), connectedPlayer.getUniqueId())
));
user.getPipeline().replace(MINECRAFT_DECODER, FALLBACK_PACKET_DECODER, new FallbackPacketDecoder(user,
new FallbackVerificationHandler(user, gameProfile.getName(), connectedPlayer.getUniqueId())));
}));
} catch (Throwable throwable) {
throw new ReflectiveOperationException(throwable);
@@ -349,22 +346,6 @@ public final class FallbackListener {
public void handle(final @NotNull LoginEvent event) {
val connectedPlayer = (ConnectedPlayer) event.getPlayer();
if (Sonar.get().getConfig().getLockdown().isEnabled()
&& !event.getPlayer().hasPermission(Sonar.get().getConfig().getLockdown().getBypassPermission())) {
connectedPlayer.getConnection().closeWith(Disconnect.create(
Sonar.get().getConfig().getLockdown().getDisconnect(), connectedPlayer.getProtocolVersion()));
if (Sonar.get().getConfig().getLockdown().isLogAttempts()) {
Sonar.get().getLogger().info(Sonar.get().getConfig().getLockdown().getConsoleLog()
.replace("%player%", event.getPlayer().getUsername())
.replace("%ip%", Sonar.get().getConfig()
.formatAddress(event.getPlayer().getRemoteAddress().getAddress()))
.replace("%protocol%",
String.valueOf(event.getPlayer().getProtocolVersion().getProtocol())));
}
return;
}
final InetAddress inetAddress = event.getPlayer().getRemoteAddress().getAddress();
// Check if the number of online players using the same IP address as
@@ -384,15 +365,4 @@ public final class FallbackListener {
}
}
}
@Subscribe(order = PostOrder.LAST)
public void handle(final @NotNull PostLoginEvent event) {
if (Sonar.get().getConfig().getLockdown().isEnabled() && Sonar.get().getConfig().getLockdown().isNotifyAdmins()) {
if (event.getPlayer().hasPermission(Sonar.get().getConfig().getLockdown().getBypassPermission())) {
final String notification = Sonar.get().getConfig().getLockdown().getNotification();
final Component deserialized = MiniMessage.miniMessage().deserialize(notification);
event.getPlayer().sendMessage(deserialized);
}
}
}
}