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:
commit
cf9608ce5d
159 changed files with 15341 additions and 0 deletions
|
|
@ -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")
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue