Initial commit: Rampart v0.2.0

Multi-layer DDoS protection for Minecraft servers.

- rampart-core: Edge node with XDP/eBPF + Rust L7 filtering
- rampart-manager: REST API with JWT auth, Redis sync
- rampart-cli: CLI tool for operators
- velocity-plugin: Domain check, HMAC verify, server registry, load balancer
- paper-plugin: Auto-registration, heartbeat, HMAC verify
- dashboard: React + Vite web UI for management
This commit is contained in:
loki5512344 2026-07-20 20:53:32 +02:00
commit cf9608ce5d
Signed by: boba
GPG key ID: 253067914055423B
159 changed files with 15341 additions and 0 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

View file

@ -0,0 +1,2 @@
#Sun Jul 19 13:29:18 CEST 2026
gradle.version=9.6.1

Binary file not shown.

Binary file not shown.

View file

28
plugins/.project Normal file
View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>rampart-plugins-plugins</name>
<comment>Project plugins created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
<filteredResources>
<filter>
<id>1784460569616</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

View file

@ -0,0 +1,13 @@
arguments=--init-script /home/loki/.cache/opencode/bin/jdtls/config_linux/org.eclipse.osgi/57/0/.cp/gradle/init/init.gradle
auto.sync=false
build.scans.enabled=false
connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER)
connection.project.dir=
eclipse.preferences.version=1
gradle.user.home=
java.home=/usr/lib/jvm/java-21-openjdk
jvm.arguments=
offline.mode=false
override.workspace.settings=true
show.console.view=true
show.executions.view=true

14
plugins/build.gradle.kts Normal file
View file

@ -0,0 +1,14 @@
subprojects {
apply(plugin = "java")
configure<JavaPluginExtension> {
toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
}
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
version=0.1.0
group=me.rampart

Binary file not shown.

View file

@ -0,0 +1,9 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip
networkTimeout=10000
retries=0
retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
plugins/gradlew vendored Executable file
View file

@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# gradlew start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh gradlew
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/<unknown>/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

82
plugins/gradlew.bat vendored Normal file
View file

@ -0,0 +1,82 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem gradlew startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables, and ensure extensions are enabled
setlocal EnableExtensions
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
"%COMSPEC%" /c exit 1
:execute
@rem Setup the command line
@rem Execute gradlew
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
@rem which allows us to clear the local environment before executing the java command
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
:exitWithErrorLevel
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
"%COMSPEC%" /c exit %ERRORLEVEL%

18
plugins/paper/.classpath Normal file
View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="bin/main" path="src/main/java">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/main" path="src/main/resources">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-21/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="output" path="bin/default"/>
</classpath>

34
plugins/paper/.project Normal file
View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>paper</name>
<comment>Project paper created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
<filteredResources>
<filter>
<id>1784566057669</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

View file

@ -0,0 +1,2 @@
connection.project.dir=..
eclipse.preferences.version=1

View file

@ -0,0 +1,6 @@
name: Rampart
version: '0.1.0'
main: me.rampart.paper.RampartPaper
api-version: '1.21'
author: loki
description: HMAC hostname verification for Rampart

View file

@ -0,0 +1,26 @@
plugins {
id("java")
id("com.gradleup.shadow") version "9.0.0-beta2"
}
repositories {
mavenCentral()
maven("https://repo.papermc.io/repository/maven-public/")
}
dependencies {
compileOnly("io.papermc.paper:paper-api:1.21.3-R0.1-SNAPSHOT")
implementation("redis.clients:jedis:5.2.0")
}
tasks {
shadowJar {
archiveBaseName.set("rampart-paper")
archiveClassifier.set("")
archiveVersion.set(project.property("version").toString())
}
build {
dependsOn(shadowJar)
}
}

View file

@ -0,0 +1,51 @@
package me.rampart.paper;
import net.kyori.adventure.text.Component;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
public class HmacLoginListener implements Listener {
private static final int HEX_SIG_LENGTH = 64;
private final RampartPaper plugin;
public HmacLoginListener(RampartPaper plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerLogin(PlayerLoginEvent event) {
String secretEnv = System.getenv("RAMPART_HMAC_SECRET");
if (secretEnv == null || secretEnv.isEmpty()) return;
byte[] secret = secretEnv.getBytes();
String raw = event.getHostname();
if (raw == null || raw.isEmpty()) return;
int sepIdx = raw.indexOf(RampartPaper.SHIELD_SEPARATOR);
if (sepIdx < 0) {
return;
}
String domain = raw.substring(0, sepIdx);
String sig = raw.substring(sepIdx + RampartPaper.SHIELD_SEPARATOR.length());
if (sig.length() != HEX_SIG_LENGTH) {
plugin.getLogger().warning("Invalid sig length from " + event.getAddress() +
": got " + sig.length() + ", expected " + HEX_SIG_LENGTH);
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
Component.text("Connection rejected: invalid signature"));
return;
}
String expected = plugin.hmacHex(domain, secret);
if (expected == null || !plugin.constantTimeEquals(sig, expected)) {
plugin.getLogger().warning("HMAC verification failed for " + event.getAddress());
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
Component.text("Connection rejected: invalid signature"));
}
}
}

View file

@ -0,0 +1,62 @@
package me.rampart.paper;
import org.bukkit.plugin.java.JavaPlugin;
public class RampartPaper extends JavaPlugin {
static final String SHIELD_SEPARATOR = "\0shield\0";
private ShieldAgent shieldAgent;
@Override
public void onEnable() {
String secret = System.getenv("RAMPART_HMAC_SECRET");
if (secret == null || secret.isEmpty()) {
getLogger().warning("RAMPART_HMAC_SECRET not set — HMAC verification disabled");
} else {
getLogger().info("Rampart HMAC verification enabled");
}
getServer().getPluginManager().registerEvents(new HmacLoginListener(this), this);
try {
shieldAgent = new ShieldAgent(this);
shieldAgent.start();
getLogger().info("ShieldAgent started");
} catch (Exception e) {
getLogger().severe("Failed to start ShieldAgent: " + e.getMessage());
}
}
@Override
public void onDisable() {
if (shieldAgent != null) {
shieldAgent.shutdown();
getLogger().info("ShieldAgent shut down");
}
}
String hmacHex(String data, byte[] secret) {
try {
var mac = javax.crypto.Mac.getInstance("HmacSHA256");
mac.init(new javax.crypto.spec.SecretKeySpec(secret, "HmacSHA256"));
byte[] raw = mac.doFinal(data.getBytes());
StringBuilder sb = new StringBuilder(raw.length * 2);
for (byte b : raw) {
sb.append(String.format("%02x", b & 0xFF));
}
return sb.toString();
} catch (Exception e) {
getLogger().severe("HMAC error: " + e.getMessage());
return null;
}
}
boolean constantTimeEquals(String a, String b) {
if (a.length() != b.length()) return false;
int result = 0;
for (int i = 0; i < a.length(); i++) {
result |= a.charAt(i) ^ b.charAt(i);
}
return result == 0;
}
}

View file

@ -0,0 +1,117 @@
package me.rampart.paper;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import redis.clients.jedis.Jedis;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.concurrent.ThreadLocalRandom;
public class ShieldAgent {
private final RampartPaper plugin;
private final Jedis jedis;
private final String serverName;
private final String serverIp;
private final int serverPort;
private BukkitRunnable task;
public ShieldAgent(RampartPaper plugin) {
this.plugin = plugin;
String redisUrl = System.getenv("RAMPART_REDIS_URL");
if (redisUrl == null || redisUrl.isEmpty()) {
redisUrl = "redis://127.0.0.1:6379/0";
}
this.jedis = new Jedis(URI.create(redisUrl));
String name = System.getenv("RAMPART_SERVER_NAME");
if (name == null || name.isEmpty()) {
int rand = ThreadLocalRandom.current().nextInt(0x10000);
name = "paper-" + String.format("%04x", rand);
}
this.serverName = name;
String ip = System.getenv("RAMPART_SERVER_IP");
if (ip == null || ip.isEmpty()) {
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
ip = "127.0.0.1";
}
}
this.serverIp = ip;
this.serverPort = plugin.getServer().getPort();
}
public void start() {
register();
task = new BukkitRunnable() {
@Override
public void run() {
heartbeat();
}
};
task.runTaskTimer(plugin, 0L, 20L);
}
public void shutdown() {
if (task != null) {
task.cancel();
}
try {
setOffline();
} finally {
jedis.close();
}
}
private void register() {
try {
String json = buildJson("online", plugin.getServer().getOnlinePlayers().size(),
plugin.getServer().getMaxPlayers(), Bukkit.getTPS()[0]);
jedis.set("rampart:servers:" + serverName, json);
plugin.getLogger().info("Registered server " + serverName + " in Redis at " + serverIp + ":" + serverPort);
} catch (Exception e) {
plugin.getLogger().severe("Failed to register in Redis: " + e.getMessage());
}
}
private void heartbeat() {
try {
int online = plugin.getServer().getOnlinePlayers().size();
int maxPlayers = plugin.getServer().getMaxPlayers();
double tps = Bukkit.getTPS()[0];
String json = buildJson("online", online, maxPlayers, tps);
jedis.set("rampart:servers:" + serverName, json);
} catch (Exception e) {
plugin.getLogger().severe("Heartbeat error: " + e.getMessage());
}
}
private void setOffline() {
try {
int online = plugin.getServer().getOnlinePlayers().size();
int maxPlayers = plugin.getServer().getMaxPlayers();
double tps = Bukkit.getTPS()[0];
String json = buildJson("offline", online, maxPlayers, tps);
jedis.set("rampart:servers:" + serverName, json);
plugin.getLogger().info("Server " + serverName + " marked offline in Redis");
} catch (Exception e) {
plugin.getLogger().severe("Failed to mark offline in Redis: " + e.getMessage());
}
}
private String buildJson(String status, int online, int maxPlayers, double tps) {
return "{\"name\":\"" + serverName + "\",\"type\":\"paper\",\"ip\":\"" + serverIp
+ "\",\"port\":" + serverPort + ",\"status\":\"" + status
+ "\",\"online\":" + online + ",\"max_players\":" + maxPlayers
+ ",\"tps\":" + tps
+ ",\"last_heartbeat\":" + System.currentTimeMillis() / 1000 + "}";
}
}

View file

@ -0,0 +1,6 @@
name: Rampart
version: '0.1.0'
main: me.rampart.paper.RampartPaper
api-version: '1.21'
author: loki
description: HMAC hostname verification for Rampart

View file

@ -0,0 +1,10 @@
rootProject.name = "rampart-plugins"
pluginManagement {
repositories {
gradlePluginPortal()
maven("https://papermc.io/repo/repository/maven-public/")
}
}
include("velocity", "paper")

View file

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="bin/main" path="src/main/java">
<attributes>
<attribute name="gradle_scope" value="main"/>
<attribute name="gradle_used_by_scope" value="main,test"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/test" path="src/test/java">
<attributes>
<attribute name="gradle_scope" value="test"/>
<attribute name="gradle_used_by_scope" value="test"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-21/"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer"/>
<classpathentry kind="src" path="bin/generated-sources/annotations">
<attributes>
<attribute name="optional" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="bin/test" path="bin/generated-test-sources/annotations">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin/default"/>
</classpath>

View file

@ -0,0 +1,40 @@
<factorypath>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/org.spongepowered/configurate-hocon/4.1.2/3953a4aef8ff62c72d34e405d6df333f3876592a/configurate-hocon-4.1.2.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/org.slf4j/slf4j-api/2.0.17/d9e58ac9c7779ba3bf8142aff6c830617a7fe60f/slf4j-api-2.0.17.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.velocitypowered/velocity-brigadier/1.0.0-SNAPSHOT/c85456381b9942f529995996793190c091ef57a9/velocity-brigadier-1.0.0-SNAPSHOT.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/adventure-key/4.26.1/6ded614dc07cc6c2da418a8e907ee42325badcda/adventure-key-4.26.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/org.spongepowered/configurate-gson/4.1.2/3e5c7a0ea73e95ce6139fa72f1b6d36eb531ab81/configurate-gson-4.1.2.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.google.j2objc/j2objc-annotations/1.3/ba035118bc8bac37d7eff77700720999acd9986d/j2objc-annotations-1.3.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/org.spongepowered/configurate-yaml/4.1.2/f726180c21ec387be5b8a2e04d916443c4046207/configurate-yaml-4.1.2.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/aopalliance/aopalliance/1.0/235ba8b489512805ac13a8f9ea77a1ca5ebe3e8/aopalliance-1.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.google.code.findbugs/jsr305/3.0.2/25ea2e8b0c338a877313bd4672d3fe056ea78f0d/jsr305-3.0.2.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/org.checkerframework/checker-qual/3.42.0/638ec33f363a94d41a4f03c3e7d3dcfba64e402d/checker-qual-3.42.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.google.errorprone/error_prone_annotations/2.21.1/6d9b10773b5237df178a7b3c1b4208df7d0e7f94/error_prone_annotations-2.21.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/adventure-text-serializer-json/4.26.1/7f98d4d9105254b1567379629a52236f5ebaf215/adventure-text-serializer-json-4.26.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/adventure-text-serializer-plain/4.26.1/cce5ad32da24b824edc8518535431059340873d5/adventure-text-serializer-plain-4.26.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/option/1.1.0/593fecb9c42688eebc7d8da5d6ea127f4d4c92a2/option-1.1.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/adventure-text-serializer-legacy/4.26.1/3267b14ac7fa167b97beb8c114d87d83609847af/adventure-text-serializer-legacy-4.26.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.google.guava/listenablefuture/9999.0-empty-to-avoid-conflict-with-guava/b421526c5f297295adef1c886e5246c39d4ac629/listenablefuture-9999.0-empty-to-avoid-conflict-with-guava.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/org.spongepowered/configurate-core/4.1.2/d6728b04738e73847f6a26349cf4368362feab97/configurate-core-4.1.2.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.github.ben-manes.caffeine/caffeine/3.1.8/24795585df8afaf70a2cd534786904ea5889c047/caffeine-3.1.8.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/adventure-text-serializer-commons/4.26.1/ef0ca2d1307415c9700d8e2f04adf283d6da46fa/adventure-text-serializer-commons-4.26.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/examination-api/1.3.0/8a2d185275307f1e2ef2adf7152b9a0d1d44c30b/examination-api-1.3.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.google.code.gson/gson/2.10.1/b3add478d4382b78ea20b1671390a858002feb6c/gson-2.10.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/adventure-text-serializer-ansi/4.26.1/7b441092ed57af2445872daa652ba2fce5deba31/adventure-text-serializer-ansi-4.26.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/jakarta.inject/jakarta.inject-api/2.0.1/4c28afe1991a941d7702fe1362c365f0a8641d1e/jakarta.inject-api-2.0.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.moandjiezana.toml/toml4j/0.7.2/a03337911d0bd2c40932aca3946edb30d0e7d0c/toml4j-0.7.2.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.google.inject/guice/6.0.0/9b422c69c4fa1ea95b2615444a94fede9b02fc40/guice-6.0.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/examination-string/1.3.0/6f34afef5c54ccce4996bc321abf77518b55b4bd/examination-string-1.3.0.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.google.guava/failureaccess/1.0.1/1dcf1de382a0bf95a3d8b0849546c88bac1292c9/failureaccess-1.0.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/ansi/1.1.1/beeb71e49b25cac87c22975014e74c7b5940d1b7/ansi-1.1.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.typesafe/config/1.4.1/19058a07624a87f90d129af7cd9c68bee94535a9/config-1.4.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/adventure-text-serializer-gson/4.26.1/3523abdae3098630e4ce9e808bb25e3f71ca60d1/adventure-text-serializer-gson-4.26.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.google.guava/guava/31.0.1-jre/119ea2b2bc205b138974d351777b20f02b92704b/guava-31.0.1-jre.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/adventure-text-minimessage/4.26.1/9983d86668d6adba7e600dac20a5e61af703a6c6/adventure-text-minimessage-4.26.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/io.leangen.geantyref/geantyref/1.3.11/bc9c03b53917314d21fe6276aceb08aa84bf80dd/geantyref-1.3.11.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/adventure-text-logger-slf4j/4.26.1/f18d40094ec8f64087f420069f06e024558d74d6/adventure-text-logger-slf4j-4.26.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/org.yaml/snakeyaml/1.33/2cd0a87ff7df953f810c344bdf2fe3340b954c69/snakeyaml-1.33.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/javax.inject/javax.inject/1/6975da39a7040257bd51d21a231b76c915872d38/javax.inject-1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/net.kyori/adventure-api/4.26.1/907ea365968cae9bdd84d19f2c258f65cf5f12a4/adventure-api-4.26.1.jar" enabled="true" runInBatchMode="false"/>
<factorypathentry kind="EXTJAR" id="/home/loki/.gradle/caches/modules-2/files-2.1/com.velocitypowered/velocity-api/3.4.0-SNAPSHOT/f8b024e83389b5293b1efa55f1753de8151b79fa/velocity-api-3.4.0-SNAPSHOT.jar" enabled="true" runInBatchMode="false"/>
</factorypath>

34
plugins/velocity/.project Normal file
View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>velocity</name>
<comment>Project velocity created by Buildship.</comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.buildship.core.gradleprojectbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.buildship.core.gradleprojectnature</nature>
</natures>
<filteredResources>
<filter>
<id>1784566057672</id>
<name></name>
<type>30</type>
<matcher>
<id>org.eclipse.core.resources.regexFilterMatcher</id>
<arguments>node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

View file

@ -0,0 +1,2 @@
connection.project.dir=..
eclipse.preferences.version=1

View file

@ -0,0 +1,4 @@
eclipse.preferences.version=1
org.eclipse.jdt.apt.aptEnabled=true
org.eclipse.jdt.apt.genSrcDir=bin/generated-sources/annotations
org.eclipse.jdt.apt.genTestSrcDir=bin/generated-test-sources/annotations

View file

@ -0,0 +1,2 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.processAnnotations=enabled

View file

@ -0,0 +1 @@
{"id":"rampart","name":"Rampart","version":"0.1.0","description":"HMAC hostname verification + domain whitelist + Redis server registry for Rampart","authors":["loki"],"dependencies":[],"main":"me.rampart.velocity.RampartVelocity"}

View file

@ -0,0 +1,37 @@
plugins {
id("java")
id("com.gradleup.shadow") version "9.0.0-beta2"
}
repositories {
mavenCentral()
maven("https://papermc.io/repo/repository/maven-public/")
}
dependencies {
compileOnly("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT")
annotationProcessor("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT")
implementation("redis.clients:jedis:5.2.0")
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
testImplementation("org.slf4j:slf4j-api:2.0.16")
testRuntimeOnly("org.slf4j:slf4j-simple:2.0.16")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks {
shadowJar {
archiveBaseName.set("rampart-velocity")
archiveClassifier.set("")
archiveVersion.set(project.property("version").toString())
}
build {
dependsOn(shadowJar)
}
}

View file

@ -0,0 +1,56 @@
package me.rampart.velocity;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.LoginEvent;
import net.kyori.adventure.text.Component;
import org.slf4j.Logger;
import java.net.InetSocketAddress;
import java.util.List;
public class DomainCheckListener {
private final Logger logger;
private final List<String> allowedDomains;
public DomainCheckListener(Logger logger, List<String> allowedDomains) {
this.logger = logger;
this.allowedDomains = allowedDomains;
}
@Subscribe
public void onLogin(LoginEvent event) {
if (allowedDomains.isEmpty()) return;
var player = event.getPlayer();
String hostname = player.getVirtualHost()
.map(InetSocketAddress::getHostString)
.orElse("");
if (hostname.isEmpty()) {
event.setResult(LoginEvent.ComponentResult.denied(
Component.text("Connection rejected: no hostname")
));
return;
}
String clean = hostname.split("\0")[0];
if (DomainCheckUtil.isIpAddress(clean)) {
logger.warn("Direct IP connect blocked from {} (hostname: {})",
player.getRemoteAddress(), clean);
event.setResult(LoginEvent.ComponentResult.denied(
Component.text("Direct IP connections are not allowed")
));
return;
}
if (!DomainCheckUtil.isDomainAllowed(clean, allowedDomains)) {
logger.warn("Domain not allowed from {} (hostname: {})",
player.getRemoteAddress(), clean);
event.setResult(LoginEvent.ComponentResult.denied(
Component.text("This domain is not allowed")
));
}
}
}

View file

@ -0,0 +1,33 @@
package me.rampart.velocity;
import java.util.List;
public class DomainCheckUtil {
public static boolean isIpAddress(String hostname) {
if (hostname == null || hostname.isEmpty()) return false;
if (hostname.chars().allMatch(c -> c == '.' || Character.isDigit(c))) {
String[] parts = hostname.split("\\.");
if (parts.length == 4) {
try {
for (String p : parts) {
int val = Integer.parseInt(p);
if (val < 0 || val > 255) return false;
}
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
return false;
}
public static boolean isDomainAllowed(String hostname, List<String> allowedDomains) {
if (allowedDomains == null || allowedDomains.isEmpty()) return true;
String clean = hostname.split("\0")[0];
return allowedDomains.stream()
.anyMatch(d -> clean.equals(d) || clean.endsWith("." + d));
}
}

View file

@ -0,0 +1,107 @@
package me.rampart.velocity;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.LoginEvent;
import net.kyori.adventure.text.Component;
import org.slf4j.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class HmacCheckListener {
private static final String SHIELD_SEPARATOR = "\0shield\0";
private static final String HMAC_ALGO = "HmacSHA256";
private static final int HEX_SIG_LENGTH = 64;
private final Logger logger;
private final byte[] secret;
public HmacCheckListener(Logger logger, String secret) {
this.logger = logger;
this.secret = secret.getBytes();
}
@Subscribe
public void onLogin(LoginEvent event) {
var player = event.getPlayer();
var vh = player.getVirtualHost();
if (vh.isEmpty()) {
event.setResult(LoginEvent.ComponentResult.denied(
Component.text("Connection rejected: no virtual host")
));
return;
}
String raw = vh.get().getHostString();
if (raw == null || raw.isEmpty()) {
event.setResult(LoginEvent.ComponentResult.denied(
Component.text("Connection rejected: empty hostname")
));
return;
}
int sepIdx = raw.indexOf(SHIELD_SEPARATOR);
if (sepIdx < 0) {
event.setResult(LoginEvent.ComponentResult.denied(
Component.text("Connection rejected: unsigned connection")
));
return;
}
String domain = raw.substring(0, sepIdx);
String sig = raw.substring(sepIdx + SHIELD_SEPARATOR.length());
if (sig.length() != HEX_SIG_LENGTH) {
logger.warn("Invalid HMAC signature length from {}: got {}, expected {}",
player.getRemoteAddress(), sig.length(), HEX_SIG_LENGTH);
event.setResult(LoginEvent.ComponentResult.denied(
Component.text("Connection rejected: invalid signature")
));
return;
}
String expected = hmacHex(domain);
if (expected == null) {
event.setResult(LoginEvent.ComponentResult.denied(
Component.text("Connection rejected: internal error")
));
return;
}
if (!constantTimeEquals(sig, expected)) {
logger.warn("HMAC verification failed for {} (domain: {})",
player.getRemoteAddress(), domain);
event.setResult(LoginEvent.ComponentResult.denied(
Component.text("Connection rejected: invalid signature")
));
}
}
private String hmacHex(String data) {
try {
Mac mac = Mac.getInstance(HMAC_ALGO);
mac.init(new SecretKeySpec(secret, HMAC_ALGO));
byte[] raw = mac.doFinal(data.getBytes());
StringBuilder sb = new StringBuilder(raw.length * 2);
for (byte b : raw) {
sb.append(String.format("%02x", b & 0xFF));
}
return sb.toString();
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
logger.error("HMAC error", e);
return null;
}
}
private boolean constantTimeEquals(String a, String b) {
if (a.length() != b.length()) return false;
int result = 0;
for (int i = 0; i < a.length(); i++) {
result |= a.charAt(i) ^ b.charAt(i);
}
return result == 0;
}
}

View file

@ -0,0 +1,64 @@
package me.rampart.velocity;
import com.google.inject.Inject;
import com.velocitypowered.api.event.EventManager;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.proxy.ProxyServer;
import org.slf4j.Logger;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Plugin(
id = "rampart",
name = "Rampart",
version = "0.1.0",
description = "HMAC hostname verification + domain whitelist + Redis server registry for Rampart",
authors = {"loki"}
)
public class RampartVelocity {
private final Logger logger;
private final ServerRegistry serverRegistry;
@Inject
public RampartVelocity(ProxyServer server, Logger logger) {
this.logger = logger;
String secret = System.getenv("RAMPART_HMAC_SECRET");
List<String> allowed = loadDomainWhitelist();
if (!allowed.isEmpty()) {
logger.info("Domain whitelist: {} domains loaded", allowed.size());
server.getEventManager().register(this, new DomainCheckListener(logger, allowed));
} else {
logger.warn("RAMPART_ALLOWED_DOMAINS not set — domain check disabled");
}
if (secret != null && !secret.isEmpty()) {
logger.info("HMAC verification enabled");
server.getEventManager().register(this, new HmacCheckListener(logger, secret));
} else {
logger.warn("RAMPART_HMAC_SECRET not set — HMAC verification disabled");
}
String redisUrl = System.getenv("RAMPART_REDIS_URL");
if (redisUrl == null || redisUrl.isEmpty()) {
redisUrl = "redis://127.0.0.1:6379/0";
}
serverRegistry = new ServerRegistry(server, logger, redisUrl);
serverRegistry.startSync();
logger.info("Server registry sync started with Redis at {}", redisUrl);
}
private List<String> loadDomainWhitelist() {
String env = System.getenv("RAMPART_ALLOWED_DOMAINS");
if (env == null || env.isEmpty()) return Collections.emptyList();
return Arrays.stream(env.split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.toList();
}
}

View file

@ -0,0 +1,142 @@
package me.rampart.velocity;
import com.velocitypowered.api.proxy.ProxyServer;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import com.velocitypowered.api.proxy.server.ServerInfo;
import org.slf4j.Logger;
import redis.clients.jedis.Jedis;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class ServerRegistry {
private final ProxyServer proxyServer;
private final Logger logger;
private final String redisUrl;
private final AtomicInteger counter = new AtomicInteger(0);
private volatile List<RegisteredServer> cachedServers = new ArrayList<>();
public ServerRegistry(ProxyServer proxyServer, Logger logger, String redisUrl) {
this.proxyServer = proxyServer;
this.logger = logger;
this.redisUrl = redisUrl;
}
public void startSync() {
loadAndUpdateServers();
proxyServer.getScheduler()
.buildTask(this, this::loadAndUpdateServers)
.repeat(30, TimeUnit.SECONDS)
.schedule();
}
void loadAndUpdateServers() {
List<ServerInfo> redisServers = loadServersFromRedis();
Set<String> redisNames = redisServers.stream()
.map(ServerInfo::getName)
.collect(Collectors.toSet());
Set<String> registeredNames = proxyServer.getAllServers().stream()
.map(s -> s.getServerInfo().getName())
.collect(Collectors.toSet());
int registered = 0;
int unregistered = 0;
for (ServerInfo info : redisServers) {
if (!registeredNames.contains(info.getName())) {
proxyServer.registerServer(info);
registered++;
}
}
for (String name : registeredNames) {
if (!redisNames.contains(name)) {
proxyServer.getServer(name).ifPresent(s ->
proxyServer.unregisterServer(s.getServerInfo()));
unregistered++;
}
}
List<RegisteredServer> servers = redisServers.stream()
.map(info -> proxyServer.getServer(info.getName()).orElse(null))
.filter(Objects::nonNull)
.collect(Collectors.toList());
cachedServers = servers;
logger.info("Server sync complete: {} registered, {} unregistered, {} online",
registered, unregistered, servers.size());
}
List<ServerInfo> loadServersFromRedis() {
List<ServerInfo> servers = new ArrayList<>();
try (Jedis jedis = new Jedis(redisUrl)) {
Set<String> keys = jedis.keys("rampart:servers:*");
for (String key : keys) {
String json = jedis.get(key);
if (json == null || json.isEmpty()) continue;
try {
String name = extractJsonString(json, "name");
String ip = extractJsonString(json, "ip");
if (name == null || ip == null) continue;
int port = extractJsonInt(json, "port");
if (port <= 0) continue;
String status = extractJsonString(json, "status");
if (!"online".equals(status)) continue;
servers.add(new ServerInfo(name, InetSocketAddress.createUnresolved(ip, port)));
} catch (Exception e) {
logger.warn("Failed to parse server data for key {}: {}", key, e.getMessage());
}
}
} catch (Exception e) {
logger.warn("Failed to connect to Redis at {}: {}", redisUrl, e.getMessage());
}
return servers;
}
public Optional<RegisteredServer> getNextServer() {
List<RegisteredServer> servers = cachedServers;
if (servers.isEmpty()) return Optional.empty();
int index = Math.abs(counter.getAndIncrement() % servers.size());
return Optional.ofNullable(servers.get(index));
}
public List<RegisteredServer> getCachedServers() {
return cachedServers;
}
private static String extractJsonString(String json, String key) {
String search = "\"" + key + "\":\"";
int start = json.indexOf(search);
if (start < 0) return null;
start += search.length();
int end = json.indexOf("\"", start);
if (end < 0) return null;
return json.substring(start, end);
}
private static int extractJsonInt(String json, String key) {
String search = "\"" + key + "\":";
int start = json.indexOf(search);
if (start < 0) return -1;
start += search.length();
int end = start;
while (end < json.length() && Character.isDigit(json.charAt(end))) {
end++;
}
if (end == start) return -1;
try {
return Integer.parseInt(json.substring(start, end));
} catch (NumberFormatException e) {
return -1;
}
}
}

View file

@ -0,0 +1,18 @@
package me.rampart.velocity;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import java.util.Optional;
public class ServerRouter {
private final ServerRegistry registry;
public ServerRouter(ServerRegistry registry) {
this.registry = registry;
}
public Optional<RegisteredServer> routeServer(String domain) {
return registry.getNextServer();
}
}

View file

@ -0,0 +1,144 @@
package me.rampart.velocity;
import org.junit.jupiter.api.Test;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class RampartVelocityTest {
@Test
void hmacProduces64HexChars() {
String sig = hmacHex("play.example.com", "test_secret");
assertNotNull(sig);
assertEquals(64, sig.length());
assertTrue(sig.matches("[0-9a-f]{64}"));
}
@Test
void hmacSameInputSameOutput() {
String a = hmacHex("play.example.com", "secret");
String b = hmacHex("play.example.com", "secret");
assertEquals(a, b);
}
@Test
void hmacDifferentSecretDifferentOutput() {
String a = hmacHex("play.example.com", "secret1");
String b = hmacHex("play.example.com", "secret2");
assertNotEquals(a, b);
}
@Test
void hmacDifferentInputDifferentOutput() {
String a = hmacHex("play.example.com", "secret");
String b = hmacHex("hub.example.com", "secret");
assertNotEquals(a, b);
}
@Test
void constantTimeEqualsSame() {
assertTrue(constantTimeEquals("abcdef", "abcdef"));
}
@Test
void constantTimeEqualsDifferent() {
assertFalse(constantTimeEquals("abcdef", "abcdeg"));
}
@Test
void constantTimeEqualsDifferentLength() {
assertFalse(constantTimeEquals("abc", "abcd"));
}
@Test
void constantTimeEqualsEmpty() {
assertTrue(constantTimeEquals("", ""));
}
@Test
void constantTimeEqualsNullSafety() {
assertFalse(constantTimeEquals(null, "a"));
assertFalse(constantTimeEquals("a", null));
}
@Test
void domainCheckRejectsIpv4() {
assertTrue(DomainCheckUtil.isIpAddress("192.168.1.1"));
assertTrue(DomainCheckUtil.isIpAddress("0.0.0.0"));
assertTrue(DomainCheckUtil.isIpAddress("255.255.255.255"));
}
@Test
void domainCheckAllowsDomains() {
assertTrue(DomainCheckUtil.isDomainAllowed("play.example.com", List.of("example.com")));
assertTrue(DomainCheckUtil.isDomainAllowed("mc.example.com", List.of("example.com")));
assertFalse(DomainCheckUtil.isIpAddress("play.example.com"));
assertFalse(DomainCheckUtil.isIpAddress("localhost"));
}
@Test
void domainCheckRejectsInvalidIp() {
assertFalse(DomainCheckUtil.isIpAddress("256.1.2.3"));
assertFalse(DomainCheckUtil.isIpAddress("1.2.3.4.5"));
assertFalse(DomainCheckUtil.isIpAddress("abc.def.ghi.jkl"));
assertFalse(DomainCheckUtil.isIpAddress(""));
assertFalse(DomainCheckUtil.isIpAddress(null));
}
@Test
void domainCheckSubdomainMatch() {
assertTrue(DomainCheckUtil.isDomainAllowed("play.example.com", List.of("example.com")));
assertTrue(DomainCheckUtil.isDomainAllowed("survival.hub.example.com", List.of("example.com")));
}
@Test
void domainCheckExactMatch() {
assertTrue(DomainCheckUtil.isDomainAllowed("example.com", List.of("example.com")));
}
@Test
void domainCheckNoMatch() {
assertFalse(DomainCheckUtil.isDomainAllowed("evil.com", List.of("example.com")));
}
@Test
void domainCheckEmptyWhitelistAllowsAll() {
assertTrue(DomainCheckUtil.isDomainAllowed("anything.com", List.of()));
assertTrue(DomainCheckUtil.isDomainAllowed("192.168.1.1", List.of()));
}
// --- HMAC utility (mirrors HmacCheckListener) ---
private String hmacHex(String data, String secret) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(), "HmacSHA256"));
byte[] raw = mac.doFinal(data.getBytes());
StringBuilder sb = new StringBuilder(raw.length * 2);
for (byte b : raw) {
sb.append(String.format("%02x", b & 0xFF));
}
return sb.toString();
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
return null;
}
}
// --- constant-time equals (mirrors HmacCheckListener) ---
private boolean constantTimeEquals(String a, String b) {
if (a == null || b == null) return false;
if (a.length() != b.length()) return false;
int result = 0;
for (int i = 0; i < a.length(); i++) {
result |= a.charAt(i) ^ b.charAt(i);
}
return result == 0;
}
}