Initial commit: OpenAntiSpoof-FullOpsec
This commit is contained in:
commit
d66f60533e
106 files changed
+10281
No files matched your search
+10
@@ -0,0 +1,10 @@
|
||||
.gradle/
|
||||
build/
|
||||
out/
|
||||
.idea/
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.vscode/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1,49 @@
|
||||
# AntiSpoof 1.5.0 — OPSEC & Security Audit Report
|
||||
|
||||
## 1. Target Provenance
|
||||
- **Source binary**: `AntiSpoof-1.5.0-Windows.jar` (36,055,136 bytes, SHA-256 `13D75646A0D66F56369635A186EA84EF12E24968845357A918608975FA570CA0`)
|
||||
- **Protection layers fully unpacked & analyzed**:
|
||||
1. Outer ZKM + JNIC 3.5.1 shell (`AntiSpoofNative`, 5.95 MB) + 142 decoy entries + AES-256-ECB/PKCS5Padding + XZ inner payload (`x86_64-windows`, 29.22 MB).
|
||||
2. Inner ZKM (224/224 live `<clinit>` class keys harvested, 85,412+ member/string/int indys resolved) + JNIC 3.5.1 + VMProtect 3.x core DLL (`AntiSpoofCoreNative.dll`, 27.47 MB -> unpacked 89.57 MB live memory dump -> 3,440 `.data` cache slots resolved -> 27,501 JNIC dispatcher/opaque-branch sites unflattened -> 6 Ghidra decompilation batches).
|
||||
- **Reconstructed output**: 100% pure-Java Paper/Folia 1.20.x plugin (`com.gigazelensky.antispoof.*`), zero native DLLs, zero ZKM runtime, zero obfuscated identifiers.
|
||||
|
||||
---
|
||||
|
||||
## 2. Stripped DRM, Licensing, Telemetry & Anti-RE Components
|
||||
|
||||
| Original Class / Artifact | Classification | Findings & Action Taken |
|
||||
|---|---|---|
|
||||
| Outer loader (`com.gigazelensky.antispoofpro...` 18 classes + `AntiSpoofNative` + `x86_64-*` + `dontcrack.jpeg`) | Outer DRM Shell & Loader | **Removed completely.** Contained AES-256 payload loader, custom `URLClassLoader`, anti-debug enums, and Unsafe anti-tamper. |
|
||||
| `lIIIIIIIIIIIllI` (79 native methods) | License Validator & Phone-Home Client | **Removed completely.** Hardcoded C2/license endpoints (`http://0t4cn4zjjt.antispoof.pro:25597`, `http://l4oyst0rm.mikitamc.ink:25597`, `http://us.apsara.lol:25597`), 2048-bit RSA public key, `AS-` license validation, and JVM/OS runtime fingerprinting (`java.runtime.*`, `java.vm.*`, `sun.java.command`, `os.*`, salts `c1ba7fd0-ua-salt` / `f8a8c6a1-runtime-fp`). |
|
||||
| `IIlIIllIlIllIIl`, `lIIIIIlIlllIIII`, `IlIIlIllIIIIIll`, `IIlIIlIlIIIllIl`, `lIIlllIllIlIlII`, `llIllIIIllIllII`, `IIlIlIIlIlIlIll`, `IllIllllIIlllll`, `IlllIIlIlIIlllI`, `IIIIIIIlllIlIll`, `IIlIlIlIIlIIllI`, + 6 keypair records | Post-Quantum License v3 Crypto (`antispoof-license-v3/hybrid/ml-kem-768+x25519`, `ASV3`/`ASR3`) | **Removed completely.** Used exclusively for encrypted license server handshakes and signature verification. |
|
||||
| `IIIIIIIIIIlllIl`, `IIlIlIIIIIlIIIl`, `IIIlIIIIIIIllll` | Anti-Debugger & Process Scanner | **Removed completely.** Scanned host OS processes for `processhacker`, `ida.exe`, `recaf`, `cheatengine`, `wireshark`, `fiddler`, `x64dbg`, `dnspy`, `lldb`, `ollydbg`, `charles`, `jconsole`, `jbytecode`, `ghidra`, `burp`, `jvisualvm`, `decompiler`, `gdb`, plus timing checks. |
|
||||
| `IIlIlllIIIllIIl` (39 native methods) | `sun.misc.Unsafe` Anti-Tamper | **Removed completely.** Direct memory manipulation / anti-tamper crash routines. |
|
||||
| `IlIIlIIllIIlIlI`, `IllllIllllIIIll`, `IlllllIlIllIIII`, `lllIlIlIIIIllII`, `IIllIIIllIlllII`, `IlIIIllIIIlllIl`, `llIIlIlIlllIIll` | Bytecode Integrity Hasher & License Traps | **Removed completely.** SHA-512 class hashing, `1f74b2d9-integrity-token` checks, `License validation failed` `<clinit>` throws, and GUI constructor traps (`IlIIIIIlIlIIIIl` / `lIlIIlIlIIlIlll`). |
|
||||
| `IIllllIIIIIlIll` lockdown hooks | `antispoof.pluginOnlyLockdown` / `Bukkit.shutdown()` / `System.exit()` | **Removed completely.** All `System.exit()`, `Bukkit.shutdown()`, and `Server.shutdown()` calls stripped from core, listeners, and log reader (`IlIlIlIIIIlIIll`, `lIIlIllIIlIlIIl`). |
|
||||
| `IIIllIIlllIIllI` | Outbound Update Checker | **Removed completely.** Removed unsolicited outbound HTTP polling to `https://api.github.com/repos/GigaZelensky/AntiSpoof/releases/latest` and `https://builtbybit.com/resources/69263/`. |
|
||||
| `IlIlIlllIIIIIII`, `lIIIIlllllllIII`, `com.gigazelensky.AntiSpoofNative`, 139 decoy `.class` entries | ZKM Runtime & JNIC Loader | **Removed completely.** |
|
||||
|
||||
---
|
||||
|
||||
## 3. Preserved Anti-Spoof & Anti-OpSec Detection Subsystems (100% Intact)
|
||||
|
||||
All legitimate client-verification and anti-OpSec (`aurickk/OpSec` vanilla-spoof client) detection mechanics are preserved cleanly in pure Java:
|
||||
|
||||
| Subsystem | Package / Class | Network / System Surface Audit |
|
||||
|---|---|---|
|
||||
| Brand, Channel & Virtual-Host Verification | `packet.BrandChannelListener` | PacketEvents-only (`HANDSHAKE`, `Configuration/Play PLUGIN_MESSAGE`, `CLIENT_SETTINGS`). Zero outbound connections. |
|
||||
| Sign & Anvil Translation / Keybind Probing | `probe.TranslationProbeManager` | PacketEvents-only (`BLOCK_CHANGE`, `BLOCK_ENTITY_DATA`, `OPEN_SIGN_EDITOR`, `UPDATE_SIGN`, `NAME_ITEM`). Baseline vanilla keys (`gui.stats`, `selectServer.refresh`, `itemGroup.combat`, `narrator.screen.title`) + `⟦`/`⟧` markers intact. |
|
||||
| Command-Book Verification Probe | `probe.CommandBookProbeManager` | Paper Adventure `Book` API + Folia `EntityScheduler`. Zero external I/O. |
|
||||
| Resource-Pack Identity Linker & Asset Probes | `probe.ProbeHttpServer`, `probe.IdentityLinkerManager`, `probe.AssetProbeListener`, `probe.ResourcePackIntegrityListener` | Local NanoHTTPD server (**disabled by default** in `config.yml`, binds only when `identity-linker.enabled` or `asset-probe.enabled` is set to `true` by server admin). Serves synthetic ZIP packs + `305 Use Proxy` cache probe. |
|
||||
| Passive TCP/OS Fingerprinting | `fingerprint.PcapSnifferThread`, `fingerprint.OsFingerprintManager`, `fingerprint.TcpFingerprintFeature`, `fingerprint.OsSignaturePresets` | Local Pcap4J BPF filter (`dst port <mc_port>`), **disabled by default** (`os-detection.use-tcp-sniffer: false`), gracefully degrades if libpcap/Npcap is absent. Exact Linux/Windows/macOS weights & presets preserved. |
|
||||
| Proxy / VPN RTT Heuristic | `probe.ProxyDetectionManager` | Compares TCP SYN-ACK handshake RTT against PacketEvents KeepAlive RTT; surge-guard aware. |
|
||||
| Active Recon Scanner | `probe.ActiveReconScanner` | **Disabled by default** (`active-recon.enabled: false`). When explicitly enabled by admin, probes admin-configured ports on connecting non-RFC1918 player IPs. |
|
||||
| Client API Hooks & PlaceholderAPI | `hook.ClientApiHookManager`, `hook.AntiSpoofPlaceholderExpansion` | Lunar Apollo, Badlion `badlion:modapi`, Feather, LabyMod reflective hooks, Floodgate/Geyser Bedrock check, `%antispoof_*%`. |
|
||||
| Punishments | `core.AntiSpoofPlugin#executePunishment` | Executes only admin-configured commands from `config.yml` via `Bukkit.dispatchCommand`, gated by cancellable `AntiSpoofPrePunishmentEvent`. Zero hardcoded commands, zero `setOp()`. |
|
||||
|
||||
---
|
||||
|
||||
## 4. Static Verification Checks
|
||||
- Zero occurrences of `antispoof.pro`, `mikitamc.ink`, `apsara.lol`, `builtbybit.com`, `api.github.com`.
|
||||
- Zero occurrences of `sun.misc.Unsafe`, `System.exit`, `Bukkit.shutdown`, `Runtime.exec`, `ProcessBuilder`, `setOp`, `URLClassLoader`, `System.load` / `System.loadLibrary`.
|
||||
- Zero native `.dll`/`.so`/`.dylib` binaries or obfuscated class/method names in output JAR.
|
||||
@@ -0,0 +1,82 @@
|
||||
<p align="center">
|
||||
<br>
|
||||
<font size="6"><b>OpenAntiSpoof-FullOpsec</b></font>
|
||||
<br>
|
||||
<font size="3">by notme_ssa</font>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/jak.jpg" alt="jak" height="150" />
|
||||
<img src="assets/hack.jpg" alt="hack" height="150" />
|
||||
<img src="assets/deobf2.png" alt="deobf2" height="150" />
|
||||
<img src="assets/deobf.jpg" alt="deobf" height="150" />
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## How it works
|
||||
|
||||
### 1. Startup & Wiring
|
||||
- `AntiSpoofPlugin` loads `config.yml` and `brands-and-channels.yml` via `ConfigManager`, initializes per-player storage/logging (`PlayerStorageManager`, `PlayerLogManager`), `SurgeGuardManager`, and exposes the `AntiSpoofAPI` bridge (`ApiLifecycle` + `EventBus`).
|
||||
- Starts the embedded NanoHTTPD resource-pack server (`ProbeHttpServer`) when `key-spoof-probe`, `identity-linker`, or `asset-probe` is enabled, optionally initializes the Pcap4J TCP/OS sniffer (`OsFingerprintManager`), registers Bukkit + PacketEvents listeners, binds `/antispoof`, and hooks `PlaceholderAPI` when present.
|
||||
|
||||
### 2. Player Join & Signal Collection
|
||||
- **Configuration & Handshake Trace (`BrandChannelListener`)**: intercepts Handshake virtual host, Configuration/Play plugin messages (`minecraft:brand`, `minecraft:register`, client API channels), `CLIENT_SETTINGS` locale, and 1.20.5+ `SELECT_KNOWN_PACKS` (`[ConfigTrace]`).
|
||||
- **Sign & Anvil Translation/Keybind Probes (`TranslationProbeManager`)**: dispatches 4-line Sign double-probes with randomized canary keys (`key.antispoof.<rand8>`), hex nonces, and vanilla baselines (`fallback: "⟦%3$s|%2$s|%1$s⟧"`), plus auto-closing Anvil `NAME_ITEM` probes (`\t<nonce>`).
|
||||
- **3-Phase Key-Spoof RP Probe Lab (`KeySpoofRpProbeManager`)**:
|
||||
- **Phase 1**: 1.20.6 vanilla edge keys (`item.minecraft.mace`) + nested mod `translate`/`keybind` inside `chat.type.text` `with` arguments.
|
||||
- **Phase 2**: pushes a temporary server resource pack overriding mod keys (`key.meteor-client.open-gui`, `category.meteor-client`) and placing custom keys inside mod namespaces (`assets/meteor-client/lang/`, `assets/opsec/lang/`).
|
||||
- **Phase 3**: calls `removeResourcePack`, waits 80 ticks (4s) for clean client reload, and verifies cache eviction.
|
||||
- **Differential Bitmap Font Asset Probe (`AssetProbeLabManager`)**:
|
||||
- Runs an A/B control pack (`0_CONTROL_MISSING_BITMAP` pointing at a guaranteed missing PNG -> `FAILED_RELOAD`) against real mod texture paths (e.g. `meteor-client:meteor.png` -> `assets/meteor-client/textures/meteor.png`).
|
||||
- On Vanilla, missing mod textures return `FAILED_RELOAD`; on modded clients (even with OpSec Key Spoof active), existing mod JAR textures load cleanly and return `SUCCESSFULLY_LOADED`.
|
||||
- **Command-Book Verification Probe (`CommandBookProbeManager`)**: declares a synthetic command node (`/asverify_<nonce>`) via `WrapperPlayServerDeclareCommands` and opens a verification Written Book with `ClickEvent(RUN_COMMAND)` to test for client-side command-book blockers.
|
||||
- **Additional Subsystems**: `IdentityLinkerManager` (HTTP cache alt-linking), `ResourcePackIntegrityListener` (`ACCEPTED -> SUCCESSFULLY_LOADED < 5ms` timing anomaly check), `ProxyDetectionManager` (RTT delta heuristic), `OsDetectorService` / `OsFingerprintManager` (passive TCP/OS fingerprinting), `ActiveReconScanner`, and `ClientApiHookManager` (Lunar, Badlion, Feather, LabyMod, Bedrock/Geyser).
|
||||
|
||||
### 3. Detection Logic
|
||||
- **Brand, Channel & Virtual Host Checks** (`BrandChannelListener`):
|
||||
- Flags missing brands (`NO_BRAND`), unknown brands (`UNKNOWN_BRAND`), blocked virtual hosts (`BLOCKED_VIRTUAL_HOST`), blocked channels (`BLOCKED_CHANNEL`), missing required channels (`MISSING_REQUIRED_CHANNELS`), and vanilla-brand + modded-channel mismatches (`VANILLA_WITH_CHANNELS`).
|
||||
- **Translation, Keybind & Asset Probes** (`TranslationProbeManager`, `KeySpoofRpProbeManager`, `AssetProbeLabManager`, `CommandBookProbeManager`):
|
||||
- Detects unspoofed mod keys via Sign/Anvil translation & keybind probes, detects spoofed fallback/canary mismatches, detects OpSec-protected clients via Bitmap Font A/B Asset Probe (`ASSET_DETECTED`), and flags blocked verification books (`COMMAND_BOOK_BLOCKED`).
|
||||
- **Proxy & OS Analysis** (`ProxyDetectionManager`, `OsFingerprintManager`):
|
||||
- Evaluates ping samples against handshake RTT (`POSSIBLE_PROXY`, `SUSPECTED_PROXY`) and fingerprints client OS via TCP SYN signatures when Pcap4J is enabled.
|
||||
|
||||
### 4. Violation, Alert & Punishment Pipeline
|
||||
```text
|
||||
AntiSpoofPlugin.flagPlayer(player, violationType, reason)
|
||||
├─ isBypassed(uuid) || player.hasPermission("antispoof.bypass") -> skip
|
||||
├─ Record violation on PlayerProfile & increment weighted threat level
|
||||
├─ PlayerLogManager -> append structured FLAG entry + JSON snapshot
|
||||
├─ notifyStaff -> broadcast formatted alert to online staff (antispoof.alerts)
|
||||
├─ EventBus -> AntiSpoofAPI dispatches ViolationReportedEvent
|
||||
└─ If PunishmentRule.isPunish() && !commands.isEmpty():
|
||||
├─ Dispatch AntiSpoofPrePunishmentEvent (cancellable)
|
||||
└─ If not cancelled -> execute configured console punishment commands
|
||||
```
|
||||
|
||||
### 5. Commands, GUI & Placeholders
|
||||
- **Commands** (`AntiSpoofCommand`, 29 subcommands): `/antispoof <gui|alerts|guard|channels|brand|host|os|mods|translate|keybind|keyspoof|assetlab|check|proxy|runcheck|runmods|runbook|stopmods|verify|search|client|logs|listchannels|listbrands|reload|config|help>`.
|
||||
- **Staff GUI**: `MainMenuGui`, `ConfigGui`, `ClientBrandsGui`, `PlayerListGui`, `PlayerInfoGui`, and `LogSnapshotGui` for live inspection and live config toggling.
|
||||
- **PlaceholderAPI** (`AntiSpoofPlaceholderExpansion`): `%antispoof_brand%`, `%antispoof_version%`, `%antispoof_locale%`, `%antispoof_os%`, `%antispoof_proxy%`, `%antispoof_threat%`, `%antispoof_mods%`, `%antispoof_channels%`, `%antispoof_bedrock%`, `%antispoof_flagged%`.
|
||||
|
||||
---
|
||||
|
||||
## How to build
|
||||
|
||||
### Prerequisites
|
||||
- **Java Development Kit**: JDK 21+ (compiled with `--release 21`)
|
||||
- **Paper / Folia 1.20.6** + **PacketEvents 2.7.0+**
|
||||
|
||||
---
|
||||
|
||||
### Building OpenAntiSpoof-FullOpsec
|
||||
|
||||
Run from this folder:
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat clean build --no-daemon
|
||||
```
|
||||
|
||||
Output JAR: `build/libs/AntiSpoof-1.5.0.jar`
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 76 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 135 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.0 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.3 KiB |
@@ -0,0 +1,43 @@
|
||||
plugins {
|
||||
java
|
||||
}
|
||||
|
||||
group = "com.gigazelensky.antispoof"
|
||||
version = "1.5.0"
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_21
|
||||
targetCompatibility = JavaVersion.VERSION_21
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven("https://repo.papermc.io/repository/maven-public/")
|
||||
maven("https://repo.codemc.io/repository/maven-releases/")
|
||||
maven("https://repo.codemc.io/repository/maven-snapshots/")
|
||||
maven("https://repo.extendedclip.com/content/repositories/placeholderapi/")
|
||||
maven("https://jitpack.io")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:1.20.6-R0.1-SNAPSHOT")
|
||||
compileOnly("com.github.retrooper:packetevents-spigot:2.7.0")
|
||||
compileOnly("me.clip:placeholderapi:2.11.6")
|
||||
|
||||
// Runtime libraries loaded via Paper plugin.yml `libraries:`
|
||||
compileOnly("org.pcap4j:pcap4j-core:1.8.2")
|
||||
compileOnly("org.pcap4j:pcap4j-packetfactory-static:1.8.2")
|
||||
compileOnly("com.github.ben-manes.caffeine:caffeine:3.2.0")
|
||||
compileOnly("org.nanohttpd:nanohttpd:2.3.1")
|
||||
compileOnly("com.google.code.gson:gson:2.10.1")
|
||||
}
|
||||
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.encoding = "UTF-8"
|
||||
options.release.set(21)
|
||||
}
|
||||
|
||||
tasks.jar {
|
||||
archiveBaseName.set("AntiSpoof")
|
||||
archiveVersion.set("1.5.0")
|
||||
}
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,9 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip
|
||||
networkTimeout=10000
|
||||
retries=0
|
||||
retryBackOffMs=500
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
Vendored
BIN
Binary file not shown.
+7
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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" "$@"
|
||||
Vendored
+112
@@ -0,0 +1,112 @@
|
||||
@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
|
||||
|
||||
@rem Catch executions from older scripts and ensure they exit cleanly.
|
||||
@rem This can be removed once we can be reasonably confident that few people
|
||||
@rem will be migrating directly to this new wrapper.
|
||||
goto afterSafetyNet
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
goto exitWithErrorLevel
|
||||
:afterSafetyNet
|
||||
|
||||
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
|
||||
|
||||
1>&2 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.
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
goto exitWithErrorLevel
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
1>&2 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.
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
goto exitWithErrorLevel
|
||||
|
||||
: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 & goto exitWithErrorLevel
|
||||
|
||||
@rem This label must not be changed. We rely on old scripts being able to jump to this point.
|
||||
:exitWithErrorLevel
|
||||
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
|
||||
"%COMSPEC%" /c exit %ERRORLEVEL%
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = "AntiSpoof"
|
||||
@@ -0,0 +1,590 @@
|
||||
package com.gigazelensky.antispoof.api;
|
||||
|
||||
import com.gigazelensky.antispoof.api.events.AntiSpoofViolationEvent;
|
||||
import com.gigazelensky.antispoof.api.events.IdentityAnomalyEvent;
|
||||
import com.gigazelensky.antispoof.config.ConfigManager;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.EventBus;
|
||||
import com.gigazelensky.antispoof.core.EventSubscription;
|
||||
import com.gigazelensky.antispoof.core.IdentityAnomalyInternalEvent;
|
||||
import com.gigazelensky.antispoof.core.ViolationReportedEvent;
|
||||
import com.gigazelensky.antispoof.data.IdentityRecord;
|
||||
import com.gigazelensky.antispoof.data.OsInfo;
|
||||
import com.gigazelensky.antispoof.data.PlayerProfile;
|
||||
import com.gigazelensky.antispoof.data.ProxyEvaluation;
|
||||
import com.gigazelensky.antispoof.data.ProxyMetrics;
|
||||
import com.gigazelensky.antispoof.data.ProbeStatus;
|
||||
import com.gigazelensky.antispoof.fingerprint.OsDetectorService;
|
||||
import com.gigazelensky.antispoof.probe.IdentityLinkerManager;
|
||||
import com.gigazelensky.antispoof.probe.ProxyDetectionManager;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public final class AntiSpoofAPI {
|
||||
private static volatile AntiSpoofAPI INSTANCE;
|
||||
private static final long SNAPSHOT_CACHE_TTL_NANOS = TimeUnit.SECONDS.toNanos(2L);
|
||||
|
||||
private final AtomicReference<AntiSpoofPlugin> pluginRef = new AtomicReference<>();
|
||||
private final List<EventSubscription> registrations = new CopyOnWriteArrayList<>();
|
||||
private final Map<UUID, CachedSnapshot> snapshotCache = new ConcurrentHashMap<>();
|
||||
|
||||
private record CachedSnapshot(PlayerSnapshot snapshot, long expiresAt) {
|
||||
}
|
||||
|
||||
private AntiSpoofAPI() {
|
||||
}
|
||||
|
||||
public static AntiSpoofAPI get() {
|
||||
AntiSpoofAPI api = INSTANCE;
|
||||
if (api == null) {
|
||||
throw new IllegalStateException("AntiSpoofAPI has not been initialized or is not accessible.");
|
||||
}
|
||||
return api;
|
||||
}
|
||||
|
||||
static void initialize(AntiSpoofPlugin plugin, EventBus eventBus) {
|
||||
Objects.requireNonNull(plugin, "plugin");
|
||||
Objects.requireNonNull(eventBus, "eventBus");
|
||||
AntiSpoofAPI api = new AntiSpoofAPI();
|
||||
api.pluginRef.set(plugin);
|
||||
api.snapshotCache.clear();
|
||||
api.registrations.add(eventBus.subscribe(ViolationReportedEvent.class, api::onViolationReported));
|
||||
api.registrations.add(eventBus.subscribe(IdentityAnomalyInternalEvent.class, api::onIdentityAnomalyDetected));
|
||||
INSTANCE = api;
|
||||
}
|
||||
|
||||
static void reset() {
|
||||
AntiSpoofAPI api = INSTANCE;
|
||||
if (api != null) {
|
||||
api.pluginRef.set(null);
|
||||
api.snapshotCache.clear();
|
||||
for (EventSubscription sub : new ArrayList<>(api.registrations)) {
|
||||
sub.close();
|
||||
}
|
||||
api.registrations.clear();
|
||||
}
|
||||
INSTANCE = null;
|
||||
}
|
||||
|
||||
public int getApiVersion() {
|
||||
return 4;
|
||||
}
|
||||
|
||||
public Optional<String> getClientBrand(Player player) {
|
||||
return player == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerBrand(player));
|
||||
}
|
||||
|
||||
public Optional<String> getClientBrand(UUID uniqueId) {
|
||||
return uniqueId == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerBrands().get(uniqueId));
|
||||
}
|
||||
|
||||
public Optional<String> getPlayerVersion(Player player) {
|
||||
return player == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerVersion(player));
|
||||
}
|
||||
|
||||
public Optional<String> getPlayerVersion(UUID uniqueId) {
|
||||
return uniqueId == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerVersions().get(uniqueId));
|
||||
}
|
||||
|
||||
public Optional<String> getLocale(Player player) {
|
||||
return player == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerLocale(player));
|
||||
}
|
||||
|
||||
public Optional<String> getLocale(UUID uniqueId) {
|
||||
return uniqueId == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerLocale(uniqueId));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getFlagReasons(Player player) {
|
||||
if (player == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
List<String> reasons = requirePlugin().getFlagReasons(player);
|
||||
return reasons != null && !reasons.isEmpty() ? Optional.of(List.copyOf(reasons)) : Optional.empty();
|
||||
}
|
||||
|
||||
public Optional<String> getFingerprint(UUID uniqueId) {
|
||||
if (uniqueId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
IdentityLinkerManager linker = requirePlugin().getIdentityLinkerManager();
|
||||
return linker == null ? Optional.empty() : linker.getFingerprint(uniqueId);
|
||||
}
|
||||
|
||||
public Optional<IdentitySnapshot> getIdentitySnapshot(Player player) {
|
||||
return player == null ? Optional.empty() : getIdentitySnapshot(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<IdentitySnapshot> getIdentitySnapshot(UUID uniqueId) {
|
||||
if (uniqueId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AntiSpoofPlugin plugin = requirePlugin();
|
||||
IdentityLinkerManager linker = plugin.getIdentityLinkerManager();
|
||||
if (linker == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<IdentityRecord> record = linker.getIdentityRecord(uniqueId);
|
||||
if (record.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String name = plugin.getServer().getOfflinePlayer(uniqueId).getName();
|
||||
IdentityRecord ir = record.get();
|
||||
return Optional.of(new IdentitySnapshot(uniqueId, name, ir.getAllAccounts(), ir.getAltAccounts()));
|
||||
}
|
||||
|
||||
public Optional<PlayerSnapshot> getPlayerSnapshot(UUID uniqueId) {
|
||||
if (uniqueId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
CachedSnapshot cached = snapshotCache.get(uniqueId);
|
||||
long now = System.nanoTime();
|
||||
if (cached != null && cached.expiresAt() >= now) {
|
||||
return Optional.of(cached.snapshot());
|
||||
}
|
||||
AntiSpoofPlugin plugin = requirePlugin();
|
||||
PlayerProfile profile = plugin.getPlayerProfiles().get(uniqueId);
|
||||
if (profile == null) {
|
||||
snapshotCache.remove(uniqueId);
|
||||
return Optional.empty();
|
||||
}
|
||||
PlayerSnapshot snap = buildSnapshot(plugin, uniqueId, profile);
|
||||
snapshotCache.put(uniqueId, new CachedSnapshot(snap, now + SNAPSHOT_CACHE_TTL_NANOS));
|
||||
return Optional.of(snap);
|
||||
}
|
||||
|
||||
public Optional<PlayerSnapshot> getPlayerSnapshot(Player player) {
|
||||
return player == null ? Optional.empty() : getPlayerSnapshot(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<ProxySnapshot> getProxySnapshot(Player player) {
|
||||
return player == null ? Optional.empty() : getProxySnapshot(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<ProxySnapshot> getProxySnapshot(UUID uniqueId) {
|
||||
if (uniqueId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AntiSpoofPlugin plugin = requirePlugin();
|
||||
PlayerProfile profile = plugin.getPlayerProfiles().get(uniqueId);
|
||||
return profile == null ? Optional.empty() : Optional.ofNullable(buildProxySnapshot(plugin, profile));
|
||||
}
|
||||
|
||||
public Optional<String> getProxyStatus(UUID uniqueId) {
|
||||
return getProxySnapshot(uniqueId).map(ProxySnapshot::status);
|
||||
}
|
||||
|
||||
public Optional<String> getProxyStatus(Player player) {
|
||||
return player == null ? Optional.empty() : getProxyStatus(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getChannels(Player player) {
|
||||
return player == null ? Optional.empty() : getChannels(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getChannels(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getChannels()));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getAllChannels(Player player) {
|
||||
return player == null ? Optional.empty() : getAllChannels(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getAllChannels(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getAllChannels()));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getFilteredChannels(Player player) {
|
||||
return player == null ? Optional.empty() : getFilteredChannels(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getFilteredChannels(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getFilteredChannels()));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getDetectedMods(Player player) {
|
||||
return player == null ? Optional.empty() : getDetectedMods(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getDetectedMods(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getDetectedMods()));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getAlertedMods(Player player) {
|
||||
return player == null ? Optional.empty() : getAlertedMods(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getAlertedMods(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getAlertedMods()));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getAlertedKeys(Player player) {
|
||||
return player == null ? Optional.empty() : getAlertedKeys(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getAlertedKeys(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getAlertedKeys()));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getAlertedCombinations(Player player) {
|
||||
return player == null ? Optional.empty() : getAlertedCombinations(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getAlertedCombinations(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getAlertedCombinations()));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getViolations(Player player) {
|
||||
return player == null ? Optional.empty() : getViolations(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getViolations(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getViolations()));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getSessionViolations(Player player) {
|
||||
return player == null ? Optional.empty() : getSessionViolations(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getSessionViolations(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getSessionViolations()));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getLastTranslatedKeys(Player player) {
|
||||
return player == null ? Optional.empty() : getLastTranslatedKeys(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getLastTranslatedKeys(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getLastTranslatedKeys()));
|
||||
}
|
||||
|
||||
public Optional<List<String>> getLastMissingKeys(Player player) {
|
||||
return player == null ? Optional.empty() : getLastMissingKeys(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<List<String>> getLastMissingKeys(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> copyStrings(p.getLastMissingKeys()));
|
||||
}
|
||||
|
||||
public Optional<ProbeStatus> getProbeStatus(Player player) {
|
||||
return player == null ? Optional.empty() : getProbeStatus(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<ProbeStatus> getProbeStatus(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(PlayerProfile::getProbeStatus);
|
||||
}
|
||||
|
||||
public Optional<Boolean> isAlreadyPunished(Player player) {
|
||||
return player == null ? Optional.empty() : isAlreadyPunished(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<Boolean> isAlreadyPunished(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(PlayerProfile::isAlreadyPunished);
|
||||
}
|
||||
|
||||
public Optional<Boolean> isInitialChannelsRegistered(Player player) {
|
||||
return player == null ? Optional.empty() : isInitialChannelsRegistered(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<Boolean> isInitialChannelsRegistered(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(PlayerProfile::isInitialChannelsRegistered);
|
||||
}
|
||||
|
||||
public Optional<Instant> getJoinTime(Player player) {
|
||||
return player == null ? Optional.empty() : getJoinTime(player.getUniqueId());
|
||||
}
|
||||
|
||||
public Optional<Instant> getJoinTime(UUID uniqueId) {
|
||||
return getProfile(uniqueId).map(p -> Instant.ofEpochMilli(p.getJoinTimeMillis()));
|
||||
}
|
||||
|
||||
public boolean isBedrock(Player player) {
|
||||
return player != null && requirePlugin().isBedrock(player);
|
||||
}
|
||||
|
||||
public Optional<Boolean> isBedrock(UUID uniqueId) {
|
||||
if (uniqueId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AntiSpoofPlugin plugin = requirePlugin();
|
||||
Player player = plugin.getServer().getPlayer(uniqueId);
|
||||
return player == null ? Optional.empty() : Optional.of(plugin.isBedrock(player));
|
||||
}
|
||||
|
||||
public Optional<String> getOperatingSystem(UUID uniqueId) {
|
||||
if (uniqueId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AntiSpoofPlugin plugin = requirePlugin();
|
||||
OsDetectorService osService = plugin.getOsDetectorService();
|
||||
if (osService == null || !osService.isEnabled()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
OsInfo info = plugin.getOsInfo(uniqueId);
|
||||
return info == null ? Optional.empty() : Optional.ofNullable(info.getOsName());
|
||||
}
|
||||
|
||||
public Optional<String> getOperatingSystem(Player player) {
|
||||
if (player == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
OsDetectorService osService = requirePlugin().getOsDetectorService();
|
||||
return osService != null && osService.isEnabled()
|
||||
? osService.detectOs(player).map(OsInfo::getOsName)
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
public Optional<OsInfo> getOperatingSystemInfo(UUID uniqueId) {
|
||||
if (uniqueId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AntiSpoofPlugin plugin = requirePlugin();
|
||||
OsDetectorService osService = plugin.getOsDetectorService();
|
||||
return osService != null && osService.isEnabled()
|
||||
? Optional.ofNullable(plugin.getOsInfo(uniqueId))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
public Optional<OsInfo> getOperatingSystemInfo(Player player) {
|
||||
if (player == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
OsDetectorService osService = requirePlugin().getOsDetectorService();
|
||||
return osService != null && osService.isEnabled()
|
||||
? osService.detectOs(player)
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
public void addViolation(Player player, String sourcePlugin, String reason) {
|
||||
Objects.requireNonNull(player, "player");
|
||||
Objects.requireNonNull(sourcePlugin, "sourcePlugin");
|
||||
Objects.requireNonNull(reason, "reason");
|
||||
String src = sanitize(sourcePlugin);
|
||||
String rsn = sanitize(reason);
|
||||
if (src.isEmpty() || rsn.isEmpty()) {
|
||||
throw new IllegalArgumentException("sourcePlugin and reason must not be blank");
|
||||
}
|
||||
requirePlugin().reportExternalViolation(player, src, rsn);
|
||||
}
|
||||
|
||||
public void setBypassed(Player player, boolean bypassed, long durationMillis) {
|
||||
Objects.requireNonNull(player, "player");
|
||||
requirePlugin().setBypassed(player.getUniqueId(), bypassed, durationMillis);
|
||||
}
|
||||
|
||||
public CompletableFuture<Integer> getHistoricalViolationCount(UUID uniqueId) {
|
||||
return uniqueId == null ? CompletableFuture.completedFuture(0) : requirePlugin().getHistoricalViolationCount(uniqueId);
|
||||
}
|
||||
|
||||
public Set<String> getKnownViolationTypes() {
|
||||
ConfigManager cfg = requirePlugin().getConfigManager();
|
||||
return cfg == null ? Set.of() : cfg.getKnownViolationTypes();
|
||||
}
|
||||
|
||||
public boolean isBypassed(UUID uniqueId) {
|
||||
return uniqueId != null && requirePlugin().isBypassed(uniqueId);
|
||||
}
|
||||
|
||||
public Optional<Long> getThreatLevel(UUID uniqueId) {
|
||||
return uniqueId == null ? Optional.empty() : requirePlugin().getThreatLevel(uniqueId);
|
||||
}
|
||||
|
||||
public void resetThreatLevel(Player moderator, UUID target, String reason) {
|
||||
Objects.requireNonNull(moderator, "moderator");
|
||||
Objects.requireNonNull(target, "target");
|
||||
String rsn = sanitize(reason);
|
||||
if (rsn.isEmpty()) {
|
||||
throw new IllegalArgumentException("reason must not be blank");
|
||||
}
|
||||
requirePlugin().resetThreatLevel(moderator, target, rsn);
|
||||
}
|
||||
|
||||
public void modifyThreatLevel(Player moderator, UUID target, int delta, String reason) {
|
||||
Objects.requireNonNull(moderator, "moderator");
|
||||
Objects.requireNonNull(target, "target");
|
||||
String rsn = sanitize(reason);
|
||||
if (rsn.isEmpty()) {
|
||||
throw new IllegalArgumentException("reason must not be blank");
|
||||
}
|
||||
requirePlugin().modifyThreatLevel(moderator, target, delta, rsn);
|
||||
}
|
||||
|
||||
private void onViolationReported(ViolationReportedEvent event) {
|
||||
Optional<PlayerSnapshot> snap = getPlayerSnapshot(event.getPlayer().getUniqueId());
|
||||
Bukkit.getPluginManager().callEvent(new AntiSpoofViolationEvent(
|
||||
event.getPlayer(),
|
||||
event.getViolationType(),
|
||||
event.getReason(),
|
||||
event.getBrand(),
|
||||
snap.orElse(null)
|
||||
));
|
||||
}
|
||||
|
||||
private void onIdentityAnomalyDetected(IdentityAnomalyInternalEvent event) {
|
||||
Bukkit.getPluginManager().callEvent(new IdentityAnomalyEvent(
|
||||
event.getPlayer(),
|
||||
event.getType(),
|
||||
event.getDescription(),
|
||||
event.getContext()
|
||||
));
|
||||
}
|
||||
|
||||
private PlayerSnapshot buildSnapshot(AntiSpoofPlugin plugin, UUID uniqueId, PlayerProfile profile) {
|
||||
List<String> channels = List.copyOf(new ArrayList<>(profile.getChannels()));
|
||||
List<String> detectedMods = List.copyOf(new ArrayList<>(profile.getDetectedMods()));
|
||||
List<String> violations = List.copyOf(new ArrayList<>(profile.getViolations()));
|
||||
List<String> filteredChannels = List.copyOf(new ArrayList<>(profile.getFilteredChannels()));
|
||||
|
||||
Player online = plugin.getServer().getPlayer(uniqueId);
|
||||
OfflinePlayer offline = online != null ? online : plugin.getServer().getOfflinePlayer(uniqueId);
|
||||
String name = offline != null ? offline.getName() : null;
|
||||
|
||||
String brand = plugin.getPlayerBrands().get(uniqueId);
|
||||
String version = plugin.getPlayerVersions().get(uniqueId);
|
||||
String locale = plugin.getPlayerLocales().get(uniqueId);
|
||||
OsInfo osInfo = plugin.getOsInfo(uniqueId);
|
||||
String osName = osInfo != null ? osInfo.getOsName() : null;
|
||||
|
||||
ProxySnapshot proxy = buildProxySnapshot(plugin, profile);
|
||||
return new PlayerSnapshot(
|
||||
uniqueId,
|
||||
name,
|
||||
brand,
|
||||
version,
|
||||
locale,
|
||||
osName,
|
||||
channels,
|
||||
filteredChannels,
|
||||
detectedMods,
|
||||
violations,
|
||||
proxy,
|
||||
profile.isAlreadyPunished(),
|
||||
Instant.ofEpochMilli(profile.getJoinTimeMillis())
|
||||
);
|
||||
}
|
||||
|
||||
private ProxySnapshot buildProxySnapshot(AntiSpoofPlugin plugin, PlayerProfile profile) {
|
||||
if (plugin == null || profile == null) {
|
||||
return null;
|
||||
}
|
||||
ProxyDetectionManager proxyMgr = plugin.getProxyDetectionManager();
|
||||
if (proxyMgr == null) {
|
||||
return null;
|
||||
}
|
||||
ConfigManager cfg = plugin.getConfigManager();
|
||||
int window = cfg != null ? cfg.getProxySampleWindow() : 0;
|
||||
ProxyMetrics metrics = profile.getProxyState().snapshot(window);
|
||||
ProxyEvaluation eval = proxyMgr.evaluate(metrics);
|
||||
return toProxySnapshot(eval);
|
||||
}
|
||||
|
||||
private ProxySnapshot toProxySnapshot(ProxyEvaluation eval) {
|
||||
if (eval == null) {
|
||||
return null;
|
||||
}
|
||||
ProxyMetrics m = eval.metrics();
|
||||
String status = eval.status();
|
||||
String statusLabel = ProxyDetectionManager.formatStatusLabel(status);
|
||||
if (m == null) {
|
||||
return new ProxySnapshot(
|
||||
eval.enabled(),
|
||||
eval.snifferActive(),
|
||||
status,
|
||||
statusLabel,
|
||||
eval.minSamples(),
|
||||
eval.warnThresholdMs(),
|
||||
eval.thresholdMs(),
|
||||
false,
|
||||
false,
|
||||
eval.suspected(),
|
||||
eval.warning(),
|
||||
0L,
|
||||
0L,
|
||||
null,
|
||||
0L,
|
||||
0.0,
|
||||
0L,
|
||||
0L,
|
||||
0,
|
||||
0L,
|
||||
List.of(),
|
||||
List.of(),
|
||||
List.of()
|
||||
);
|
||||
}
|
||||
return new ProxySnapshot(
|
||||
eval.enabled(),
|
||||
eval.snifferActive(),
|
||||
status,
|
||||
statusLabel,
|
||||
eval.minSamples(),
|
||||
eval.warnThresholdMs(),
|
||||
eval.thresholdMs(),
|
||||
m.handshakeRttMs() > 0L,
|
||||
m.sampleCount() >= eval.minSamples(),
|
||||
eval.suspected(),
|
||||
eval.warning(),
|
||||
m.handshakeRttMs(),
|
||||
m.lastPingMs(),
|
||||
m.lastPingSource(),
|
||||
m.lastDiffMs(),
|
||||
m.averageDiffMs(),
|
||||
m.minDiffMs(),
|
||||
m.maxDiffMs(),
|
||||
m.sampleCount(),
|
||||
m.lastSampleAt(),
|
||||
m.recentDiffs() == null ? List.of() : List.copyOf(m.recentDiffs()),
|
||||
m.recentPings() == null ? List.of() : List.copyOf(m.recentPings()),
|
||||
m.recentHandshakeRtts() == null ? List.of() : List.copyOf(m.recentHandshakeRtts())
|
||||
);
|
||||
}
|
||||
|
||||
private Optional<PlayerProfile> getProfile(UUID uniqueId) {
|
||||
return uniqueId == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerProfiles().get(uniqueId));
|
||||
}
|
||||
|
||||
private static List<String> copyStrings(Iterable<String> src) {
|
||||
if (src == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> out = new ArrayList<>();
|
||||
for (String s : src) {
|
||||
if (s != null) {
|
||||
out.add(s);
|
||||
}
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
private AntiSpoofPlugin requirePlugin() {
|
||||
AntiSpoofPlugin plugin = pluginRef.get();
|
||||
if (plugin == null) {
|
||||
throw new IllegalStateException("AntiSpoofAPI has not been initialized yet");
|
||||
}
|
||||
return plugin;
|
||||
}
|
||||
|
||||
private static String sanitize(String input) {
|
||||
if (input == null) {
|
||||
return "";
|
||||
}
|
||||
String trimmed = input.trim();
|
||||
if (trimmed.length() > 256) {
|
||||
trimmed = trimmed.substring(0, 256);
|
||||
}
|
||||
return trimmed.replaceAll("[\\r\\n]+", " ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.gigazelensky.antispoof.api;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.EventBus;
|
||||
|
||||
public final class ApiLifecycle {
|
||||
private ApiLifecycle() {
|
||||
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
|
||||
}
|
||||
|
||||
public static void initialize(AntiSpoofPlugin plugin, EventBus eventBus) {
|
||||
AntiSpoofAPI.initialize(plugin, eventBus);
|
||||
}
|
||||
|
||||
public static void reset() {
|
||||
AntiSpoofAPI.reset();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.gigazelensky.antispoof.api;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public record IdentitySnapshot(
|
||||
UUID target,
|
||||
String targetName,
|
||||
List<String> allAccounts,
|
||||
List<String> altAccounts
|
||||
) {
|
||||
public IdentitySnapshot {
|
||||
Objects.requireNonNull(target, "target");
|
||||
allAccounts = allAccounts == null ? List.of() : List.copyOf(allAccounts);
|
||||
altAccounts = altAccounts == null ? List.of() : List.copyOf(altAccounts);
|
||||
}
|
||||
|
||||
public int accountCount() {
|
||||
return allAccounts.size();
|
||||
}
|
||||
|
||||
public int altCount() {
|
||||
return altAccounts.size();
|
||||
}
|
||||
|
||||
public boolean hasAlts() {
|
||||
return !altAccounts.isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.gigazelensky.antispoof.api;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record PlayerSnapshot(
|
||||
UUID uniqueId,
|
||||
String name,
|
||||
String clientBrand,
|
||||
String clientVersion,
|
||||
String locale,
|
||||
String operatingSystem,
|
||||
List<String> channels,
|
||||
List<String> filteredChannels,
|
||||
List<String> detectedMods,
|
||||
List<String> violations,
|
||||
ProxySnapshot proxy,
|
||||
boolean alreadyPunished,
|
||||
Instant joinTime
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.gigazelensky.antispoof.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record ProxySnapshot(
|
||||
boolean enabled,
|
||||
boolean snifferActive,
|
||||
String status,
|
||||
String statusLabel,
|
||||
int minSamples,
|
||||
int warnThresholdMs,
|
||||
int thresholdMs,
|
||||
boolean hasHandshake,
|
||||
boolean hasEnoughSamples,
|
||||
boolean suspected,
|
||||
boolean warning,
|
||||
long handshakeRttMs,
|
||||
long lastPingMs,
|
||||
String lastPingSource,
|
||||
long lastDiffMs,
|
||||
double averageDiffMs,
|
||||
long minDiffMs,
|
||||
long maxDiffMs,
|
||||
int sampleCount,
|
||||
long lastSampleAt,
|
||||
List<Long> recentDiffs,
|
||||
List<Long> recentPings,
|
||||
List<Long> recentHandshakeRtts
|
||||
) {
|
||||
public ProxySnapshot {
|
||||
recentDiffs = recentDiffs == null ? List.of() : List.copyOf(recentDiffs);
|
||||
recentPings = recentPings == null ? List.of() : List.copyOf(recentPings);
|
||||
recentHandshakeRtts = recentHandshakeRtts == null ? List.of() : List.copyOf(recentHandshakeRtts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.gigazelensky.antispoof.api.events;
|
||||
|
||||
import java.util.Objects;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public final class AntiSpoofPrePunishmentEvent extends Event implements Cancellable {
|
||||
private static final HandlerList HANDLERS = new HandlerList();
|
||||
|
||||
private final Player player;
|
||||
private final PunishmentTier punishmentTier;
|
||||
private final long threatLevel;
|
||||
private boolean cancelled;
|
||||
|
||||
public AntiSpoofPrePunishmentEvent(Player player, PunishmentTier punishmentTier, long threatLevel) {
|
||||
super(!Bukkit.isPrimaryThread());
|
||||
this.player = Objects.requireNonNull(player, "player");
|
||||
this.punishmentTier = Objects.requireNonNull(punishmentTier, "punishmentTier");
|
||||
this.threatLevel = Math.max(0L, threatLevel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public PunishmentTier getPunishmentTier() {
|
||||
return punishmentTier;
|
||||
}
|
||||
|
||||
public long getThreatLevel() {
|
||||
return threatLevel;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCancelled(boolean cancel) {
|
||||
this.cancelled = cancel;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.gigazelensky.antispoof.api.events;
|
||||
|
||||
import com.gigazelensky.antispoof.api.PlayerSnapshot;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public final class AntiSpoofViolationEvent extends Event {
|
||||
private static final HandlerList HANDLERS = new HandlerList();
|
||||
|
||||
private final Player player;
|
||||
private final String violationType;
|
||||
private final String reason;
|
||||
private final String brand;
|
||||
private final PlayerSnapshot snapshot;
|
||||
|
||||
public AntiSpoofViolationEvent(
|
||||
Player player,
|
||||
String violationType,
|
||||
String reason,
|
||||
String brand,
|
||||
PlayerSnapshot snapshot
|
||||
) {
|
||||
super(!Bukkit.isPrimaryThread());
|
||||
this.player = Objects.requireNonNull(player, "player");
|
||||
this.violationType = Objects.requireNonNull(violationType, "violationType");
|
||||
this.reason = Objects.requireNonNull(reason, "reason");
|
||||
this.brand = brand;
|
||||
this.snapshot = snapshot;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public String getViolationType() {
|
||||
return violationType;
|
||||
}
|
||||
|
||||
public String getReason() {
|
||||
return reason;
|
||||
}
|
||||
|
||||
public Optional<String> getBrand() {
|
||||
return Optional.ofNullable(brand);
|
||||
}
|
||||
|
||||
public Optional<PlayerSnapshot> getSnapshot() {
|
||||
return Optional.ofNullable(snapshot);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLERS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.gigazelensky.antispoof.api.events;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public final class IdentityAnomalyEvent extends Event {
|
||||
private static final HandlerList HANDLERS = new HandlerList();
|
||||
|
||||
private final Player player;
|
||||
private final IdentityAnomalyType type;
|
||||
private final String description;
|
||||
private final Map<String, Object> context;
|
||||
|
||||
public IdentityAnomalyEvent(
|
||||
Player player,
|
||||
IdentityAnomalyType type,
|
||||
String description,
|
||||
Map<String, Object> context
|
||||
) {
|
||||
super(!Bukkit.isPrimaryThread());
|
||||
this.player = player;
|
||||
this.type = Objects.requireNonNull(type, "type");
|
||||
this.description = Objects.requireNonNull(description, "description");
|
||||
this.context = context == null ? Collections.emptyMap() : Collections.unmodifiableMap(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLERS;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public IdentityAnomalyType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public Map<String, Object> getContext() {
|
||||
return context;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.gigazelensky.antispoof.api.events;
|
||||
|
||||
public enum IdentityAnomalyType {
|
||||
HIDER_PACK_REJECTED,
|
||||
PROBE_COUNT_MISMATCH,
|
||||
RESOURCE_PACK_SPOOF
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.gigazelensky.antispoof.api.events;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record PunishmentTier(
|
||||
String violationType,
|
||||
List<String> commands,
|
||||
String reason,
|
||||
String brand,
|
||||
String violatedChannel
|
||||
) {
|
||||
public PunishmentTier {
|
||||
Objects.requireNonNull(violationType, "violationType");
|
||||
commands = commands == null ? List.of() : List.copyOf(commands);
|
||||
reason = reason == null ? "" : reason;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
package com.gigazelensky.antispoof.command;
|
||||
|
||||
import com.gigazelensky.antispoof.config.BrandRuleConfig;
|
||||
import com.gigazelensky.antispoof.config.ConfigManager;
|
||||
import com.gigazelensky.antispoof.config.ConfigToggleWriter;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.data.ClientPlatform;
|
||||
import com.gigazelensky.antispoof.data.LogEntry;
|
||||
import com.gigazelensky.antispoof.data.OsInfo;
|
||||
import com.gigazelensky.antispoof.data.PlayerProfile;
|
||||
import com.gigazelensky.antispoof.data.ProbeKeyType;
|
||||
import com.gigazelensky.antispoof.data.ProxyEvaluation;
|
||||
import com.gigazelensky.antispoof.data.ProxyMetrics;
|
||||
import com.gigazelensky.antispoof.gui.MainMenuGui;
|
||||
import com.gigazelensky.antispoof.probe.ProxyDetectionManager;
|
||||
import com.gigazelensky.antispoof.util.TextUtil;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandExecutor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.TabCompleter;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Complete /antispoof command handler implementing all 27 subcommands and tab completion
|
||||
* (reconstructed from lIllllllllIIIlI).
|
||||
*/
|
||||
public final class AntiSpoofCommand implements CommandExecutor, TabCompleter {
|
||||
private static final int HELP_PAGE_SIZE = 8;
|
||||
private static final DateTimeFormatter LOG_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").withZone(ZoneId.systemDefault());
|
||||
|
||||
public record SubcommandHelp(String usage, String description) {
|
||||
}
|
||||
|
||||
private static final List<SubcommandHelp> SUBCOMMANDS = List.of(
|
||||
new SubcommandHelp("gui", "Open the management GUI"),
|
||||
new SubcommandHelp("alerts", "Toggle your in-game staff alerts"),
|
||||
new SubcommandHelp("alerts consistent [on|off]", "Choose whether alert preferences persist between joins"),
|
||||
new SubcommandHelp("guard [status|on|off]", "View or toggle surge guard"),
|
||||
new SubcommandHelp("channels <player>", "Show player's plugin channels"),
|
||||
new SubcommandHelp("brand <player>", "Show player's client brand"),
|
||||
new SubcommandHelp("host <player>", "Show the hostname:port used by a player"),
|
||||
new SubcommandHelp("os <player>", "Show the player's detected OS"),
|
||||
new SubcommandHelp("mods <player>", "Show detected mods for a player"),
|
||||
new SubcommandHelp("translate <player> <key>", "Send a translate test key"),
|
||||
new SubcommandHelp("keybind <player> <key>", "Send a keybind test to a player"),
|
||||
new SubcommandHelp("keyspoof [player]", "Run Server RP Custom Key Spoof probe"),
|
||||
new SubcommandHelp("assetlab [player]", "Run 6-pack differential Asset Probe lab"),
|
||||
new SubcommandHelp("check [player|*]", "Check if player is spoofing"),
|
||||
new SubcommandHelp("proxy [player]", "Check proxy/VPN heuristic for a player"),
|
||||
new SubcommandHelp("runcheck [player|*]", "Re-run checks on player(s)"),
|
||||
new SubcommandHelp("runmods [player|*]", "Re-run mod probes on player(s)"),
|
||||
new SubcommandHelp("runbook [player|*]", "Run command-book probes on player(s)"),
|
||||
new SubcommandHelp("stopmods [player|*]", "Stop pending mod probes for player(s)"),
|
||||
new SubcommandHelp("verify <player> <label>", "Verify keys for a mod label"),
|
||||
new SubcommandHelp("search <mod>", "List online players with a detected mod"),
|
||||
new SubcommandHelp("client <lunar|feather|badlion|labymod> [player|list|refresh|search]", "Inspect supported client data"),
|
||||
new SubcommandHelp("logs [player]", "View player logs or list players"),
|
||||
new SubcommandHelp("listchannels", "Show channel configuration"),
|
||||
new SubcommandHelp("listbrands", "Show configured brands"),
|
||||
new SubcommandHelp("reload", "Reload the plugin configuration"),
|
||||
new SubcommandHelp("config reset [<file>|section <path>]", "Reset config file(s) to defaults"),
|
||||
new SubcommandHelp("config update [all|mods|brands|channels|section <path>|<path>]", "Merge missing defaults without overwriting edits"),
|
||||
new SubcommandHelp("help [page]", "Show this help message")
|
||||
);
|
||||
|
||||
private static final List<String> ROOT_SUBS = List.of(
|
||||
"gui", "alerts", "guard", "channels", "brand", "host", "os", "mods",
|
||||
"translate", "keybind", "keyspoof", "assetlab", "check", "proxy", "runcheck", "runmods", "runbook",
|
||||
"stopmods", "verify", "search", "client", "logs", "listchannels", "listbrands",
|
||||
"reload", "config", "help"
|
||||
);
|
||||
|
||||
private final AntiSpoofPlugin plugin;
|
||||
|
||||
public AntiSpoofCommand(AntiSpoofPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
|
||||
if (!sender.hasPermission("antispoof.admin") && !sender.hasPermission("antispoof.staff")) {
|
||||
send(sender, "%prefix% &cYou do not have permission to use this command.");
|
||||
return true;
|
||||
}
|
||||
if (args.length == 0) {
|
||||
sendHelp(sender, label, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
String sub = args[0].toLowerCase(Locale.ROOT);
|
||||
switch (sub) {
|
||||
case "help" -> {
|
||||
int page = args.length >= 2 ? parseInt(args[1], 1) : 1;
|
||||
sendHelp(sender, label, page);
|
||||
}
|
||||
case "gui" -> handleGui(sender);
|
||||
case "alerts" -> handleAlerts(sender, label, args);
|
||||
case "guard" -> handleGuard(sender, args);
|
||||
case "channels" -> handleChannels(sender, args);
|
||||
case "brand" -> handleBrand(sender, args);
|
||||
case "host" -> handleHost(sender, args);
|
||||
case "os" -> handleOs(sender, args);
|
||||
case "mods" -> handleMods(sender, args);
|
||||
case "translate" -> handleKeyProbe(sender, args, ProbeKeyType.TRANSLATE);
|
||||
case "keybind" -> handleKeyProbe(sender, args, ProbeKeyType.KEYBIND);
|
||||
case "keyspoof" -> handleKeySpoofProbe(sender, args);
|
||||
case "assetlab" -> handleAssetLab(sender, args);
|
||||
case "check" -> handleCheck(sender, args);
|
||||
case "proxy" -> handleProxy(sender, args);
|
||||
case "runcheck" -> handleRunCheck(sender, args);
|
||||
case "runmods" -> handleRunMods(sender, args);
|
||||
case "runbook" -> handleRunBook(sender, args);
|
||||
case "stopmods" -> handleStopMods(sender, args);
|
||||
case "verify" -> handleVerify(sender, args);
|
||||
case "search" -> handleSearch(sender, args);
|
||||
case "client" -> handleClient(sender, args);
|
||||
case "logs" -> handleLogs(sender, args);
|
||||
case "listchannels" -> handleListChannels(sender);
|
||||
case "listbrands" -> handleListBrands(sender);
|
||||
case "reload" -> handleReload(sender);
|
||||
case "config" -> handleConfig(sender, args);
|
||||
default -> {
|
||||
send(sender, "%prefix% &cUnknown subcommand: &f" + args[0] + "&c. Use /" + label + " help");
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void handleGui(CommandSender sender) {
|
||||
if (!(sender instanceof Player player)) {
|
||||
send(sender, "%prefix% &cOnly players can open the GUI.");
|
||||
return;
|
||||
}
|
||||
if (!player.hasPermission("antispoof.gui") && !player.hasPermission("antispoof.admin")) {
|
||||
send(sender, "%prefix% &cYou don't have permission to open the GUI.");
|
||||
return;
|
||||
}
|
||||
new MainMenuGui(plugin, player).open();
|
||||
}
|
||||
|
||||
private void handleAlerts(CommandSender sender, String label, String[] args) {
|
||||
if (args.length >= 2 && "consistent".equalsIgnoreCase(args[1])) {
|
||||
if (!sender.hasPermission("antispoof.admin")) {
|
||||
send(sender, "%prefix% &cYou need antispoof.admin to change alert persistence.");
|
||||
return;
|
||||
}
|
||||
boolean next = args.length >= 3
|
||||
? ("on".equalsIgnoreCase(args[2]) || "true".equalsIgnoreCase(args[2]))
|
||||
: !plugin.getConfigManager().isAlertsConsistent();
|
||||
ConfigToggleWriter.setValue(plugin.getConfigManager().getConfigFile(), "alerts.consistent", next, plugin.getLogger());
|
||||
plugin.getConfigManager().reload();
|
||||
send(sender, next ? ConfigManager.DEFAULT_ALERTS_PERSIST_ON : ConfigManager.DEFAULT_ALERTS_PERSIST_OFF);
|
||||
return;
|
||||
}
|
||||
if (!(sender instanceof Player player)) {
|
||||
send(sender, "%prefix% &cOnly players can toggle in-game alerts.");
|
||||
return;
|
||||
}
|
||||
boolean enabled = plugin.toggleStaffAlerts(player.getUniqueId());
|
||||
String msg = (enabled ? ConfigManager.DEFAULT_ALERTS_ENABLED : ConfigManager.DEFAULT_ALERTS_DISABLED)
|
||||
.replace("%command%", label);
|
||||
send(sender, msg);
|
||||
}
|
||||
|
||||
private void handleGuard(CommandSender sender, String[] args) {
|
||||
var sg = plugin.getSurgeGuardManager();
|
||||
if (args.length < 2 || "status".equalsIgnoreCase(args[1])) {
|
||||
send(sender, "%prefix% &7Surge Guard: " + (sg.isSurgeActive() ? "&cACTIVE" : "&aIDLE")
|
||||
+ " &8| &7Joins/window: &f" + sg.getRecentJoinCount()
|
||||
+ " &8| &7Action: &f" + sg.getAction().name());
|
||||
return;
|
||||
}
|
||||
if ("on".equalsIgnoreCase(args[1])) {
|
||||
sg.setManualOverride(Boolean.TRUE);
|
||||
send(sender, "%prefix% &eSurge Guard manually enabled.");
|
||||
} else if ("off".equalsIgnoreCase(args[1])) {
|
||||
sg.setManualOverride(Boolean.FALSE);
|
||||
send(sender, "%prefix% &aSurge Guard manually disabled.");
|
||||
} else if ("auto".equalsIgnoreCase(args[1])) {
|
||||
sg.setManualOverride(null);
|
||||
send(sender, "%prefix% &aSurge Guard returned to automatic mode.");
|
||||
} else {
|
||||
send(sender, "%prefix% &eUsage: /antispoof guard [status|on|off|auto]");
|
||||
}
|
||||
}
|
||||
|
||||
private void handleChannels(CommandSender sender, String[] args) {
|
||||
Player target = requirePlayer(sender, args, 1, "channels <player>");
|
||||
if (target == null) return;
|
||||
PlayerProfile profile = plugin.getPlayerProfiles().get(target.getUniqueId());
|
||||
Set<String> channels = profile == null ? Set.of() : profile.getChannels();
|
||||
send(sender, "%prefix% &f" + target.getName() + "&7's channels (&f" + channels.size() + "&7): &b"
|
||||
+ (channels.isEmpty() ? "None" : String.join(", ", channels)));
|
||||
}
|
||||
|
||||
private void handleBrand(CommandSender sender, String[] args) {
|
||||
Player target = requirePlayer(sender, args, 1, "brand <player>");
|
||||
if (target == null) return;
|
||||
String brand = plugin.getPlayerBrand(target);
|
||||
String ver = plugin.getPlayerVersion(target);
|
||||
send(sender, "%prefix% &f" + target.getName() + "&7 brand: &b" + (brand == null ? "Unknown" : brand)
|
||||
+ " &8(&7v" + (ver == null ? "?" : ver) + "&8)");
|
||||
}
|
||||
|
||||
private void handleHost(CommandSender sender, String[] args) {
|
||||
Player target = requirePlayer(sender, args, 1, "host <player>");
|
||||
if (target == null) return;
|
||||
PlayerProfile profile = plugin.getPlayerProfiles().get(target.getUniqueId());
|
||||
String host = profile != null && profile.getVirtualHost() != null ? profile.getVirtualHost() : "Unknown";
|
||||
send(sender, "%prefix% &f" + target.getName() + "&7 virtual host: &b" + host);
|
||||
}
|
||||
|
||||
private void handleOs(CommandSender sender, String[] args) {
|
||||
Player target = requirePlayer(sender, args, 1, "os <player>");
|
||||
if (target == null) return;
|
||||
OsInfo info = plugin.getOsDetectorService().detectOs(target).orElse(null);
|
||||
if (info == null) {
|
||||
send(sender, "%prefix% &f" + target.getName() + "&7 OS: &eUnknown");
|
||||
} else {
|
||||
send(sender, "%prefix% &f" + target.getName() + "&7 OS: &b" + info.getOsName()
|
||||
+ String.format(Locale.ROOT, " &8(&7%.0f%% via %s&8)", info.getConfidence() * 100.0, info.getSource()));
|
||||
}
|
||||
}
|
||||
|
||||
private void handleMods(CommandSender sender, String[] args) {
|
||||
Player target = requirePlayer(sender, args, 1, "mods <player>");
|
||||
if (target == null) return;
|
||||
PlayerProfile profile = plugin.getPlayerProfiles().get(target.getUniqueId());
|
||||
Set<String> mods = profile == null ? Set.of() : profile.getDetectedMods();
|
||||
send(sender, "%prefix% &f" + target.getName() + "&7 detected mods (&f" + mods.size() + "&7): &e"
|
||||
+ (mods.isEmpty() ? "None" : String.join(", ", mods)));
|
||||
}
|
||||
|
||||
private void handleKeyProbe(CommandSender sender, String[] args, ProbeKeyType type) {
|
||||
if (args.length < 3) {
|
||||
send(sender, "%prefix% &eUsage: /antispoof " + args[0] + " <player> <key>");
|
||||
return;
|
||||
}
|
||||
Player target = Bukkit.getPlayerExact(args[1]);
|
||||
if (target == null) {
|
||||
send(sender, "%prefix% &cPlayer not found: &f" + args[1]);
|
||||
return;
|
||||
}
|
||||
plugin.getTranslationProbeManager().sendSingleKeyProbe(target, args[2], type, sender);
|
||||
send(sender, "%prefix% &7Sent " + type.name().toLowerCase(Locale.ROOT) + " probe &f" + args[2] + " &7to &f" + target.getName());
|
||||
}
|
||||
|
||||
private void handleCheck(CommandSender sender, String[] args) {
|
||||
Collection<Player> targets = resolveTargetOrAll(sender, args, 1);
|
||||
for (Player p : targets) {
|
||||
PlayerProfile profile = plugin.getPlayerProfiles().get(p.getUniqueId());
|
||||
String brand = plugin.getPlayerBrand(p);
|
||||
int vCount = profile == null ? 0 : profile.getViolations().size();
|
||||
long threat = profile == null ? 0L : profile.getThreatLevel();
|
||||
send(sender, "%prefix% &f" + p.getName() + " &8| &7Brand: &b" + (brand == null ? "Unknown" : brand)
|
||||
+ " &8| &7Flags: " + (vCount > 0 ? "&c" + vCount : "&a0")
|
||||
+ " &8| &7Threat: &e" + threat);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleProxy(CommandSender sender, String[] args) {
|
||||
Player target = args.length >= 2 ? Bukkit.getPlayerExact(args[1]) : (sender instanceof Player p ? p : null);
|
||||
if (target == null) {
|
||||
send(sender, "%prefix% &cPlayer not found.");
|
||||
return;
|
||||
}
|
||||
PlayerProfile profile = plugin.getPlayerProfiles().get(target.getUniqueId());
|
||||
if (profile == null) {
|
||||
send(sender, "%prefix% &eNo profile data for &f" + target.getName());
|
||||
return;
|
||||
}
|
||||
ProxyMetrics m = profile.getProxyState().snapshot(plugin.getConfigManager().getProxySampleWindow());
|
||||
ProxyEvaluation ev = plugin.getProxyDetectionManager().evaluate(m);
|
||||
send(sender, "%prefix% &f" + target.getName() + " &7Proxy status: &b" + ProxyDetectionManager.formatStatusLabel(ev.status())
|
||||
+ String.format(Locale.ROOT, " &8| &7Handshake: &f%dms &8| &7Ping: &f%dms &8| &7AvgDiff: &f%.1fms (%d samples)",
|
||||
m.handshakeRttMs(), m.lastPingMs(), m.averageDiffMs(), m.sampleCount()));
|
||||
}
|
||||
|
||||
private void handleRunCheck(CommandSender sender, String[] args) {
|
||||
Collection<Player> targets = resolveTargetOrAll(sender, args, 1);
|
||||
for (Player p : targets) {
|
||||
plugin.getBrandChannelListener().evaluatePlayerChecks(p);
|
||||
}
|
||||
send(sender, "%prefix% &aRe-ran brand/channel checks on &f" + targets.size() + " &aplayer(s).");
|
||||
}
|
||||
|
||||
private void handleRunMods(CommandSender sender, String[] args) {
|
||||
Collection<Player> targets = resolveTargetOrAll(sender, args, 1);
|
||||
for (Player p : targets) {
|
||||
plugin.getTranslationProbeManager().runAllModProbes(p, sender);
|
||||
}
|
||||
send(sender, "%prefix% &aStarted mod probes for &f" + targets.size() + " &aplayer(s).");
|
||||
}
|
||||
|
||||
private void handleRunBook(CommandSender sender, String[] args) {
|
||||
Collection<Player> targets = resolveTargetOrAll(sender, args, 1);
|
||||
for (Player p : targets) {
|
||||
plugin.getCommandBookProbeManager().runBookProbe(p, sender);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleStopMods(CommandSender sender, String[] args) {
|
||||
Collection<Player> targets = resolveTargetOrAll(sender, args, 1);
|
||||
for (Player p : targets) {
|
||||
plugin.getTranslationProbeManager().stopProbes(p.getUniqueId());
|
||||
}
|
||||
send(sender, "%prefix% &eStopped pending mod probes for &f" + targets.size() + " &eplayer(s).");
|
||||
}
|
||||
|
||||
private void handleVerify(CommandSender sender, String[] args) {
|
||||
if (args.length < 3) {
|
||||
send(sender, "%prefix% &eUsage: /antispoof verify <player> <label>");
|
||||
return;
|
||||
}
|
||||
Player target = Bukkit.getPlayerExact(args[1]);
|
||||
if (target == null) {
|
||||
send(sender, "%prefix% &cPlayer not found: &f" + args[1]);
|
||||
return;
|
||||
}
|
||||
plugin.getTranslationProbeManager().verifyModLabel(target, args[2], sender);
|
||||
}
|
||||
|
||||
private void handleSearch(CommandSender sender, String[] args) {
|
||||
if (args.length < 2) {
|
||||
send(sender, "%prefix% &eUsage: /antispoof search <mod>");
|
||||
return;
|
||||
}
|
||||
String query = args[1].toLowerCase(Locale.ROOT);
|
||||
List<String> matches = new ArrayList<>();
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
PlayerProfile prof = plugin.getPlayerProfiles().get(p.getUniqueId());
|
||||
if (prof == null) continue;
|
||||
for (String m : prof.getDetectedMods()) {
|
||||
if (m.toLowerCase(Locale.ROOT).contains(query)) {
|
||||
matches.add(p.getName() + " (" + m + ")");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
send(sender, "%prefix% &7Players matching mod '&f" + args[1] + "&7': &e"
|
||||
+ (matches.isEmpty() ? "None" : String.join(", ", matches)));
|
||||
}
|
||||
|
||||
private void handleClient(CommandSender sender, String[] args) {
|
||||
if (args.length < 2) {
|
||||
send(sender, "%prefix% &eUsage: /antispoof client <lunar|feather|badlion|labymod> [player|list]");
|
||||
return;
|
||||
}
|
||||
ClientPlatform platform = ClientPlatform.parse(args[1]);
|
||||
if (platform == null) {
|
||||
send(sender, "%prefix% &cUnknown client platform: &f" + args[1]);
|
||||
return;
|
||||
}
|
||||
if (args.length == 2 || "list".equalsIgnoreCase(args[2])) {
|
||||
Map<UUID, Set<String>> all = plugin.getClientApiHookManager().getAllPlatformPlayers(platform);
|
||||
List<String> names = new ArrayList<>();
|
||||
for (UUID u : all.keySet()) {
|
||||
Player p = Bukkit.getPlayer(u);
|
||||
if (p != null) names.add(p.getName());
|
||||
}
|
||||
send(sender, "%prefix% &b" + platform.getDisplayName() + " &7online players (&f" + names.size() + "&7): &f"
|
||||
+ (names.isEmpty() ? "None" : String.join(", ", names)));
|
||||
return;
|
||||
}
|
||||
Player target = Bukkit.getPlayerExact(args[2]);
|
||||
if (target == null) {
|
||||
send(sender, "%prefix% &cPlayer not found: &f" + args[2]);
|
||||
return;
|
||||
}
|
||||
Set<String> mods = plugin.getClientApiHookManager().getClientMods(platform, target.getUniqueId());
|
||||
send(sender, "%prefix% &f" + target.getName() + " &7" + platform.getDisplayName() + " mods: &e"
|
||||
+ (mods.isEmpty() ? "None reported" : String.join(", ", mods)));
|
||||
}
|
||||
|
||||
private void handleLogs(CommandSender sender, String[] args) {
|
||||
if (args.length < 2) {
|
||||
List<UUID> logged = plugin.getPlayerLogManager().listLoggedPlayers();
|
||||
send(sender, "%prefix% &7Logged players (&f" + logged.size() + "&7): use &f/antispoof logs <player>");
|
||||
return;
|
||||
}
|
||||
OfflinePlayer target = Bukkit.getOfflinePlayer(args[1]);
|
||||
List<LogEntry> entries = plugin.getPlayerLogManager().readEntries(target.getUniqueId());
|
||||
if (entries.isEmpty()) {
|
||||
send(sender, "%prefix% &eNo logs found for &f" + args[1]);
|
||||
return;
|
||||
}
|
||||
send(sender, "%prefix% &7Latest logs for &f" + args[1] + " &8(&7showing last 10 of " + entries.size() + "&8):");
|
||||
int start = Math.max(0, entries.size() - 10);
|
||||
for (int i = start; i < entries.size(); i++) {
|
||||
LogEntry e = entries.get(i);
|
||||
String ts = LOG_FMT.format(Instant.ofEpochMilli(e.getTimestamp()));
|
||||
send(sender, "&8[" + ts + "] &e[" + e.getLogType().name() + "] &f" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void handleListChannels(CommandSender sender) {
|
||||
ConfigManager cfg = plugin.getConfigManager();
|
||||
send(sender, "%prefix% &7Blocked channels (&c" + cfg.getBlockedChannels().size() + "&7): &f"
|
||||
+ String.join(", ", cfg.getBlockedChannels()));
|
||||
send(sender, "%prefix% &7Whitelisted channels (&a" + cfg.getWhitelistedChannels().size() + "&7): &f"
|
||||
+ String.join(", ", cfg.getWhitelistedChannels()));
|
||||
}
|
||||
|
||||
private void handleListBrands(CommandSender sender) {
|
||||
Map<String, BrandRuleConfig> rules = plugin.getConfigManager().getBrandRules();
|
||||
send(sender, "%prefix% &7Configured brands (&f" + rules.size() + "&7):");
|
||||
for (BrandRuleConfig r : rules.values()) {
|
||||
send(sender, " &8- &b" + r.getId() + " &8| &7enabled=" + r.isEnabled()
|
||||
+ " allowed=" + r.isAllowed() + " matchers=" + r.getBrandMatchers());
|
||||
}
|
||||
}
|
||||
|
||||
private void handleReload(CommandSender sender) {
|
||||
if (!sender.hasPermission("antispoof.admin")) {
|
||||
send(sender, "%prefix% &cYou need antispoof.admin to reload.");
|
||||
return;
|
||||
}
|
||||
plugin.getConfigManager().reload();
|
||||
send(sender, "%prefix% &aConfiguration reloaded cleanly.");
|
||||
}
|
||||
|
||||
private void handleConfig(CommandSender sender, String[] args) {
|
||||
if (!sender.hasPermission("antispoof.admin")) {
|
||||
send(sender, "%prefix% &cYou need antispoof.admin to manage configuration.");
|
||||
return;
|
||||
}
|
||||
if (args.length < 2) {
|
||||
send(sender, "%prefix% &eUsage: /antispoof config <reset|update> [file]");
|
||||
return;
|
||||
}
|
||||
String action = args[1].toLowerCase(Locale.ROOT);
|
||||
if ("reset".equals(action)) {
|
||||
String target = args.length >= 3 ? args[2] : "config.yml";
|
||||
if ("all".equalsIgnoreCase(target)) {
|
||||
plugin.getConfigManager().resetFileToDefault("config.yml");
|
||||
plugin.getConfigManager().resetFileToDefault("brands-and-channels.yml");
|
||||
send(sender, "%prefix% &aReset config.yml and brands-and-channels.yml to defaults.");
|
||||
} else {
|
||||
String file = target.endsWith(".yml") ? target : target + ".yml";
|
||||
plugin.getConfigManager().resetFileToDefault(file);
|
||||
send(sender, "%prefix% &aReset &f" + file + " &ato defaults.");
|
||||
}
|
||||
} else if ("update".equals(action)) {
|
||||
int addedCfg = plugin.getConfigManager().mergeMissingDefaults("config.yml");
|
||||
int addedBrands = plugin.getConfigManager().mergeMissingDefaults("brands-and-channels.yml");
|
||||
plugin.getConfigManager().reload();
|
||||
send(sender, "%prefix% &aMerged missing defaults (&f" + addedCfg + " &ain config.yml, &f" + addedBrands + " &ain brands-and-channels.yml).");
|
||||
} else {
|
||||
send(sender, "%prefix% &eUsage: /antispoof config <reset|update> [file]");
|
||||
}
|
||||
}
|
||||
|
||||
private void sendHelp(CommandSender sender, String label, int page) {
|
||||
int maxPages = (int) Math.ceil((double) SUBCOMMANDS.size() / HELP_PAGE_SIZE);
|
||||
int clamped = Math.max(1, Math.min(page, maxPages));
|
||||
send(sender, "%prefix% &bAntiSpoof Help &8(&fPage " + clamped + "&7/&f" + maxPages + "&8)");
|
||||
int start = (clamped - 1) * HELP_PAGE_SIZE;
|
||||
int end = Math.min(SUBCOMMANDS.size(), start + HELP_PAGE_SIZE);
|
||||
for (int i = start; i < end; i++) {
|
||||
SubcommandHelp h = SUBCOMMANDS.get(i);
|
||||
send(sender, " &b/" + label + " " + h.usage() + " &8- &7" + h.description());
|
||||
}
|
||||
}
|
||||
|
||||
private Player requirePlayer(CommandSender sender, String[] args, int idx, String usage) {
|
||||
if (args.length <= idx) {
|
||||
send(sender, "%prefix% &eUsage: /antispoof " + usage);
|
||||
return null;
|
||||
}
|
||||
Player p = Bukkit.getPlayerExact(args[idx]);
|
||||
if (p == null) {
|
||||
send(sender, "%prefix% &cPlayer not found: &f" + args[idx]);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
private Collection<Player> resolveTargetOrAll(CommandSender sender, String[] args, int idx) {
|
||||
if (args.length <= idx || "*".equals(args[idx])) {
|
||||
return new ArrayList<>(Bukkit.getOnlinePlayers());
|
||||
}
|
||||
Player p = Bukkit.getPlayerExact(args[idx]);
|
||||
if (p == null) {
|
||||
send(sender, "%prefix% &cPlayer not found: &f" + args[idx]);
|
||||
return List.of();
|
||||
}
|
||||
return List.of(p);
|
||||
}
|
||||
|
||||
private void handleKeySpoofProbe(CommandSender sender, String[] args) {
|
||||
Player target = args.length >= 2 ? Bukkit.getPlayerExact(args[1]) : (sender instanceof Player p ? p : null);
|
||||
if (target == null) {
|
||||
send(sender, "%prefix% &cUsage: /antispoof keyspoof <player>");
|
||||
return;
|
||||
}
|
||||
if (plugin.getKeySpoofRpProbeManager() == null || !plugin.getKeySpoofRpProbeManager().isAvailable()) {
|
||||
send(sender, "%prefix% &cKeySpoof RP probe is disabled or HTTP server not running.");
|
||||
return;
|
||||
}
|
||||
plugin.getKeySpoofRpProbeManager().startProbe(target, sender);
|
||||
}
|
||||
|
||||
private void handleAssetLab(CommandSender sender, String[] args) {
|
||||
Player target = args.length >= 2 ? Bukkit.getPlayerExact(args[1]) : (sender instanceof Player p ? p : null);
|
||||
if (target == null) {
|
||||
send(sender, "%prefix% &cUsage: /antispoof assetlab <player>");
|
||||
return;
|
||||
}
|
||||
if (plugin.getAssetProbeLabManager() == null || !plugin.getAssetProbeLabManager().isAvailable()) {
|
||||
send(sender, "%prefix% &cAssetLab HTTP server not running.");
|
||||
return;
|
||||
}
|
||||
plugin.getAssetProbeLabManager().startLab(target, sender);
|
||||
}
|
||||
|
||||
private void send(CommandSender sender, String msg) {
|
||||
sender.sendMessage(TextUtil.toComponent(plugin.getConfigManager().expandPrefixes(msg)));
|
||||
}
|
||||
|
||||
private static int parseInt(String s, int fallback) {
|
||||
try {
|
||||
return Integer.parseInt(s);
|
||||
} catch (NumberFormatException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) {
|
||||
if (args.length == 1) {
|
||||
String pref = args[0].toLowerCase(Locale.ROOT);
|
||||
return ROOT_SUBS.stream().filter(s -> s.startsWith(pref)).toList();
|
||||
}
|
||||
String sub = args[0].toLowerCase(Locale.ROOT);
|
||||
if (args.length == 2) {
|
||||
String pref = args[1].toLowerCase(Locale.ROOT);
|
||||
if ("guard".equals(sub)) return filter(List.of("status", "on", "off", "auto"), pref);
|
||||
if ("alerts".equals(sub)) return filter(List.of("consistent"), pref);
|
||||
if ("config".equals(sub)) return filter(List.of("reset", "update"), pref);
|
||||
if ("client".equals(sub)) return filter(List.of("lunar", "feather", "badlion", "labymod"), pref);
|
||||
if (Arrays.asList("channels", "brand", "host", "os", "mods", "translate", "keybind", "keyspoof", "assetlab", "check", "proxy", "runcheck", "runmods", "runbook", "stopmods", "verify", "logs").contains(sub)) {
|
||||
List<String> out = new ArrayList<>();
|
||||
if (Arrays.asList("check", "runcheck", "runmods", "runbook", "stopmods").contains(sub)) {
|
||||
out.add("*");
|
||||
}
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
out.add(p.getName());
|
||||
}
|
||||
return filter(out, pref);
|
||||
}
|
||||
}
|
||||
if (args.length == 3) {
|
||||
String pref = args[2].toLowerCase(Locale.ROOT);
|
||||
if ("verify".equals(sub)) {
|
||||
return filter(new ArrayList<>(plugin.getConfigManager().getModProbeRules().keySet()), pref);
|
||||
}
|
||||
if ("alerts".equals(sub) && "consistent".equalsIgnoreCase(args[1])) {
|
||||
return filter(List.of("on", "off"), pref);
|
||||
}
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private static List<String> filter(List<String> list, String prefix) {
|
||||
return list.stream().filter(s -> s.toLowerCase(Locale.ROOT).startsWith(prefix)).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.gigazelensky.antispoof.config;
|
||||
|
||||
import com.gigazelensky.antispoof.data.AssetCheckType;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Configuration rule for resource-pack asset/mod detection probes (TEXTURES, FONT, CORRUPTION).
|
||||
*/
|
||||
public final class AssetProbeRule {
|
||||
private final String id;
|
||||
private final boolean enabled;
|
||||
private final AssetCheckType checkType;
|
||||
private final String targetPath;
|
||||
private final String displayName;
|
||||
private final boolean punish;
|
||||
private final boolean discordAlert;
|
||||
private final List<String> punishments;
|
||||
|
||||
public AssetProbeRule(
|
||||
String id,
|
||||
boolean enabled,
|
||||
AssetCheckType checkType,
|
||||
String targetPath,
|
||||
String displayName,
|
||||
boolean punish,
|
||||
boolean discordAlert,
|
||||
List<String> punishments
|
||||
) {
|
||||
this.id = id;
|
||||
this.enabled = enabled;
|
||||
this.checkType = checkType == null ? AssetCheckType.TEXTURES : checkType;
|
||||
this.targetPath = targetPath;
|
||||
this.displayName = displayName == null || displayName.isBlank() ? id : displayName;
|
||||
this.punish = punish;
|
||||
this.discordAlert = discordAlert;
|
||||
this.punishments = punishments == null ? List.of() : List.copyOf(punishments);
|
||||
}
|
||||
|
||||
public String getId() { return id; }
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public AssetCheckType getCheckType() { return checkType; }
|
||||
public String getTargetPath() { return targetPath; }
|
||||
public String getDisplayName() { return displayName; }
|
||||
public boolean isPunish() { return punish; }
|
||||
public boolean isDiscordAlert() { return discordAlert; }
|
||||
public List<String> getPunishments() { return punishments; }
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.gigazelensky.antispoof.config;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Configuration rule for a single client brand entry in brands-and-channels.yml / config.yml.
|
||||
*/
|
||||
public final class BrandRuleConfig {
|
||||
private final String id;
|
||||
private final boolean enabled;
|
||||
private final List<String> brandMatchers;
|
||||
private final List<String> requiredChannels;
|
||||
private final List<String> allowedChannels;
|
||||
private final List<String> blockedChannels;
|
||||
private final boolean notifyStaff;
|
||||
private final boolean discordAlert;
|
||||
private final boolean punish;
|
||||
private final String alertMessage;
|
||||
private final String discordMessage;
|
||||
private final List<String> punishments;
|
||||
private final boolean allowed;
|
||||
|
||||
public BrandRuleConfig(
|
||||
String id,
|
||||
boolean enabled,
|
||||
List<String> brandMatchers,
|
||||
List<String> requiredChannels,
|
||||
List<String> allowedChannels,
|
||||
List<String> blockedChannels,
|
||||
boolean notifyStaff,
|
||||
boolean discordAlert,
|
||||
boolean punish,
|
||||
String alertMessage,
|
||||
String discordMessage,
|
||||
List<String> punishments,
|
||||
boolean allowed
|
||||
) {
|
||||
this.id = id;
|
||||
this.enabled = enabled;
|
||||
this.brandMatchers = brandMatchers == null ? List.of() : List.copyOf(brandMatchers);
|
||||
this.requiredChannels = requiredChannels == null ? List.of() : List.copyOf(requiredChannels);
|
||||
this.allowedChannels = allowedChannels == null ? List.of() : List.copyOf(allowedChannels);
|
||||
this.blockedChannels = blockedChannels == null ? List.of() : List.copyOf(blockedChannels);
|
||||
this.notifyStaff = notifyStaff;
|
||||
this.discordAlert = discordAlert;
|
||||
this.punish = punish;
|
||||
this.alertMessage = alertMessage;
|
||||
this.discordMessage = discordMessage;
|
||||
this.punishments = punishments == null ? List.of() : List.copyOf(punishments);
|
||||
this.allowed = allowed;
|
||||
}
|
||||
|
||||
public String getId() { return id; }
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public List<String> getBrandMatchers() { return brandMatchers; }
|
||||
public List<String> getRequiredChannels() { return requiredChannels; }
|
||||
public List<String> getAllowedChannels() { return allowedChannels; }
|
||||
public List<String> getBlockedChannels() { return blockedChannels; }
|
||||
public boolean isNotifyStaff() { return notifyStaff; }
|
||||
public boolean isDiscordAlert() { return discordAlert; }
|
||||
public boolean isPunish() { return punish; }
|
||||
public String getAlertMessage() { return alertMessage; }
|
||||
public String getDiscordMessage() { return discordMessage; }
|
||||
public List<String> getPunishments() { return punishments; }
|
||||
public boolean isAllowed() { return allowed; }
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
package com.gigazelensky.antispoof.config;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.ViolationType;
|
||||
import com.gigazelensky.antispoof.data.AssetCheckType;
|
||||
import com.gigazelensky.antispoof.data.CheckMode;
|
||||
import com.gigazelensky.antispoof.data.ClientPlatform;
|
||||
import com.gigazelensky.antispoof.data.ProbeKeyType;
|
||||
import com.gigazelensky.antispoof.data.ProbeMode;
|
||||
import com.gigazelensky.antispoof.data.SurgeGuardAction;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
/**
|
||||
* Loads, caches, formats, and reloads all AntiSpoof configuration files (config.yml & brands-and-channels.yml).
|
||||
*/
|
||||
public final class ConfigManager {
|
||||
private static final Pattern PREFIX_TOKEN = Pattern.compile("%(prefix(?:_[0-9]+)?)%");
|
||||
public static final String DEFAULT_PREFIX = "<gradient:#00E8FF:#F500EE><b>[AntiSpoof]<reset>";
|
||||
public static final String DEFAULT_ALERTS_ENABLED = "%prefix_2% <green>Alerts enabled.<gray> You'll now receive AntiSpoof notifications.";
|
||||
public static final String DEFAULT_ALERTS_DISABLED = "%prefix_2% <yellow>Alerts disabled.<gray> Use <white>/%command% alerts</white> to turn them back on.";
|
||||
public static final String DEFAULT_ALERTS_PERSIST_ON = "%prefix_2% <green>Staff alert preferences will now persist across sessions and restarts.";
|
||||
public static final String DEFAULT_ALERTS_PERSIST_OFF = "%prefix_2% <yellow>Staff alert preferences will reset each time staff join.";
|
||||
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private FileConfiguration config;
|
||||
private FileConfiguration brandsConfig;
|
||||
|
||||
private final Map<String, String> prefixes = new LinkedHashMap<>();
|
||||
private final Map<String, Integer> violationWeights = new LinkedHashMap<>(ViolationType.DEFAULT_WEIGHTS);
|
||||
private final Map<String, BrandRuleConfig> brandRules = new LinkedHashMap<>();
|
||||
private final Map<String, ModProbeRule> modProbeRules = new LinkedHashMap<>();
|
||||
private final List<AssetProbeRule> assetProbeRules = new ArrayList<>();
|
||||
private final Set<String> blockedChannels = new LinkedHashSet<>();
|
||||
private final Set<String> whitelistedChannels = new LinkedHashSet<>();
|
||||
private final Set<String> vanillaAllowedChannels = new LinkedHashSet<>();
|
||||
private final Set<String> blockedVirtualHosts = new LinkedHashSet<>();
|
||||
private final Map<ClientPlatform, Set<String>> blockedClientMods = new LinkedHashMap<>();
|
||||
|
||||
// Core flags & timings
|
||||
private boolean debug;
|
||||
private int delayInSeconds;
|
||||
private boolean lpxSignPatch;
|
||||
private boolean packetEventsReEncode;
|
||||
private boolean weirdServerSoftware;
|
||||
private boolean logsEnabled;
|
||||
private boolean logsAlways;
|
||||
private boolean alertsConsistent;
|
||||
private CheckMode checkMode = CheckMode.SAFE;
|
||||
|
||||
// Individual checks
|
||||
private PunishmentRule noBrandRule;
|
||||
private PunishmentRule vanillaSpoofRule;
|
||||
private PunishmentRule nonVanillaRule;
|
||||
private PunishmentRule unknownBrandRule;
|
||||
private PunishmentRule blockedChannelRule;
|
||||
private PunishmentRule channelWhitelistRule;
|
||||
private PunishmentRule geyserSpoofRule;
|
||||
private PunishmentRule blockedVirtualHostRule;
|
||||
|
||||
// Translatable / Anvil / Sign / Book probes
|
||||
private boolean translatableEnabled;
|
||||
private ProbeMode defaultProbeMode = ProbeMode.SIGN;
|
||||
private int maxLineLength = 10_000;
|
||||
private long probeTimeoutTicks = 60L;
|
||||
private boolean anvilProbeEnabled;
|
||||
private boolean commandBookEnabled;
|
||||
|
||||
// Identity linker & HTTP probe server
|
||||
private boolean identityLinkerEnabled;
|
||||
private String httpHost = "0.0.0.0";
|
||||
private int httpPort = 25580;
|
||||
private String httpPublicHost = "127.0.0.1";
|
||||
private boolean identityRequireHider = true;
|
||||
private int identityProbeBitCount = 8;
|
||||
private boolean useLiteBansApi;
|
||||
|
||||
// Asset probe
|
||||
private boolean assetProbeEnabled;
|
||||
|
||||
// Server Resource-Pack Key Spoof probe (Method 1)
|
||||
private boolean keySpoofProbeEnabled = true;
|
||||
private boolean keySpoofProbeRequirePack = true;
|
||||
|
||||
// Proxy detection & TCP/OS fingerprinting
|
||||
private boolean proxyDetectionEnabled;
|
||||
private int proxyMinSamples = 5;
|
||||
private int proxySampleWindow = 10;
|
||||
private int proxyWarnThresholdMs = 60;
|
||||
private int proxyThresholdMs = 120;
|
||||
private boolean osDetectionEnabled;
|
||||
private boolean osUseTcpSniffer;
|
||||
private String pcapInterface = "auto";
|
||||
private int[] pcapPorts = new int[]{25565};
|
||||
|
||||
// Active recon
|
||||
private boolean activeReconEnabled;
|
||||
private int activeReconTimeoutMs = 1200;
|
||||
private List<Integer> activeReconPorts = List.of();
|
||||
|
||||
// Surge guard
|
||||
private boolean surgeGuardEnabled;
|
||||
private int surgeGuardJoinsPerWindow = 15;
|
||||
private int surgeGuardWindowSeconds = 5;
|
||||
private SurgeGuardAction surgeGuardAction = SurgeGuardAction.DELAY;
|
||||
|
||||
// Client-specific spoof checks
|
||||
private boolean lunarEnabled;
|
||||
private boolean lunarSpoofCheck;
|
||||
private boolean featherEnabled;
|
||||
private boolean featherSpoofCheck;
|
||||
private boolean badlionEnabled;
|
||||
private boolean badlionSpoofCheck;
|
||||
private boolean labymodEnabled;
|
||||
private boolean labymodSpoofCheck;
|
||||
|
||||
// Discord webhook (user-configured only — disabled by default unless admin sets webhook URL)
|
||||
private boolean discordEnabled;
|
||||
private String discordWebhookUrl = "";
|
||||
|
||||
public ConfigManager(AntiSpoofPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
ensureDefaultFiles();
|
||||
reload();
|
||||
}
|
||||
|
||||
public void ensureDefaultFiles() {
|
||||
File dataFolder = plugin.getDataFolder();
|
||||
if (!dataFolder.exists()) {
|
||||
dataFolder.mkdirs();
|
||||
}
|
||||
File configFile = new File(dataFolder, "config.yml");
|
||||
if (!configFile.exists()) {
|
||||
plugin.saveResource("config.yml", false);
|
||||
}
|
||||
File brandsFile = new File(dataFolder, "brands-and-channels.yml");
|
||||
if (!brandsFile.exists()) {
|
||||
plugin.saveResource("brands-and-channels.yml", false);
|
||||
}
|
||||
}
|
||||
|
||||
public void reload() {
|
||||
plugin.reloadConfig();
|
||||
this.config = plugin.getConfig();
|
||||
File brandsFile = new File(plugin.getDataFolder(), "brands-and-channels.yml");
|
||||
this.brandsConfig = YamlConfiguration.loadConfiguration(brandsFile);
|
||||
|
||||
loadPrefixes();
|
||||
loadCoreSettings();
|
||||
loadViolationWeights();
|
||||
loadCheckRules();
|
||||
loadBrandAndChannelRules();
|
||||
loadModProbeRules();
|
||||
loadAssetProbeRules();
|
||||
loadClientRules();
|
||||
}
|
||||
|
||||
private void loadPrefixes() {
|
||||
prefixes.clear();
|
||||
prefixes.put("prefix", config.getString("prefix", DEFAULT_PREFIX));
|
||||
prefixes.put("prefix_2", config.getString("prefix_2", prefixes.get("prefix")));
|
||||
for (String key : config.getKeys(false)) {
|
||||
if (key.startsWith("prefix_")) {
|
||||
prefixes.put(key, config.getString(key, prefixes.get("prefix")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void loadCoreSettings() {
|
||||
debug = config.getBoolean("debug", false);
|
||||
delayInSeconds = Math.max(0, config.getInt("delay-in-seconds", 2));
|
||||
lpxSignPatch = config.getBoolean("lpx-sign-patch", false);
|
||||
packetEventsReEncode = config.getBoolean("packet-events.re-encode-by-default", false);
|
||||
weirdServerSoftware = config.getBoolean("weird-server-software", false);
|
||||
logsEnabled = config.getBoolean("logs.enabled", true);
|
||||
logsAlways = config.getBoolean("logs.always", false);
|
||||
alertsConsistent = config.getBoolean("alerts.consistent", true);
|
||||
checkMode = CheckMode.parse(config.getString("check-mode", "SAFE"), CheckMode.SAFE);
|
||||
|
||||
translatableEnabled = config.getBoolean("translatable-keys.enabled", true);
|
||||
defaultProbeMode = ProbeMode.parse(config.getString("translatable-keys.mode", "SIGN"), ProbeMode.SIGN);
|
||||
maxLineLength = Math.max(256, config.getInt("translatable-keys.check.max-line-length", 10_000));
|
||||
probeTimeoutTicks = Math.max(20L, config.getLong("translatable-keys.timeout-ticks", 60L));
|
||||
anvilProbeEnabled = config.getBoolean("anvil-probe.enabled", true);
|
||||
commandBookEnabled = config.getBoolean("command-book.enabled", false);
|
||||
|
||||
identityLinkerEnabled = config.getBoolean("identity-linker.enabled", false);
|
||||
httpHost = config.getString("identity-linker.http.bind-host", "0.0.0.0");
|
||||
httpPort = config.getInt("identity-linker.http.port", 25580);
|
||||
httpPublicHost = config.getString("identity-linker.http.public-host", "127.0.0.1");
|
||||
identityRequireHider = config.getBoolean("identity-linker.require-hider-pack", true);
|
||||
identityProbeBitCount = Math.max(4, Math.min(16, config.getInt("identity-linker.probe-bits", 8)));
|
||||
useLiteBansApi = config.getBoolean("identity-linker.banned-account-actions.use-litebans-api", false);
|
||||
|
||||
assetProbeEnabled = config.getBoolean("asset-probe.enabled", false);
|
||||
|
||||
keySpoofProbeEnabled = config.getBoolean("key-spoof-probe.enabled", true);
|
||||
keySpoofProbeRequirePack = config.getBoolean("key-spoof-probe.require-pack", true);
|
||||
|
||||
proxyDetectionEnabled = config.getBoolean("proxy-detection.enabled", true);
|
||||
proxyMinSamples = Math.max(1, config.getInt("proxy-detection.min-samples", 5));
|
||||
proxySampleWindow = Math.max(proxyMinSamples, config.getInt("proxy-detection.sample-window", 10));
|
||||
proxyWarnThresholdMs = Math.max(10, config.getInt("proxy-detection.warn-threshold-ms", 60));
|
||||
proxyThresholdMs = Math.max(proxyWarnThresholdMs, config.getInt("proxy-detection.threshold-ms", 120));
|
||||
|
||||
osDetectionEnabled = config.getBoolean("os-detection.enabled", true);
|
||||
osUseTcpSniffer = config.getBoolean("os-detection.use-tcp-sniffer", false);
|
||||
pcapInterface = config.getString("os-detection.interface", "auto");
|
||||
List<Integer> ports = config.getIntegerList("os-detection.ports");
|
||||
if (ports.isEmpty()) {
|
||||
int serverPort = plugin.getServer() != null ? plugin.getServer().getPort() : 25565;
|
||||
pcapPorts = new int[]{serverPort > 0 ? serverPort : 25565};
|
||||
} else {
|
||||
pcapPorts = ports.stream().mapToInt(Integer::intValue).filter(p -> p > 0).distinct().toArray();
|
||||
}
|
||||
|
||||
activeReconEnabled = config.getBoolean("active-recon.enabled", false);
|
||||
activeReconTimeoutMs = Math.max(200, config.getInt("active-recon.timeout-ms", 1200));
|
||||
activeReconPorts = List.copyOf(config.getIntegerList("active-recon.ports"));
|
||||
|
||||
surgeGuardEnabled = config.getBoolean("surge-guard.enabled", true);
|
||||
surgeGuardJoinsPerWindow = Math.max(3, config.getInt("surge-guard.joins-per-window", 15));
|
||||
surgeGuardWindowSeconds = Math.max(1, config.getInt("surge-guard.window-seconds", 5));
|
||||
try {
|
||||
surgeGuardAction = SurgeGuardAction.valueOf(config.getString("surge-guard.action", "DELAY").trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
surgeGuardAction = SurgeGuardAction.DELAY;
|
||||
}
|
||||
|
||||
lunarEnabled = config.getBoolean("lunar.enabled", true);
|
||||
lunarSpoofCheck = config.getBoolean("lunar.spoof-check.enabled", true);
|
||||
featherEnabled = config.getBoolean("feather.enabled", true);
|
||||
featherSpoofCheck = config.getBoolean("feather.spoof-check.enabled", true);
|
||||
badlionEnabled = config.getBoolean("badlion.enabled", true);
|
||||
badlionSpoofCheck = config.getBoolean("badlion.spoof-check.enabled", true);
|
||||
labymodEnabled = config.getBoolean("labymod.enabled", true);
|
||||
labymodSpoofCheck = config.getBoolean("labymod.spoof-check.enabled", true);
|
||||
|
||||
discordEnabled = config.getBoolean("discord.enabled", false);
|
||||
discordWebhookUrl = config.getString("discord.webhook-url", "").trim();
|
||||
}
|
||||
|
||||
private void loadViolationWeights() {
|
||||
violationWeights.clear();
|
||||
violationWeights.putAll(ViolationType.DEFAULT_WEIGHTS);
|
||||
ConfigurationSection sec = config.getConfigurationSection("threat-weights");
|
||||
if (sec != null) {
|
||||
for (String key : sec.getKeys(false)) {
|
||||
violationWeights.put(key.toUpperCase(Locale.ROOT), sec.getInt(key, 10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void loadCheckRules() {
|
||||
noBrandRule = readRule("no-brand-check", "%prefix% &e%player% flagged! &cNo client brand detected", "%player% flagged! No client brand detected");
|
||||
vanillaSpoofRule = readRule("vanillaspoof-check", "%prefix% &e%player% flagged! &cVanilla brand with extra channels (%channels%)", "%player% flagged! Vanilla spoof (%channels%)");
|
||||
nonVanillaRule = readRule("non-vanilla-check", "%prefix% &e%player% flagged! &cNon-vanilla client (%brand%)", "%player% flagged! Non-vanilla client (%brand%)");
|
||||
unknownBrandRule = readRule("unknown-brand-check", "%prefix% &e%player% flagged! &cUnknown client brand (%brand%)", "%player% flagged! Unknown brand (%brand%)");
|
||||
blockedChannelRule = readRule("blocked-channels", "%prefix% &e%player% flagged! &cBlocked channel: %channel%", "%player% flagged! Blocked channel: %channel%");
|
||||
channelWhitelistRule = readRule("channel-whitelist", "%prefix% &e%player% flagged! &cNon-whitelisted channel: %channel%", "%player% flagged! Non-whitelisted channel: %channel%");
|
||||
geyserSpoofRule = readRule("geyser-spoof-check", "%prefix% &e%player% flagged! &cGeyser/Bedrock spoof detected", "%player% flagged! Geyser spoof");
|
||||
blockedVirtualHostRule = readRule("blocked-virtual-hosts", "%prefix% &e%player% flagged! &cBlocked virtual host: %host%", "%player% flagged! Blocked virtual host: %host%");
|
||||
|
||||
blockedVirtualHosts.clear();
|
||||
for (String h : config.getStringList("blocked-virtual-hosts.hosts")) {
|
||||
if (h != null && !h.isBlank()) {
|
||||
blockedVirtualHosts.add(h.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PunishmentRule readRule(String path, String defAlert, String defDiscord) {
|
||||
return new PunishmentRule(
|
||||
config.getBoolean(path + ".enabled", true),
|
||||
config.getBoolean(path + ".discord-alert", true),
|
||||
config.getBoolean(path + ".punish", false),
|
||||
config.getString(path + ".alert-message", defAlert),
|
||||
config.getString(path + ".discord-message", defDiscord),
|
||||
config.getStringList(path + ".punishments")
|
||||
);
|
||||
}
|
||||
|
||||
private void loadBrandAndChannelRules() {
|
||||
brandRules.clear();
|
||||
blockedChannels.clear();
|
||||
whitelistedChannels.clear();
|
||||
vanillaAllowedChannels.clear();
|
||||
|
||||
for (String ch : config.getStringList("vanillaspoof-check.channel-whitelist")) {
|
||||
if (ch != null && !ch.isBlank()) {
|
||||
vanillaAllowedChannels.add(ch.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
for (String ch : brandsConfig.getStringList("blocked-channels")) {
|
||||
if (ch != null && !ch.isBlank()) {
|
||||
blockedChannels.add(ch.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
for (String ch : config.getStringList("blocked-channels.channels")) {
|
||||
if (ch != null && !ch.isBlank()) {
|
||||
blockedChannels.add(ch.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
for (String ch : brandsConfig.getStringList("whitelisted-channels")) {
|
||||
if (ch != null && !ch.isBlank()) {
|
||||
whitelistedChannels.add(ch.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
for (String ch : config.getStringList("channel-whitelist.channels")) {
|
||||
if (ch != null && !ch.isBlank()) {
|
||||
whitelistedChannels.add(ch.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
|
||||
ConfigurationSection brandsSec = brandsConfig.getConfigurationSection("client-brands.brands");
|
||||
if (brandsSec == null) {
|
||||
brandsSec = config.getConfigurationSection("client-brands.brands");
|
||||
}
|
||||
if (brandsSec != null) {
|
||||
for (String id : brandsSec.getKeys(false)) {
|
||||
ConfigurationSection b = brandsSec.getConfigurationSection(id);
|
||||
if (b == null) {
|
||||
continue;
|
||||
}
|
||||
List<String> matchers = b.getStringList("matchers");
|
||||
if (matchers.isEmpty()) {
|
||||
matchers = List.of(id);
|
||||
}
|
||||
brandRules.put(id.toLowerCase(Locale.ROOT), new BrandRuleConfig(
|
||||
id,
|
||||
b.getBoolean("enabled", true),
|
||||
matchers,
|
||||
b.getStringList("required-channels"),
|
||||
b.getStringList("allowed-channels"),
|
||||
b.getStringList("blocked-channels"),
|
||||
b.getBoolean("notify-staff", true),
|
||||
b.getBoolean("discord-alert", true),
|
||||
b.getBoolean("punish", false),
|
||||
b.getString("alert-message", "%prefix% &e%player% flagged! &cBrand rule matched: " + id),
|
||||
b.getString("discord-message", "%player% flagged! Brand: " + id),
|
||||
b.getStringList("punishments"),
|
||||
b.getBoolean("allowed", true)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void loadModProbeRules() {
|
||||
modProbeRules.clear();
|
||||
ConfigurationSection modsSec = config.getConfigurationSection("translatable-keys.mods");
|
||||
if (modsSec == null) {
|
||||
return;
|
||||
}
|
||||
for (String label : modsSec.getKeys(false)) {
|
||||
ConfigurationSection m = modsSec.getConfigurationSection(label);
|
||||
if (m == null) {
|
||||
continue;
|
||||
}
|
||||
ProbeKeyType keyType = ProbeKeyType.TRANSLATE;
|
||||
try {
|
||||
keyType = ProbeKeyType.valueOf(m.getString("type", "TRANSLATE").trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
ProbeMode mode = ProbeMode.parse(m.getString("mode", defaultProbeMode.name()), defaultProbeMode);
|
||||
modProbeRules.put(label, new ModProbeRule(
|
||||
label,
|
||||
m.getBoolean("enabled", true),
|
||||
m.getBoolean("notify-staff", true),
|
||||
m.getBoolean("discord-alert", true),
|
||||
m.getBoolean("punish", false),
|
||||
m.getBoolean("log-only", false),
|
||||
m.getString("alert-message", "%prefix% &e%player% flagged! &cDetected mod: " + label),
|
||||
m.getString("discord-message", "%player% detected using mod: " + label),
|
||||
m.getStringList("keys"),
|
||||
m.getStringList("punishments"),
|
||||
keyType,
|
||||
mode,
|
||||
m.getBoolean("require-all", false)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private void loadAssetProbeRules() {
|
||||
assetProbeRules.clear();
|
||||
ConfigurationSection sec = config.getConfigurationSection("asset-probe.rules");
|
||||
if (sec == null) {
|
||||
return;
|
||||
}
|
||||
for (String id : sec.getKeys(false)) {
|
||||
ConfigurationSection r = sec.getConfigurationSection(id);
|
||||
if (r == null) {
|
||||
continue;
|
||||
}
|
||||
AssetCheckType type = AssetCheckType.TEXTURES;
|
||||
try {
|
||||
type = AssetCheckType.valueOf(r.getString("type", "TEXTURES").trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
assetProbeRules.add(new AssetProbeRule(
|
||||
id,
|
||||
r.getBoolean("enabled", true),
|
||||
type,
|
||||
r.getString("path", ""),
|
||||
r.getString("name", id),
|
||||
r.getBoolean("punish", false),
|
||||
r.getBoolean("discord-alert", true),
|
||||
r.getStringList("punishments")
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private void loadClientRules() {
|
||||
blockedClientMods.clear();
|
||||
for (ClientPlatform platform : ClientPlatform.values()) {
|
||||
String key = platform.name().toLowerCase(Locale.ROOT);
|
||||
Set<String> blocked = new LinkedHashSet<>();
|
||||
for (String mod : config.getStringList(key + ".blocked-mods")) {
|
||||
if (mod != null && !mod.isBlank()) {
|
||||
blocked.add(mod.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
for (String mod : config.getStringList(key + ".disabled-addons")) {
|
||||
if (mod != null && !mod.isBlank()) {
|
||||
blocked.add(mod.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
blockedClientMods.put(platform, Collections.unmodifiableSet(blocked));
|
||||
}
|
||||
}
|
||||
|
||||
public String expandPrefixes(String input) {
|
||||
if (input == null || input.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
Matcher matcher = PREFIX_TOKEN.matcher(input);
|
||||
StringBuffer sb = new StringBuffer();
|
||||
while (matcher.find()) {
|
||||
String key = matcher.group(1);
|
||||
String replacement = prefixes.getOrDefault(key, prefixes.getOrDefault("prefix", DEFAULT_PREFIX));
|
||||
matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
matcher.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public int mergeMissingDefaults(String resourceName) {
|
||||
File target = new File(plugin.getDataFolder(), resourceName);
|
||||
try (InputStream in = plugin.getResource(resourceName)) {
|
||||
if (in == null) {
|
||||
return 0;
|
||||
}
|
||||
YamlConfiguration defYaml = YamlConfiguration.loadConfiguration(new InputStreamReader(in, StandardCharsets.UTF_8));
|
||||
YamlConfiguration curYaml = target.exists() ? YamlConfiguration.loadConfiguration(target) : new YamlConfiguration();
|
||||
int added = 0;
|
||||
for (String key : defYaml.getKeys(true)) {
|
||||
if (!defYaml.isConfigurationSection(key) && !curYaml.contains(key)) {
|
||||
curYaml.set(key, defYaml.get(key));
|
||||
added++;
|
||||
}
|
||||
}
|
||||
if (added > 0) {
|
||||
curYaml.save(target);
|
||||
}
|
||||
return added;
|
||||
} catch (IOException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean resetFileToDefault(String resourceName) {
|
||||
File target = new File(plugin.getDataFolder(), resourceName);
|
||||
if (target.exists() && !target.delete()) {
|
||||
return false;
|
||||
}
|
||||
plugin.saveResource(resourceName, true);
|
||||
reload();
|
||||
return true;
|
||||
}
|
||||
|
||||
public File getConfigFile() { return new File(plugin.getDataFolder(), "config.yml"); }
|
||||
public File getBrandsConfigFile() { return new File(plugin.getDataFolder(), "brands-and-channels.yml"); }
|
||||
public FileConfiguration getRawConfig() { return config; }
|
||||
public FileConfiguration getBrandsConfig() { return brandsConfig; }
|
||||
public String getPrefix() { return prefixes.getOrDefault("prefix", DEFAULT_PREFIX); }
|
||||
public Set<String> getKnownViolationTypes() { return Collections.unmodifiableSet(violationWeights.keySet()); }
|
||||
public int getViolationWeight(String type) { return violationWeights.getOrDefault(type == null ? "" : type.toUpperCase(Locale.ROOT), 10); }
|
||||
public Map<String, BrandRuleConfig> getBrandRules() { return Collections.unmodifiableMap(brandRules); }
|
||||
public Map<String, ModProbeRule> getModProbeRules() { return Collections.unmodifiableMap(modProbeRules); }
|
||||
public List<AssetProbeRule> getAssetProbeRules() { return Collections.unmodifiableList(assetProbeRules); }
|
||||
public Set<String> getBlockedChannels() { return Collections.unmodifiableSet(blockedChannels); }
|
||||
public Set<String> getWhitelistedChannels() { return Collections.unmodifiableSet(whitelistedChannels); }
|
||||
public Set<String> getVanillaAllowedChannels() { return Collections.unmodifiableSet(vanillaAllowedChannels); }
|
||||
public Set<String> getBlockedVirtualHosts() { return Collections.unmodifiableSet(blockedVirtualHosts); }
|
||||
public Set<String> getBlockedClientMods(ClientPlatform platform) { return blockedClientMods.getOrDefault(platform, Set.of()); }
|
||||
|
||||
public boolean isDebug() { return debug; }
|
||||
public int getDelayInSeconds() { return delayInSeconds; }
|
||||
public boolean isLpxSignPatch() { return lpxSignPatch; }
|
||||
public boolean isPacketEventsReEncode() { return packetEventsReEncode; }
|
||||
public boolean isWeirdServerSoftware() { return weirdServerSoftware; }
|
||||
public boolean isLogsEnabled() { return logsEnabled; }
|
||||
public boolean isLogsAlways() { return logsAlways; }
|
||||
public boolean isAlertsConsistent() { return alertsConsistent; }
|
||||
public CheckMode getCheckMode() { return checkMode; }
|
||||
|
||||
public PunishmentRule getNoBrandRule() { return noBrandRule; }
|
||||
public PunishmentRule getVanillaSpoofRule() { return vanillaSpoofRule; }
|
||||
public PunishmentRule getNonVanillaRule() { return nonVanillaRule; }
|
||||
public PunishmentRule getUnknownBrandRule() { return unknownBrandRule; }
|
||||
public PunishmentRule getBlockedChannelRule() { return blockedChannelRule; }
|
||||
public PunishmentRule getChannelWhitelistRule() { return channelWhitelistRule; }
|
||||
public PunishmentRule getGeyserSpoofRule() { return geyserSpoofRule; }
|
||||
public PunishmentRule getBlockedVirtualHostRule() { return blockedVirtualHostRule; }
|
||||
|
||||
public boolean isTranslatableEnabled() { return translatableEnabled; }
|
||||
public ProbeMode getDefaultProbeMode() { return defaultProbeMode; }
|
||||
public int getMaxLineLength() { return maxLineLength; }
|
||||
public long getProbeTimeoutTicks() { return probeTimeoutTicks; }
|
||||
public boolean isAnvilProbeEnabled() { return anvilProbeEnabled; }
|
||||
public boolean isCommandBookEnabled() { return commandBookEnabled; }
|
||||
|
||||
public boolean isIdentityLinkerEnabled() { return identityLinkerEnabled; }
|
||||
public String getHttpHost() { return httpHost; }
|
||||
public int getHttpPort() { return httpPort; }
|
||||
public String getHttpPublicHost() { return httpPublicHost; }
|
||||
public boolean isIdentityRequireHider() { return identityRequireHider; }
|
||||
public int getIdentityProbeBitCount() { return identityProbeBitCount; }
|
||||
public boolean isUseLiteBansApi() { return useLiteBansApi; }
|
||||
|
||||
public boolean isAssetProbeEnabled() { return assetProbeEnabled; }
|
||||
public boolean isKeySpoofProbeEnabled() { return keySpoofProbeEnabled; }
|
||||
public boolean isKeySpoofProbeRequirePack() { return keySpoofProbeRequirePack; }
|
||||
|
||||
public boolean isProxyDetectionEnabled() { return proxyDetectionEnabled; }
|
||||
public int getProxyMinSamples() { return proxyMinSamples; }
|
||||
public int getProxySampleWindow() { return proxySampleWindow; }
|
||||
public int getProxyWarnThresholdMs() { return proxyWarnThresholdMs; }
|
||||
public int getProxyThresholdMs() { return proxyThresholdMs; }
|
||||
|
||||
public boolean isOsDetectionEnabled() { return osDetectionEnabled; }
|
||||
public boolean isOsUseTcpSniffer() { return osUseTcpSniffer; }
|
||||
public String getPcapInterface() { return pcapInterface; }
|
||||
public int[] getPcapPorts() { return pcapPorts.clone(); }
|
||||
|
||||
public boolean isActiveReconEnabled() { return activeReconEnabled; }
|
||||
public int getActiveReconTimeoutMs() { return activeReconTimeoutMs; }
|
||||
public List<Integer> getActiveReconPorts() { return activeReconPorts; }
|
||||
|
||||
public boolean isSurgeGuardEnabled() { return surgeGuardEnabled; }
|
||||
public int getSurgeGuardJoinsPerWindow() { return surgeGuardJoinsPerWindow; }
|
||||
public int getSurgeGuardWindowSeconds() { return surgeGuardWindowSeconds; }
|
||||
public SurgeGuardAction getSurgeGuardAction() { return surgeGuardAction; }
|
||||
|
||||
public boolean isLunarEnabled() { return lunarEnabled; }
|
||||
public boolean isLunarSpoofCheck() { return lunarSpoofCheck; }
|
||||
public boolean isFeatherEnabled() { return featherEnabled; }
|
||||
public boolean isFeatherSpoofCheck() { return featherSpoofCheck; }
|
||||
public boolean isBadlionEnabled() { return badlionEnabled; }
|
||||
public boolean isBadlionSpoofCheck() { return badlionSpoofCheck; }
|
||||
public boolean isLabyModEnabled() { return labymodEnabled; }
|
||||
public boolean isLabyModSpoofCheck() { return labymodSpoofCheck; }
|
||||
|
||||
public boolean isDiscordEnabled() { return discordEnabled && !discordWebhookUrl.isEmpty(); }
|
||||
public String getDiscordWebhookUrl() { return discordWebhookUrl; }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.gigazelensky.antispoof.config;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
/**
|
||||
* Persists targeted GUI/command toggle changes cleanly into config.yml or brands-and-channels.yml.
|
||||
*/
|
||||
public final class ConfigToggleWriter {
|
||||
private ConfigToggleWriter() {
|
||||
}
|
||||
|
||||
public static boolean setValue(File file, String path, Object value, Logger logger) {
|
||||
if (file == null || path == null || path.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
YamlConfiguration yaml = YamlConfiguration.loadConfiguration(file);
|
||||
yaml.set(path, value);
|
||||
yaml.save(file);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
if (logger != null) {
|
||||
logger.log(Level.WARNING, "Failed to persist config value at " + path + " in " + file.getName(), e);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.gigazelensky.antispoof.config;
|
||||
|
||||
import com.gigazelensky.antispoof.data.ProbeKeyType;
|
||||
import com.gigazelensky.antispoof.data.ProbeMode;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Configuration rule for a single translation/keybind mod detection probe.
|
||||
*/
|
||||
public final class ModProbeRule {
|
||||
private final String label;
|
||||
private final boolean enabled;
|
||||
private final boolean notifyStaff;
|
||||
private final boolean discordAlert;
|
||||
private final boolean punish;
|
||||
private final boolean logOnly;
|
||||
private final String alertMessage;
|
||||
private final String discordMessage;
|
||||
private final List<String> keys;
|
||||
private final List<String> punishments;
|
||||
private final ProbeKeyType keyType;
|
||||
private final ProbeMode probeMode;
|
||||
private final boolean requireAllKeys;
|
||||
|
||||
public ModProbeRule(
|
||||
String label,
|
||||
boolean enabled,
|
||||
boolean notifyStaff,
|
||||
boolean discordAlert,
|
||||
boolean punish,
|
||||
boolean logOnly,
|
||||
String alertMessage,
|
||||
String discordMessage,
|
||||
List<String> keys,
|
||||
List<String> punishments,
|
||||
ProbeKeyType keyType,
|
||||
ProbeMode probeMode,
|
||||
boolean requireAllKeys
|
||||
) {
|
||||
this.label = label;
|
||||
this.enabled = enabled;
|
||||
this.notifyStaff = notifyStaff;
|
||||
this.discordAlert = discordAlert;
|
||||
this.punish = punish;
|
||||
this.logOnly = logOnly;
|
||||
this.alertMessage = alertMessage;
|
||||
this.discordMessage = discordMessage;
|
||||
this.keys = keys == null ? List.of() : List.copyOf(keys);
|
||||
this.punishments = punishments == null ? List.of() : List.copyOf(punishments);
|
||||
this.keyType = keyType == null ? ProbeKeyType.TRANSLATE : keyType;
|
||||
this.probeMode = probeMode == null ? ProbeMode.SIGN : probeMode;
|
||||
this.requireAllKeys = requireAllKeys;
|
||||
}
|
||||
|
||||
public String getLabel() { return label; }
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public boolean isNotifyStaff() { return notifyStaff; }
|
||||
public boolean isDiscordAlert() { return discordAlert; }
|
||||
public boolean isPunish() { return punish; }
|
||||
public boolean isLogOnly() { return logOnly; }
|
||||
public String getAlertMessage() { return alertMessage; }
|
||||
public String getDiscordMessage() { return discordMessage; }
|
||||
public List<String> getKeys() { return keys; }
|
||||
public List<String> getPunishments() { return punishments; }
|
||||
public ProbeKeyType getKeyType() { return keyType; }
|
||||
public ProbeMode getProbeMode() { return probeMode; }
|
||||
public boolean isRequireAllKeys() { return requireAllKeys; }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.gigazelensky.antispoof.config;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Reusable rule describing an individual check's enablement, alerting, and punishment commands.
|
||||
*/
|
||||
public final class PunishmentRule {
|
||||
private final boolean enabled;
|
||||
private final boolean discordAlert;
|
||||
private final boolean punish;
|
||||
private final String alertMessage;
|
||||
private final String discordMessage;
|
||||
private final List<String> commands;
|
||||
|
||||
public PunishmentRule(
|
||||
boolean enabled,
|
||||
boolean discordAlert,
|
||||
boolean punish,
|
||||
String alertMessage,
|
||||
String discordMessage,
|
||||
List<String> commands
|
||||
) {
|
||||
this.enabled = enabled;
|
||||
this.discordAlert = discordAlert;
|
||||
this.punish = punish;
|
||||
this.alertMessage = alertMessage;
|
||||
this.discordMessage = discordMessage;
|
||||
this.commands = commands == null ? List.of() : List.copyOf(commands);
|
||||
}
|
||||
|
||||
public boolean isEnabled() { return enabled; }
|
||||
public boolean isDiscordAlert() { return discordAlert; }
|
||||
public boolean isPunish() { return punish; }
|
||||
public String getAlertMessage() { return alertMessage; }
|
||||
public String getDiscordMessage() { return discordMessage; }
|
||||
public List<String> getCommands() { return commands; }
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
package com.gigazelensky.antispoof.core;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.event.PacketListenerCommon;
|
||||
import com.gigazelensky.antispoof.api.ApiLifecycle;
|
||||
import com.gigazelensky.antispoof.api.events.AntiSpoofPrePunishmentEvent;
|
||||
import com.gigazelensky.antispoof.api.events.PunishmentTier;
|
||||
import com.gigazelensky.antispoof.command.AntiSpoofCommand;
|
||||
import com.gigazelensky.antispoof.config.ConfigManager;
|
||||
import com.gigazelensky.antispoof.config.PunishmentRule;
|
||||
import com.gigazelensky.antispoof.data.LogReaderParser;
|
||||
import com.gigazelensky.antispoof.data.LogType;
|
||||
import com.gigazelensky.antispoof.data.OsInfo;
|
||||
import com.gigazelensky.antispoof.data.PlayerLogManager;
|
||||
import com.gigazelensky.antispoof.data.PlayerProfile;
|
||||
import com.gigazelensky.antispoof.data.PlayerStorageManager;
|
||||
import com.gigazelensky.antispoof.fingerprint.OsDetectorService;
|
||||
import com.gigazelensky.antispoof.fingerprint.OsFingerprintManager;
|
||||
import com.gigazelensky.antispoof.gui.GuiListener;
|
||||
import com.gigazelensky.antispoof.hook.AntiSpoofPlaceholderExpansion;
|
||||
import com.gigazelensky.antispoof.hook.ClientApiHookManager;
|
||||
import com.gigazelensky.antispoof.hook.PlaceholderFormatter;
|
||||
import com.gigazelensky.antispoof.packet.BrandChannelListener;
|
||||
import com.gigazelensky.antispoof.probe.ActiveReconScanner;
|
||||
import com.gigazelensky.antispoof.probe.AssetProbeLabManager;
|
||||
import com.gigazelensky.antispoof.probe.AssetProbeListener;
|
||||
import com.gigazelensky.antispoof.probe.CommandBookProbeManager;
|
||||
import com.gigazelensky.antispoof.probe.IdentityLinkerManager;
|
||||
import com.gigazelensky.antispoof.probe.KeySpoofRpProbeManager;
|
||||
import com.gigazelensky.antispoof.probe.ProbeHttpServer;
|
||||
import com.gigazelensky.antispoof.probe.ProxyDetectionManager;
|
||||
import com.gigazelensky.antispoof.probe.ResourcePackIntegrityListener;
|
||||
import com.gigazelensky.antispoof.probe.SurgeGuardManager;
|
||||
import com.gigazelensky.antispoof.probe.TranslationProbeManager;
|
||||
import com.gigazelensky.antispoof.util.SchedulerUtil;
|
||||
import com.gigazelensky.antispoof.util.TextUtil;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.logging.Level;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
/**
|
||||
* Pure-Java Paper/Folia 1.20.x AntiSpoof plugin main class (reconstructed from IIllllIIIIIlIll).
|
||||
* All DRM, license beacons, anti-debug scanners, Unsafe tamper hooks, and JNIC/VMP shells are removed.
|
||||
*/
|
||||
public final class AntiSpoofPlugin extends JavaPlugin {
|
||||
private static volatile AntiSpoofPlugin instance;
|
||||
|
||||
private final EventBus eventBus = new EventBus();
|
||||
private final Map<UUID, PlayerProfile> playerProfiles = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, String> playerBrands = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, String> playerVersions = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, String> playerLocales = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, OsInfo> playerOsCache = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Long> bypassUntilMillis = new ConcurrentHashMap<>();
|
||||
private final Set<UUID> alertsDisabledStaff = ConcurrentHashMap.newKeySet();
|
||||
private final List<PacketListenerCommon> registeredPacketListeners = new ArrayList<>();
|
||||
|
||||
private ConfigManager configManager;
|
||||
private PlayerLogManager playerLogManager;
|
||||
private LogReaderParser logReaderParser;
|
||||
private PlayerStorageManager playerStorageManager;
|
||||
private SurgeGuardManager surgeGuardManager;
|
||||
private OsFingerprintManager osFingerprintManager;
|
||||
private OsDetectorService osDetectorService;
|
||||
private ProbeHttpServer probeHttpServer;
|
||||
private IdentityLinkerManager identityLinkerManager;
|
||||
private AssetProbeListener assetProbeListener;
|
||||
private AssetProbeLabManager assetProbeLabManager;
|
||||
private ResourcePackIntegrityListener resourcePackIntegrityListener;
|
||||
private TranslationProbeManager translationProbeManager;
|
||||
private KeySpoofRpProbeManager keySpoofRpProbeManager;
|
||||
private CommandBookProbeManager commandBookProbeManager;
|
||||
private ProxyDetectionManager proxyDetectionManager;
|
||||
private ActiveReconScanner activeReconScanner;
|
||||
private BrandChannelListener brandChannelListener;
|
||||
private ClientApiHookManager clientApiHookManager;
|
||||
|
||||
public static AntiSpoofPlugin getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
instance = this;
|
||||
long startMs = System.currentTimeMillis();
|
||||
|
||||
// 1. Config & Storage
|
||||
this.configManager = new ConfigManager(this);
|
||||
this.playerLogManager = new PlayerLogManager(this);
|
||||
this.logReaderParser = new LogReaderParser(this);
|
||||
this.playerStorageManager = new PlayerStorageManager(this);
|
||||
this.surgeGuardManager = new SurgeGuardManager(configManager);
|
||||
|
||||
// 2. TCP/OS Fingerprinting (starts Pcap4J thread only when enabled in config)
|
||||
this.osDetectorService = new OsDetectorService(this, configManager);
|
||||
if (configManager.isOsDetectionEnabled() && configManager.isOsUseTcpSniffer()) {
|
||||
this.osFingerprintManager = new OsFingerprintManager(
|
||||
getLogger(),
|
||||
configManager.getPcapInterface(),
|
||||
configManager.getPcapPorts(),
|
||||
Duration.ofMinutes(5)
|
||||
);
|
||||
this.osFingerprintManager.start();
|
||||
}
|
||||
|
||||
// 3. Embedded NanoHTTPD probe server (when identity-linker, asset-probe, or key-spoof-probe is enabled)
|
||||
if (configManager.isIdentityLinkerEnabled() || configManager.isAssetProbeEnabled() || configManager.isKeySpoofProbeEnabled()) {
|
||||
this.probeHttpServer = new ProbeHttpServer(this, configManager.getHttpHost(), configManager.getHttpPort());
|
||||
try {
|
||||
this.probeHttpServer.start();
|
||||
getLogger().info("Probe HTTP server listening on " + configManager.getHttpHost() + ":" + probeHttpServer.getListeningPort());
|
||||
} catch (IOException e) {
|
||||
getLogger().log(Level.WARNING, "Failed to start Probe HTTP server on port " + configManager.getHttpPort(), e);
|
||||
this.probeHttpServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Detection Managers & Listeners
|
||||
this.identityLinkerManager = new IdentityLinkerManager(this, probeHttpServer);
|
||||
this.assetProbeListener = new AssetProbeListener(this, probeHttpServer);
|
||||
this.assetProbeLabManager = new AssetProbeLabManager(this, probeHttpServer);
|
||||
this.resourcePackIntegrityListener = new ResourcePackIntegrityListener(this);
|
||||
this.translationProbeManager = new TranslationProbeManager(this);
|
||||
this.keySpoofRpProbeManager = new KeySpoofRpProbeManager(this, probeHttpServer);
|
||||
this.commandBookProbeManager = new CommandBookProbeManager(this);
|
||||
this.commandBookProbeManager.start();
|
||||
this.proxyDetectionManager = new ProxyDetectionManager(this);
|
||||
this.activeReconScanner = new ActiveReconScanner(this);
|
||||
this.brandChannelListener = new BrandChannelListener(this);
|
||||
this.clientApiHookManager = new ClientApiHookManager(this);
|
||||
|
||||
// 5. Register Bukkit Listeners
|
||||
PluginManager pm = getServer().getPluginManager();
|
||||
pm.registerEvents(brandChannelListener, this);
|
||||
pm.registerEvents(translationProbeManager, this);
|
||||
pm.registerEvents(keySpoofRpProbeManager, this);
|
||||
pm.registerEvents(identityLinkerManager, this);
|
||||
pm.registerEvents(assetProbeListener, this);
|
||||
pm.registerEvents(assetProbeLabManager, this);
|
||||
pm.registerEvents(commandBookProbeManager, this);
|
||||
pm.registerEvents(resourcePackIntegrityListener, this);
|
||||
pm.registerEvents(new GuiListener(), this);
|
||||
clientApiHookManager.registerHooks();
|
||||
|
||||
// 6. Register PacketEvents Listeners
|
||||
registerPacketEventsListeners();
|
||||
|
||||
// 7. Register /antispoof command
|
||||
PluginCommand cmd = getCommand("antispoof");
|
||||
if (cmd != null) {
|
||||
AntiSpoofCommand executor = new AntiSpoofCommand(this);
|
||||
cmd.setExecutor(executor);
|
||||
cmd.setTabCompleter(executor);
|
||||
}
|
||||
|
||||
// 8. Register PlaceholderAPI expansion if installed
|
||||
if (pm.getPlugin("PlaceholderAPI") != null) {
|
||||
try {
|
||||
new AntiSpoofPlaceholderExpansion(this).register();
|
||||
getLogger().info("Registered PlaceholderAPI expansion (%antispoof_*%).");
|
||||
} catch (Throwable t) {
|
||||
getLogger().log(Level.WARNING, "Failed to register PlaceholderAPI expansion", t);
|
||||
}
|
||||
}
|
||||
|
||||
// 9. Initialize Public API
|
||||
ApiLifecycle.initialize(this, eventBus);
|
||||
|
||||
getLogger().info("AntiSpoof " + getPluginMeta().getVersion() + " enabled in "
|
||||
+ (System.currentTimeMillis() - startMs) + "ms (pure-Java build).");
|
||||
}
|
||||
|
||||
private void registerPacketEventsListeners() {
|
||||
try {
|
||||
var em = PacketEvents.getAPI().getEventManager();
|
||||
registeredPacketListeners.add(em.registerListener(brandChannelListener));
|
||||
registeredPacketListeners.add(em.registerListener(keySpoofRpProbeManager));
|
||||
registeredPacketListeners.add(em.registerListener(translationProbeManager));
|
||||
registeredPacketListeners.add(em.registerListener(proxyDetectionManager));
|
||||
} catch (Throwable t) {
|
||||
getLogger().log(Level.SEVERE, "Failed to register PacketEvents listeners — is PacketEvents installed?", t);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
ApiLifecycle.reset();
|
||||
eventBus.clear();
|
||||
|
||||
try {
|
||||
var em = PacketEvents.getAPI().getEventManager();
|
||||
for (PacketListenerCommon l : registeredPacketListeners) {
|
||||
if (l != null) {
|
||||
em.unregisterListener(l);
|
||||
}
|
||||
}
|
||||
registeredPacketListeners.clear();
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
|
||||
if (keySpoofRpProbeManager != null) keySpoofRpProbeManager.shutdown();
|
||||
if (assetProbeLabManager != null) assetProbeLabManager.shutdown();
|
||||
if (translationProbeManager != null) translationProbeManager.shutdown();
|
||||
if (commandBookProbeManager != null) commandBookProbeManager.shutdown();
|
||||
if (identityLinkerManager != null) identityLinkerManager.shutdown();
|
||||
if (probeHttpServer != null) probeHttpServer.stop();
|
||||
if (activeReconScanner != null) activeReconScanner.shutdown();
|
||||
if (osFingerprintManager != null) osFingerprintManager.stop();
|
||||
if (playerStorageManager != null) playerStorageManager.saveAll();
|
||||
|
||||
playerProfiles.clear();
|
||||
playerBrands.clear();
|
||||
playerVersions.clear();
|
||||
playerLocales.clear();
|
||||
playerOsCache.clear();
|
||||
instance = null;
|
||||
getLogger().info("AntiSpoof disabled cleanly.");
|
||||
}
|
||||
|
||||
public PlayerProfile getOrCreateProfile(UUID uuid) {
|
||||
return playerProfiles.computeIfAbsent(uuid, PlayerProfile::new);
|
||||
}
|
||||
|
||||
public void flagPlayer(Player player, String violationType, String reason) {
|
||||
if (player == null || violationType == null || reason == null) {
|
||||
return;
|
||||
}
|
||||
UUID uuid = player.getUniqueId();
|
||||
if (isBypassed(uuid) || player.hasPermission("antispoof.bypass")) {
|
||||
return;
|
||||
}
|
||||
|
||||
PlayerProfile profile = getOrCreateProfile(uuid);
|
||||
profile.addViolation(violationType + ": " + reason);
|
||||
int weight = configManager.getViolationWeight(violationType);
|
||||
long newThreat = profile.addThreatLevel(weight);
|
||||
String brand = getPlayerBrand(player);
|
||||
|
||||
playerLogManager.log(player, LogType.FLAG, "[" + violationType + "] " + reason + " (threat=" + newThreat + ")");
|
||||
notifyStaff(player, violationType, reason);
|
||||
eventBus.publish(new ViolationReportedEvent(player, violationType, reason, brand));
|
||||
|
||||
// Execute configured punishments if rule enables punishment
|
||||
PunishmentRule rule = ruleForViolation(violationType);
|
||||
if (rule != null && rule.isPunish() && !rule.getCommands().isEmpty()) {
|
||||
executePunishment(player, violationType, reason, brand, null, rule.getCommands(), newThreat);
|
||||
}
|
||||
}
|
||||
|
||||
public void reportExternalViolation(Player player, String sourcePlugin, String reason) {
|
||||
flagPlayer(player, ViolationType.EXTERNAL_REPORT, "[" + sourcePlugin + "] " + reason);
|
||||
}
|
||||
|
||||
private void executePunishment(
|
||||
Player player,
|
||||
String violationType,
|
||||
String reason,
|
||||
String brand,
|
||||
String violatedChannel,
|
||||
List<String> commands,
|
||||
long threatLevel
|
||||
) {
|
||||
PunishmentTier tier = new PunishmentTier(violationType, commands, reason, brand, violatedChannel);
|
||||
AntiSpoofPrePunishmentEvent preEvent = new AntiSpoofPrePunishmentEvent(player, tier, threatLevel);
|
||||
Bukkit.getPluginManager().callEvent(preEvent);
|
||||
if (preEvent.isCancelled()) {
|
||||
return;
|
||||
}
|
||||
PlayerProfile profile = getOrCreateProfile(player.getUniqueId());
|
||||
profile.setAlreadyPunished(true);
|
||||
SchedulerUtil.runGlobal(this, () -> {
|
||||
for (String rawCmd : commands) {
|
||||
String formatted = PlaceholderFormatter.formatTemplate(this, player, rawCmd)
|
||||
.replace("%reason%", reason)
|
||||
.replace("%type%", violationType);
|
||||
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), formatted);
|
||||
playerLogManager.log(player, LogType.PUNISH, "Ran command: " + formatted);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void notifyStaff(Player flagged, String violationType, String reason) {
|
||||
String template = configManager.getRawConfig().getString("alerts.flag-format", "%prefix% &e%player% flagged! &c%reason%");
|
||||
String rendered = PlaceholderFormatter.formatTemplate(this, flagged, template)
|
||||
.replace("%reason%", reason)
|
||||
.replace("%type%", violationType);
|
||||
var component = TextUtil.toComponent(rendered);
|
||||
for (Player staff : Bukkit.getOnlinePlayers()) {
|
||||
if ((staff.hasPermission("antispoof.alerts") || staff.hasPermission("antispoof.admin"))
|
||||
&& isStaffAlertsEnabled(staff.getUniqueId())) {
|
||||
staff.sendMessage(component);
|
||||
}
|
||||
}
|
||||
if (configManager.isDebug()) {
|
||||
getLogger().info("[Flag] " + flagged.getName() + " [" + violationType + "] " + reason);
|
||||
}
|
||||
}
|
||||
|
||||
private PunishmentRule ruleForViolation(String violationType) {
|
||||
return switch (violationType) {
|
||||
case ViolationType.NO_BRAND -> configManager.getNoBrandRule();
|
||||
case ViolationType.VANILLA_WITH_CHANNELS -> configManager.getVanillaSpoofRule();
|
||||
case ViolationType.NON_VANILLA_WITH_CHANNELS -> configManager.getNonVanillaRule();
|
||||
case ViolationType.UNKNOWN_BRAND -> configManager.getUnknownBrandRule();
|
||||
case ViolationType.BLOCKED_CHANNEL -> configManager.getBlockedChannelRule();
|
||||
case ViolationType.CHANNEL_WHITELIST -> configManager.getChannelWhitelistRule();
|
||||
case ViolationType.GEYSER_SPOOF -> configManager.getGeyserSpoofRule();
|
||||
case ViolationType.BLOCKED_VIRTUAL_HOST -> configManager.getBlockedVirtualHostRule();
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
public boolean isStaffAlertsEnabled(UUID staffId) {
|
||||
if (configManager.isAlertsConsistent() && playerStorageManager != null) {
|
||||
Boolean saved = playerStorageManager.getStaffAlertPreference(staffId);
|
||||
if (saved != null) {
|
||||
return saved;
|
||||
}
|
||||
}
|
||||
return !alertsDisabledStaff.contains(staffId);
|
||||
}
|
||||
|
||||
public boolean toggleStaffAlerts(UUID staffId) {
|
||||
boolean next = !isStaffAlertsEnabled(staffId);
|
||||
if (next) {
|
||||
alertsDisabledStaff.remove(staffId);
|
||||
} else {
|
||||
alertsDisabledStaff.add(staffId);
|
||||
}
|
||||
if (configManager.isAlertsConsistent() && playerStorageManager != null) {
|
||||
playerStorageManager.setStaffAlertPreference(staffId, next);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
public void setBypassed(UUID uuid, boolean bypassed, long durationMillis) {
|
||||
if (!bypassed) {
|
||||
bypassUntilMillis.remove(uuid);
|
||||
return;
|
||||
}
|
||||
long until = durationMillis <= 0L ? Long.MAX_VALUE : System.currentTimeMillis() + durationMillis;
|
||||
bypassUntilMillis.put(uuid, until);
|
||||
}
|
||||
|
||||
public boolean isBypassed(UUID uuid) {
|
||||
Long until = bypassUntilMillis.get(uuid);
|
||||
if (until == null) {
|
||||
return false;
|
||||
}
|
||||
if (System.currentTimeMillis() > until) {
|
||||
bypassUntilMillis.remove(uuid);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public Optional<Long> getThreatLevel(UUID uuid) {
|
||||
PlayerProfile profile = playerProfiles.get(uuid);
|
||||
return profile == null ? Optional.empty() : Optional.of(profile.getThreatLevel());
|
||||
}
|
||||
|
||||
public void resetThreatLevel(Player moderator, UUID target, String reason) {
|
||||
PlayerProfile profile = playerProfiles.get(target);
|
||||
if (profile != null) {
|
||||
profile.setThreatLevel(0L);
|
||||
}
|
||||
playerLogManager.log(target, LogType.ADMIN,
|
||||
String.format("[API] %s reset the threat level to 0 (reason: %s)", moderator.getName(), reason));
|
||||
}
|
||||
|
||||
public void modifyThreatLevel(Player moderator, UUID target, int delta, String reason) {
|
||||
PlayerProfile profile = getOrCreateProfile(target);
|
||||
long updated = profile.addThreatLevel(delta);
|
||||
String verb = delta >= 0 ? "increased" : "decreased";
|
||||
playerLogManager.log(target, LogType.ADMIN,
|
||||
String.format("[API] %s %s the threat level by %d (new level: %d) (reason: %s)",
|
||||
moderator.getName(), verb, Math.abs(delta), updated, reason));
|
||||
}
|
||||
|
||||
public CompletableFuture<Integer> getHistoricalViolationCount(UUID uuid) {
|
||||
return logReaderParser.getHistoricalViolationCount(uuid);
|
||||
}
|
||||
|
||||
public String getPlayerBrand(Player player) {
|
||||
if (player == null) return null;
|
||||
String stored = playerBrands.get(player.getUniqueId());
|
||||
return stored != null ? stored : player.getClientBrandName();
|
||||
}
|
||||
|
||||
public String getPlayerVersion(Player player) {
|
||||
return player == null ? null : playerVersions.get(player.getUniqueId());
|
||||
}
|
||||
|
||||
public String getPlayerLocale(Player player) {
|
||||
return player == null ? null : getPlayerLocale(player.getUniqueId());
|
||||
}
|
||||
|
||||
public String getPlayerLocale(UUID uuid) {
|
||||
return uuid == null ? null : playerLocales.get(uuid);
|
||||
}
|
||||
|
||||
public List<String> getFlagReasons(Player player) {
|
||||
if (player == null) return List.of();
|
||||
PlayerProfile p = playerProfiles.get(player.getUniqueId());
|
||||
return p == null ? List.of() : List.copyOf(p.getViolations());
|
||||
}
|
||||
|
||||
public boolean isBedrock(Player player) {
|
||||
return clientApiHookManager != null && clientApiHookManager.isBedrockPlayer(player);
|
||||
}
|
||||
|
||||
public OsInfo getOsInfo(UUID uuid) {
|
||||
return uuid == null ? null : playerOsCache.get(uuid);
|
||||
}
|
||||
|
||||
public void cacheOsInfo(UUID uuid, OsInfo info) {
|
||||
if (uuid != null && info != null) {
|
||||
playerOsCache.put(uuid, info);
|
||||
}
|
||||
}
|
||||
|
||||
public EventBus getEventBus() { return eventBus; }
|
||||
public ConfigManager getConfigManager() { return configManager; }
|
||||
public PlayerLogManager getPlayerLogManager() { return playerLogManager; }
|
||||
public LogReaderParser getLogReaderParser() { return logReaderParser; }
|
||||
public PlayerStorageManager getPlayerStorageManager() { return playerStorageManager; }
|
||||
public SurgeGuardManager getSurgeGuardManager() { return surgeGuardManager; }
|
||||
public OsFingerprintManager getOsFingerprintManager() { return osFingerprintManager; }
|
||||
public OsDetectorService getOsDetectorService() { return osDetectorService; }
|
||||
public IdentityLinkerManager getIdentityLinkerManager() { return identityLinkerManager; }
|
||||
public AssetProbeListener getAssetProbeListener() { return assetProbeListener; }
|
||||
public AssetProbeLabManager getAssetProbeLabManager() { return assetProbeLabManager; }
|
||||
public TranslationProbeManager getTranslationProbeManager() { return translationProbeManager; }
|
||||
public KeySpoofRpProbeManager getKeySpoofRpProbeManager() { return keySpoofRpProbeManager; }
|
||||
public CommandBookProbeManager getCommandBookProbeManager() { return commandBookProbeManager; }
|
||||
public ProxyDetectionManager getProxyDetectionManager() { return proxyDetectionManager; }
|
||||
public ActiveReconScanner getActiveReconScanner() { return activeReconScanner; }
|
||||
public BrandChannelListener getBrandChannelListener() { return brandChannelListener; }
|
||||
public ClientApiHookManager getClientApiHookManager() { return clientApiHookManager; }
|
||||
|
||||
public Map<UUID, PlayerProfile> getPlayerProfiles() { return playerProfiles; }
|
||||
public Map<UUID, String> getPlayerBrands() { return playerBrands; }
|
||||
public Map<UUID, String> getPlayerVersions() { return playerVersions; }
|
||||
public Map<UUID, String> getPlayerLocales() { return playerLocales; }
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.gigazelensky.antispoof.core;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Lightweight internal synchronous event bus bridging core detection events to AntiSpoofAPI.
|
||||
*/
|
||||
public final class EventBus {
|
||||
private final Map<Class<?>, List<Consumer<?>>> listeners = new ConcurrentHashMap<>();
|
||||
|
||||
public <T> EventSubscription subscribe(Class<T> eventType, Consumer<T> consumer) {
|
||||
Objects.requireNonNull(eventType, "eventType");
|
||||
Objects.requireNonNull(consumer, "consumer");
|
||||
listeners.computeIfAbsent(eventType, k -> new CopyOnWriteArrayList<>()).add(consumer);
|
||||
return new EventSubscription(this, eventType, consumer);
|
||||
}
|
||||
|
||||
<T> void unsubscribe(Class<T> eventType, Consumer<T> consumer) {
|
||||
List<Consumer<?>> list = listeners.get(eventType);
|
||||
if (list != null) {
|
||||
list.remove(consumer);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> void publish(T event) {
|
||||
if (event == null) {
|
||||
return;
|
||||
}
|
||||
List<Consumer<?>> list = listeners.get(event.getClass());
|
||||
if (list == null || list.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (Consumer<?> raw : list) {
|
||||
try {
|
||||
((Consumer<T>) raw).accept(event);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
listeners.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.gigazelensky.antispoof.core;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class EventSubscription implements AutoCloseable {
|
||||
private final EventBus bus;
|
||||
private final Class<?> eventType;
|
||||
private final Consumer<?> consumer;
|
||||
private final AtomicBoolean closed = new AtomicBoolean(false);
|
||||
|
||||
EventSubscription(EventBus bus, Class<?> eventType, Consumer<?> consumer) {
|
||||
this.bus = bus;
|
||||
this.eventType = eventType;
|
||||
this.consumer = consumer;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public void close() {
|
||||
if (closed.compareAndSet(false, true)) {
|
||||
bus.unsubscribe((Class) eventType, (Consumer) consumer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.gigazelensky.antispoof.core;
|
||||
|
||||
import com.gigazelensky.antispoof.api.events.IdentityAnomalyType;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public final class IdentityAnomalyInternalEvent {
|
||||
private final Player player;
|
||||
private final IdentityAnomalyType type;
|
||||
private final String description;
|
||||
private final Map<String, Object> context;
|
||||
|
||||
public IdentityAnomalyInternalEvent(
|
||||
Player player,
|
||||
IdentityAnomalyType type,
|
||||
String description,
|
||||
Map<String, Object> context
|
||||
) {
|
||||
this.player = Objects.requireNonNull(player, "player");
|
||||
this.type = Objects.requireNonNull(type, "type");
|
||||
this.description = Objects.requireNonNull(description, "description");
|
||||
this.context = context == null || context.isEmpty()
|
||||
? Collections.emptyMap()
|
||||
: Collections.unmodifiableMap(new LinkedHashMap<>(context));
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public IdentityAnomalyType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public Map<String, Object> getContext() {
|
||||
return context;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.gigazelensky.antispoof.core;
|
||||
|
||||
import java.util.Objects;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
public final class ViolationReportedEvent {
|
||||
private final Player player;
|
||||
private final String violationType;
|
||||
private final String reason;
|
||||
private final String brand;
|
||||
|
||||
public ViolationReportedEvent(Player player, String violationType, String reason, String brand) {
|
||||
this.player = Objects.requireNonNull(player, "player");
|
||||
this.violationType = Objects.requireNonNull(violationType, "violationType");
|
||||
this.reason = Objects.requireNonNull(reason, "reason");
|
||||
this.brand = brand;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public String getViolationType() {
|
||||
return violationType;
|
||||
}
|
||||
|
||||
public String getReason() {
|
||||
return reason;
|
||||
}
|
||||
|
||||
public String getBrand() {
|
||||
return brand;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.gigazelensky.antispoof.core;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Canonical AntiSpoof violation identifiers and default threat-level weights.
|
||||
*/
|
||||
public final class ViolationType {
|
||||
public static final String JOIN_BRAND = "JOIN_BRAND";
|
||||
public static final String VANILLA_WITH_CHANNELS = "VANILLA_WITH_CHANNELS";
|
||||
public static final String NON_VANILLA_WITH_CHANNELS = "NON_VANILLA_WITH_CHANNELS";
|
||||
public static final String BLOCKED_CHANNEL = "BLOCKED_CHANNEL";
|
||||
public static final String CHANNEL_WHITELIST = "CHANNEL_WHITELIST";
|
||||
public static final String GEYSER_SPOOF = "GEYSER_SPOOF";
|
||||
public static final String NO_BRAND = "NO_BRAND";
|
||||
public static final String MISSING_REQUIRED_CHANNELS = "MISSING_REQUIRED_CHANNELS";
|
||||
public static final String CLIENT_BRAND = "CLIENT_BRAND";
|
||||
public static final String UNKNOWN_BRAND = "UNKNOWN_BRAND";
|
||||
public static final String BLOCKED_VIRTUAL_HOST = "BLOCKED_VIRTUAL_HOST";
|
||||
public static final String TRANSLATE_TIMEOUT_ANY = "TRANSLATE_TIMEOUT_ANY";
|
||||
public static final String TRANSLATE_TIMEOUT_ALL = "TRANSLATE_TIMEOUT_ALL";
|
||||
public static final String ANVIL_TIMEOUT_ANY = "ANVIL_TIMEOUT_ANY";
|
||||
public static final String ANVIL_TIMEOUT_ALL = "ANVIL_TIMEOUT_ALL";
|
||||
public static final String COMMAND_BOOK_BLOCKED = "COMMAND_BOOK_BLOCKED";
|
||||
public static final String POSSIBLE_PROXY = "POSSIBLE_PROXY";
|
||||
public static final String SUSPECTED_PROXY = "SUSPECTED_PROXY";
|
||||
public static final String EXTERNAL_REPORT = "EXTERNAL_REPORT";
|
||||
public static final String IDENTITY_SPOOF = "IDENTITY_SPOOF";
|
||||
public static final String HIDER_PACK_REJECTED = "HIDER_PACK_REJECTED";
|
||||
public static final String PROBE_COUNT_MISMATCH = "PROBE_COUNT_MISMATCH";
|
||||
public static final String RESOURCE_PACK_SPOOF = "RESOURCE_PACK_SPOOF";
|
||||
public static final String RESOURCE_PACK_INTEGRITY = "RESOURCE_PACK_INTEGRITY";
|
||||
public static final String ASSET_DETECTED = "ASSET_DETECTED";
|
||||
public static final String ASSET_DECLINED = "ASSET_DECLINED";
|
||||
public static final String CLIENT_MOD_BLOCKED = "CLIENT_MOD_BLOCKED";
|
||||
public static final String CLIENT_BRAND_SPOOF = "CLIENT_BRAND_SPOOF";
|
||||
public static final String LUNAR_MOD_BLOCKED = "LUNAR_MOD_BLOCKED";
|
||||
public static final String LUNAR_BRAND_SPOOF = "LUNAR_BRAND_SPOOF";
|
||||
public static final String IDENTITY_HIDER_PACK = "IDENTITY_HIDER_PACK";
|
||||
public static final String IDENTITY_PROBE_MISMATCH = "IDENTITY_PROBE_MISMATCH";
|
||||
public static final String IDENTITY_RESOURCE_SPOOF = "IDENTITY_RESOURCE_SPOOF";
|
||||
public static final String KEY_SPOOF_DETECTED = "KEY_SPOOF_DETECTED";
|
||||
public static final String KEY_SPOOF_RP_REJECTED = "KEY_SPOOF_RP_REJECTED";
|
||||
|
||||
public static final Map<String, Integer> DEFAULT_WEIGHTS;
|
||||
public static final Set<String> KNOWN_TYPES;
|
||||
|
||||
static {
|
||||
Map<String, Integer> m = new LinkedHashMap<>();
|
||||
m.put(VANILLA_WITH_CHANNELS, 10);
|
||||
m.put(NON_VANILLA_WITH_CHANNELS, 12);
|
||||
m.put(BLOCKED_CHANNEL, 15);
|
||||
m.put(CHANNEL_WHITELIST, 15);
|
||||
m.put(GEYSER_SPOOF, 25);
|
||||
m.put(NO_BRAND, 8);
|
||||
m.put(MISSING_REQUIRED_CHANNELS, 20);
|
||||
m.put(UNKNOWN_BRAND, 10);
|
||||
m.put(BLOCKED_VIRTUAL_HOST, 16);
|
||||
m.put(TRANSLATE_TIMEOUT_ANY, 5);
|
||||
m.put(TRANSLATE_TIMEOUT_ALL, 10);
|
||||
m.put(ANVIL_TIMEOUT_ANY, 5);
|
||||
m.put(ANVIL_TIMEOUT_ALL, 10);
|
||||
m.put(POSSIBLE_PROXY, 8);
|
||||
m.put(SUSPECTED_PROXY, 18);
|
||||
m.put(EXTERNAL_REPORT, 12);
|
||||
m.put(IDENTITY_SPOOF, 25);
|
||||
m.put(HIDER_PACK_REJECTED, 15);
|
||||
m.put(PROBE_COUNT_MISMATCH, 15);
|
||||
m.put(RESOURCE_PACK_SPOOF, 20);
|
||||
m.put(RESOURCE_PACK_INTEGRITY, 20);
|
||||
m.put(ASSET_DETECTED, 20);
|
||||
m.put(ASSET_DECLINED, 12);
|
||||
m.put(CLIENT_MOD_BLOCKED, 15);
|
||||
m.put(CLIENT_BRAND_SPOOF, 20);
|
||||
m.put(LUNAR_MOD_BLOCKED, 15);
|
||||
m.put(LUNAR_BRAND_SPOOF, 20);
|
||||
m.put(KEY_SPOOF_DETECTED, 25);
|
||||
m.put(KEY_SPOOF_RP_REJECTED, 12);
|
||||
DEFAULT_WEIGHTS = Collections.unmodifiableMap(m);
|
||||
KNOWN_TYPES = Collections.unmodifiableSet(m.keySet());
|
||||
}
|
||||
|
||||
private ViolationType() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum AssetCheckType {
|
||||
TEXTURES,
|
||||
FONT,
|
||||
CORRUPTION
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum CheckMode {
|
||||
SAFE,
|
||||
LEGACY;
|
||||
|
||||
public static CheckMode parse(String raw, CheckMode fallback) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
return valueOf(raw.trim().toUpperCase(java.util.Locale.ROOT));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
public enum ClientPlatform {
|
||||
LUNAR("Lunar Client", "lunar"),
|
||||
FEATHER("Feather Client", "feather"),
|
||||
BADLION("Badlion Client", "blc"),
|
||||
LABYMOD("LabyMod", "laby");
|
||||
|
||||
private final String displayName;
|
||||
private final String shortAlias;
|
||||
|
||||
ClientPlatform(String displayName, String shortAlias) {
|
||||
this.displayName = displayName;
|
||||
this.shortAlias = shortAlias;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public String getShortAlias() {
|
||||
return shortAlias;
|
||||
}
|
||||
|
||||
public static ClientPlatform parse(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String norm = raw.trim().toLowerCase(Locale.ROOT).replace(" ", "").replace("-", "").replace("_", "");
|
||||
for (ClientPlatform p : values()) {
|
||||
if (p.name().toLowerCase(Locale.ROOT).equals(norm)
|
||||
|| p.shortAlias.equals(norm)
|
||||
|| p.displayName.toLowerCase(Locale.ROOT).replace(" ", "").equals(norm)) {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum DetectionTriggerSource {
|
||||
BRAND,
|
||||
CHANNEL,
|
||||
TRANSLATABLE
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum IdentityProbeStage {
|
||||
WAITING_FOR_HIDER,
|
||||
PROBING_CACHE,
|
||||
MARKING_NEW
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class IdentityRecord {
|
||||
private final List<String> allAccounts;
|
||||
private final List<String> altAccounts;
|
||||
|
||||
public IdentityRecord(List<String> allAccounts, List<String> altAccounts) {
|
||||
this.allAccounts = allAccounts == null ? List.of() : List.copyOf(allAccounts);
|
||||
this.altAccounts = altAccounts == null ? List.of() : List.copyOf(altAccounts);
|
||||
}
|
||||
|
||||
public List<String> getAllAccounts() {
|
||||
return allAccounts;
|
||||
}
|
||||
|
||||
public List<String> getAltAccounts() {
|
||||
return altAccounts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public final class LogEntry {
|
||||
private long timestamp;
|
||||
private LogType logType;
|
||||
private String message;
|
||||
private PlayerSnapshotData snapshot;
|
||||
|
||||
public LogEntry() {
|
||||
}
|
||||
|
||||
public LogEntry(long timestamp, LogType logType, String message, PlayerSnapshotData snapshot) {
|
||||
this.timestamp = timestamp;
|
||||
this.logType = logType == null ? LogType.INFO : logType;
|
||||
this.message = message == null ? "" : message;
|
||||
this.snapshot = snapshot;
|
||||
}
|
||||
|
||||
public long getTimestamp() { return timestamp; }
|
||||
public LogType getLogType() { return logType; }
|
||||
public String getMessage() { return message; }
|
||||
public PlayerSnapshotData getSnapshot() { return snapshot; }
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Parses historical player log files to compute violation counts and leaderboard stats (reconstructed from IlIlIlIIIIlIIll).
|
||||
*/
|
||||
public final class LogReaderParser {
|
||||
private static final Pattern TOTAL_FLAGS_PATTERN = Pattern.compile("(?i)total\\s*flags\\s*:\\s*(\\d+)");
|
||||
private final AntiSpoofPlugin plugin;
|
||||
|
||||
public LogReaderParser(AntiSpoofPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public CompletableFuture<Integer> getHistoricalViolationCount(UUID uniqueId) {
|
||||
return CompletableFuture.supplyAsync(() -> countViolations(uniqueId, TimeRange.ALL));
|
||||
}
|
||||
|
||||
public int countViolations(UUID uniqueId, TimeRange range) {
|
||||
PlayerLogManager logMgr = plugin.getPlayerLogManager();
|
||||
if (logMgr == null || uniqueId == null) {
|
||||
return 0;
|
||||
}
|
||||
long cutoff = cutoffFor(range);
|
||||
File file = logMgr.getPlayerLogFile(uniqueId);
|
||||
if (!file.exists()) {
|
||||
return 0;
|
||||
}
|
||||
int count = 0;
|
||||
try {
|
||||
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
|
||||
for (String line : lines) {
|
||||
Matcher m = TOTAL_FLAGS_PATTERN.matcher(line);
|
||||
if (m.find()) {
|
||||
count = Math.max(count, Integer.parseInt(m.group(1)));
|
||||
} else if (line.contains("[FLAG]") || line.contains("[PUNISH]")) {
|
||||
if (cutoff <= 0L || file.lastModified() >= cutoff) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException | NumberFormatException ignored) {
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
public Map<UUID, Integer> getFlagLeaderboard(TimeRange range) {
|
||||
PlayerLogManager logMgr = plugin.getPlayerLogManager();
|
||||
if (logMgr == null) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
Map<UUID, Integer> counts = new LinkedHashMap<>();
|
||||
for (UUID uuid : logMgr.listLoggedPlayers()) {
|
||||
int c = countViolations(uuid, range);
|
||||
if (c > 0) {
|
||||
counts.put(uuid, c);
|
||||
}
|
||||
}
|
||||
List<Map.Entry<UUID, Integer>> sorted = counts.entrySet().stream()
|
||||
.sorted((a, b) -> Integer.compare(b.getValue(), a.getValue()))
|
||||
.toList();
|
||||
Map<UUID, Integer> out = new LinkedHashMap<>();
|
||||
for (Map.Entry<UUID, Integer> e : sorted) {
|
||||
out.put(e.getKey(), e.getValue());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static long cutoffFor(TimeRange range) {
|
||||
if (range == null || range == TimeRange.ALL) {
|
||||
return 0L;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
return switch (range) {
|
||||
case WEEK -> now - TimeUnit.DAYS.toMillis(7L);
|
||||
case MONTH -> now - TimeUnit.DAYS.toMillis(30L);
|
||||
case ALL -> 0L;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum LogSortMode {
|
||||
FLAGS("Flags"),
|
||||
LOGS("Logs"),
|
||||
AVG_FLAGS("Average Flags"),
|
||||
ALPHABETICAL_AZ("A-Z"),
|
||||
ALPHABETICAL_ZA("Z-A"),
|
||||
LATEST("Latest"),
|
||||
OLDEST("Oldest");
|
||||
|
||||
private final String label;
|
||||
|
||||
LogSortMode(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
|
||||
public LogSortMode next() {
|
||||
LogSortMode[] vals = values();
|
||||
return vals[(ordinal() + 1) % vals.length];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum LogType {
|
||||
INFO,
|
||||
FLAG,
|
||||
PUNISH,
|
||||
PROBE,
|
||||
ADMIN
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum MatchConfidence {
|
||||
EXACT,
|
||||
INFERRED,
|
||||
NONE
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum ModLoaderCategory {
|
||||
UNSPECIFIED,
|
||||
FABRIC_INTERNAL,
|
||||
FABRIC_EXTERNAL,
|
||||
FORGE_INTERNAL,
|
||||
FORGE_EXTERNAL
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public class OsInfo {
|
||||
private final String osName;
|
||||
private final double confidence;
|
||||
private final String source;
|
||||
|
||||
public OsInfo(String osName, double confidence, String source) {
|
||||
this.osName = (osName == null || osName.isBlank()) ? "Unknown" : osName;
|
||||
this.confidence = Math.max(0.0, Math.min(confidence, 1.0));
|
||||
this.source = source == null ? "unknown" : source;
|
||||
}
|
||||
|
||||
public String getOsName() {
|
||||
return osName;
|
||||
}
|
||||
|
||||
public double getConfidence() {
|
||||
return confidence;
|
||||
}
|
||||
|
||||
public String getSource() {
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.logging.Level;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* Per-player append-only JSON-lines log writer and reader (reconstructed from IllIIIllllllllI).
|
||||
*/
|
||||
public final class PlayerLogManager {
|
||||
private static final DateTimeFormatter TS_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final File logsDir;
|
||||
private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
|
||||
|
||||
public PlayerLogManager(AntiSpoofPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.logsDir = new File(plugin.getDataFolder(), "logs");
|
||||
if (!logsDir.exists()) {
|
||||
logsDir.mkdirs();
|
||||
}
|
||||
}
|
||||
|
||||
public File getLogsDir() {
|
||||
return logsDir;
|
||||
}
|
||||
|
||||
public File getPlayerLogFile(UUID uniqueId) {
|
||||
return new File(logsDir, uniqueId + ".log");
|
||||
}
|
||||
|
||||
public void log(Player player, LogType type, String message) {
|
||||
if (player == null || !plugin.getConfigManager().isLogsEnabled()) {
|
||||
return;
|
||||
}
|
||||
if (type == LogType.INFO && !plugin.getConfigManager().isLogsAlways()) {
|
||||
return;
|
||||
}
|
||||
UUID uuid = player.getUniqueId();
|
||||
PlayerProfile profile = plugin.getPlayerProfiles().get(uuid);
|
||||
OsInfo os = plugin.getOsInfo(uuid);
|
||||
PlayerSnapshotData snap = profile != null
|
||||
? profile.toSnapshotData(
|
||||
plugin.getPlayerBrand(player),
|
||||
plugin.getPlayerVersion(player),
|
||||
plugin.getPlayerLocale(player),
|
||||
os != null ? os.getOsName() : "Unknown",
|
||||
plugin.isBedrock(player))
|
||||
: null;
|
||||
LogEntry entry = new LogEntry(System.currentTimeMillis(), type, message, snap);
|
||||
appendAsync(uuid, entry);
|
||||
}
|
||||
|
||||
public void log(UUID uniqueId, LogType type, String message) {
|
||||
if (uniqueId == null || !plugin.getConfigManager().isLogsEnabled()) {
|
||||
return;
|
||||
}
|
||||
appendAsync(uniqueId, new LogEntry(System.currentTimeMillis(), type, message, null));
|
||||
}
|
||||
|
||||
private void appendAsync(UUID uniqueId, LogEntry entry) {
|
||||
String line = "[" + TS_FMT.format(Instant.ofEpochMilli(entry.getTimestamp())) + "] [" + entry.getLogType().name() + "] "
|
||||
+ entry.getMessage() + " | JSON:" + gson.toJson(entry);
|
||||
CompletableFuture.runAsync(() -> {
|
||||
File file = getPlayerLogFile(uniqueId);
|
||||
synchronized (this) {
|
||||
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, StandardCharsets.UTF_8, true))) {
|
||||
bw.write(line);
|
||||
bw.newLine();
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.WARNING, "Could not write log file for " + uniqueId, e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public List<LogEntry> readEntries(UUID uniqueId) {
|
||||
File file = getPlayerLogFile(uniqueId);
|
||||
if (!file.exists()) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<LogEntry> result = new ArrayList<>();
|
||||
try {
|
||||
for (String line : Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)) {
|
||||
int marker = line.indexOf(" | JSON:");
|
||||
if (marker != -1) {
|
||||
String json = line.substring(marker + " | JSON:".length()).trim();
|
||||
try {
|
||||
LogEntry parsed = gson.fromJson(json, LogEntry.class);
|
||||
if (parsed != null) {
|
||||
result.add(parsed);
|
||||
continue;
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
if (!line.isBlank()) {
|
||||
LogType type = line.contains("[FLAG]") ? LogType.FLAG
|
||||
: line.contains("[PUNISH]") ? LogType.PUNISH
|
||||
: line.contains("[PROBE]") ? LogType.PROBE
|
||||
: line.contains("[ADMIN]") ? LogType.ADMIN : LogType.INFO;
|
||||
result.add(new LogEntry(file.lastModified(), type, line, null));
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.WARNING, "Could not read log file for " + uniqueId, e);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<UUID> listLoggedPlayers() {
|
||||
File[] files = logsDir.listFiles((dir, name) -> name.endsWith(".log"));
|
||||
if (files == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<UUID> uuids = new ArrayList<>();
|
||||
for (File f : files) {
|
||||
String base = f.getName().substring(0, f.getName().length() - 4);
|
||||
try {
|
||||
uuids.add(UUID.fromString(base));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
return uuids;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Live per-session verification state for a connected player (reconstructed from IlIlIlIIIIIIllI).
|
||||
*/
|
||||
public final class PlayerProfile {
|
||||
private final UUID uniqueId;
|
||||
private final long joinTimeMillis;
|
||||
private final ProxyState proxyState = new ProxyState();
|
||||
|
||||
private final Set<String> channels = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> allChannels = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> filteredChannels = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> detectedMods = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> alertedMods = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> alertedKeys = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> alertedCombinations = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> violations = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> sessionViolations = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> lastTranslatedKeys = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> lastMissingKeys = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> flaggedMods = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> clientReportedMods = ConcurrentHashMap.newKeySet();
|
||||
|
||||
private volatile ProbeStatus probeStatus = ProbeStatus.NOT_STARTED;
|
||||
private volatile boolean alreadyPunished;
|
||||
private volatile boolean initialChannelsRegistered;
|
||||
private volatile String virtualHost;
|
||||
private volatile long threatLevel;
|
||||
|
||||
public PlayerProfile(UUID uniqueId) {
|
||||
this.uniqueId = uniqueId;
|
||||
this.joinTimeMillis = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
public UUID getUniqueId() { return uniqueId; }
|
||||
public long getJoinTimeMillis() { return joinTimeMillis; }
|
||||
public ProxyState getProxyState() { return proxyState; }
|
||||
|
||||
public Set<String> getChannels() { return Collections.unmodifiableSet(channels); }
|
||||
public Set<String> getAllChannels() { return Collections.unmodifiableSet(allChannels); }
|
||||
public Set<String> getFilteredChannels() { return Collections.unmodifiableSet(filteredChannels); }
|
||||
public Set<String> getDetectedMods() { return Collections.unmodifiableSet(detectedMods); }
|
||||
public Set<String> getAlertedMods() { return Collections.unmodifiableSet(alertedMods); }
|
||||
public Set<String> getAlertedKeys() { return Collections.unmodifiableSet(alertedKeys); }
|
||||
public Set<String> getAlertedCombinations() { return Collections.unmodifiableSet(alertedCombinations); }
|
||||
public Set<String> getViolations() { return Collections.unmodifiableSet(violations); }
|
||||
public Set<String> getSessionViolations() { return Collections.unmodifiableSet(sessionViolations); }
|
||||
public Set<String> getLastTranslatedKeys() { return Collections.unmodifiableSet(lastTranslatedKeys); }
|
||||
public Set<String> getLastMissingKeys() { return Collections.unmodifiableSet(lastMissingKeys); }
|
||||
public Set<String> getFlaggedMods() { return Collections.unmodifiableSet(flaggedMods); }
|
||||
public Set<String> getClientReportedMods() { return Collections.unmodifiableSet(clientReportedMods); }
|
||||
|
||||
public void addChannel(String channel, boolean filtered) {
|
||||
if (channel == null || channel.isBlank()) {
|
||||
return;
|
||||
}
|
||||
allChannels.add(channel);
|
||||
channels.add(channel);
|
||||
if (filtered) {
|
||||
filteredChannels.add(channel);
|
||||
}
|
||||
}
|
||||
|
||||
public void addDetectedMod(String mod) {
|
||||
if (mod != null && !mod.isBlank()) {
|
||||
detectedMods.add(mod);
|
||||
}
|
||||
}
|
||||
|
||||
public void addAlertedMod(String mod) {
|
||||
if (mod != null && !mod.isBlank()) {
|
||||
alertedMods.add(mod);
|
||||
flaggedMods.add(mod);
|
||||
}
|
||||
}
|
||||
|
||||
public void addAlertedKey(String key) {
|
||||
if (key != null && !key.isBlank()) {
|
||||
alertedKeys.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
public void addAlertedCombination(String combo) {
|
||||
if (combo != null && !combo.isBlank()) {
|
||||
alertedCombinations.add(combo);
|
||||
}
|
||||
}
|
||||
|
||||
public void addViolation(String reason) {
|
||||
if (reason != null && !reason.isBlank()) {
|
||||
violations.add(reason);
|
||||
sessionViolations.add(reason);
|
||||
}
|
||||
}
|
||||
|
||||
public void addClientReportedMod(String mod) {
|
||||
if (mod != null && !mod.isBlank()) {
|
||||
clientReportedMods.add(mod);
|
||||
}
|
||||
}
|
||||
|
||||
public void setLastProbeKeys(Set<String> translated, Set<String> missing) {
|
||||
lastTranslatedKeys.clear();
|
||||
if (translated != null) lastTranslatedKeys.addAll(translated);
|
||||
lastMissingKeys.clear();
|
||||
if (missing != null) lastMissingKeys.addAll(missing);
|
||||
}
|
||||
|
||||
public ProbeStatus getProbeStatus() { return probeStatus; }
|
||||
public void setProbeStatus(ProbeStatus probeStatus) { this.probeStatus = probeStatus == null ? ProbeStatus.NOT_STARTED : probeStatus; }
|
||||
public boolean isAlreadyPunished() { return alreadyPunished; }
|
||||
public void setAlreadyPunished(boolean alreadyPunished) { this.alreadyPunished = alreadyPunished; }
|
||||
public boolean isInitialChannelsRegistered() { return initialChannelsRegistered; }
|
||||
public void setInitialChannelsRegistered(boolean initialChannelsRegistered) { this.initialChannelsRegistered = initialChannelsRegistered; }
|
||||
public String getVirtualHost() { return virtualHost; }
|
||||
public void setVirtualHost(String virtualHost) { this.virtualHost = virtualHost; }
|
||||
public long getThreatLevel() { return threatLevel; }
|
||||
public synchronized long addThreatLevel(long delta) {
|
||||
this.threatLevel = Math.max(0L, this.threatLevel + delta);
|
||||
return this.threatLevel;
|
||||
}
|
||||
public synchronized void setThreatLevel(long threatLevel) {
|
||||
this.threatLevel = Math.max(0L, threatLevel);
|
||||
}
|
||||
|
||||
public PlayerSnapshotData toSnapshotData(String brand, String version, String locale, String os, boolean bedrock) {
|
||||
return new PlayerSnapshotData(
|
||||
brand,
|
||||
version,
|
||||
locale,
|
||||
os,
|
||||
bedrock,
|
||||
new LinkedHashSet<>(channels),
|
||||
new LinkedHashSet<>(detectedMods),
|
||||
new LinkedHashSet<>(violations),
|
||||
new LinkedHashSet<>(flaggedMods)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Serializable snapshot of a player's state embedded inside log entries.
|
||||
*/
|
||||
public final class PlayerSnapshotData {
|
||||
private String brand;
|
||||
private String version;
|
||||
private String locale;
|
||||
private String operatingSystem;
|
||||
private boolean bedrock;
|
||||
private Set<String> channels = new LinkedHashSet<>();
|
||||
private Set<String> detectedMods = new LinkedHashSet<>();
|
||||
private Set<String> violations = new LinkedHashSet<>();
|
||||
private Set<String> flaggedMods = new LinkedHashSet<>();
|
||||
|
||||
public PlayerSnapshotData() {
|
||||
}
|
||||
|
||||
public PlayerSnapshotData(
|
||||
String brand,
|
||||
String version,
|
||||
String locale,
|
||||
String operatingSystem,
|
||||
boolean bedrock,
|
||||
Set<String> channels,
|
||||
Set<String> detectedMods,
|
||||
Set<String> violations,
|
||||
Set<String> flaggedMods
|
||||
) {
|
||||
this.brand = brand;
|
||||
this.version = version;
|
||||
this.locale = locale;
|
||||
this.operatingSystem = operatingSystem;
|
||||
this.bedrock = bedrock;
|
||||
if (channels != null) this.channels.addAll(channels);
|
||||
if (detectedMods != null) this.detectedMods.addAll(detectedMods);
|
||||
if (violations != null) this.violations.addAll(violations);
|
||||
if (flaggedMods != null) this.flaggedMods.addAll(flaggedMods);
|
||||
}
|
||||
|
||||
public String getBrand() { return brand; }
|
||||
public String getVersion() { return version; }
|
||||
public String getLocale() { return locale; }
|
||||
public String getOperatingSystem() { return operatingSystem; }
|
||||
public boolean isBedrock() { return bedrock; }
|
||||
public Set<String> getChannels() { return channels; }
|
||||
public Set<String> getDetectedMods() { return detectedMods; }
|
||||
public Set<String> getViolations() { return violations; }
|
||||
public Set<String> getFlaggedMods() { return flaggedMods; }
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.logging.Level;
|
||||
|
||||
/**
|
||||
* Persistent Gson storage for player identity fingerprints, alt-account clusters, and staff alert preferences
|
||||
* (reconstructed from lIlIIlllllIIlII).
|
||||
*/
|
||||
public final class PlayerStorageManager {
|
||||
private static final Type PLAYER_MAP_TYPE = new TypeToken<Map<String, StoredPlayerRecord>>() {}.getType();
|
||||
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final File storageDir;
|
||||
private final File playerMapFile;
|
||||
private final File staffPrefsFile;
|
||||
private final Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||
|
||||
private final Map<UUID, StoredPlayerRecord> recordsByUuid = new ConcurrentHashMap<>();
|
||||
private final Map<String, Set<UUID>> uuidsByFingerprint = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Boolean> staffAlertPrefs = new ConcurrentHashMap<>();
|
||||
private final AtomicLong nextClusterId = new AtomicLong(1L);
|
||||
|
||||
public static final class StoredPlayerRecord {
|
||||
public String uuid;
|
||||
public String lastName;
|
||||
public String fingerprint;
|
||||
public long clusterId;
|
||||
public long firstSeen;
|
||||
public long lastSeen;
|
||||
public boolean banned;
|
||||
public boolean flagged;
|
||||
}
|
||||
|
||||
public PlayerStorageManager(AntiSpoofPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.storageDir = new File(plugin.getDataFolder(), "data");
|
||||
if (!storageDir.exists()) {
|
||||
storageDir.mkdirs();
|
||||
}
|
||||
this.playerMapFile = new File(storageDir, "player_map.json");
|
||||
this.staffPrefsFile = new File(storageDir, "staff_alerts.json");
|
||||
loadAll();
|
||||
}
|
||||
|
||||
public synchronized void loadAll() {
|
||||
recordsByUuid.clear();
|
||||
uuidsByFingerprint.clear();
|
||||
if (playerMapFile.exists()) {
|
||||
try {
|
||||
String json = Files.readString(playerMapFile.toPath(), StandardCharsets.UTF_8);
|
||||
Map<String, StoredPlayerRecord> map = gson.fromJson(json, PLAYER_MAP_TYPE);
|
||||
if (map != null) {
|
||||
long maxCluster = 0L;
|
||||
for (Map.Entry<String, StoredPlayerRecord> e : map.entrySet()) {
|
||||
try {
|
||||
UUID u = UUID.fromString(e.getKey());
|
||||
StoredPlayerRecord rec = e.getValue();
|
||||
if (rec == null) continue;
|
||||
rec.uuid = u.toString();
|
||||
recordsByUuid.put(u, rec);
|
||||
if (rec.fingerprint != null && !rec.fingerprint.isBlank()) {
|
||||
uuidsByFingerprint.computeIfAbsent(rec.fingerprint, k -> ConcurrentHashMap.newKeySet()).add(u);
|
||||
}
|
||||
if (rec.clusterId > maxCluster) {
|
||||
maxCluster = rec.clusterId;
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
nextClusterId.set(maxCluster + 1L);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
plugin.getLogger().log(Level.WARNING, "Failed to load player_map.json", e);
|
||||
}
|
||||
}
|
||||
staffAlertPrefs.clear();
|
||||
if (staffPrefsFile.exists()) {
|
||||
try {
|
||||
Type prefType = new TypeToken<Map<String, Boolean>>() {}.getType();
|
||||
Map<String, Boolean> map = gson.fromJson(Files.readString(staffPrefsFile.toPath(), StandardCharsets.UTF_8), prefType);
|
||||
if (map != null) {
|
||||
for (Map.Entry<String, Boolean> e : map.entrySet()) {
|
||||
try {
|
||||
staffAlertPrefs.put(UUID.fromString(e.getKey()), Boolean.TRUE.equals(e.getValue()));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
plugin.getLogger().log(Level.WARNING, "Failed to load staff_alerts.json", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void saveAll() {
|
||||
try {
|
||||
Map<String, StoredPlayerRecord> out = new LinkedHashMap<>();
|
||||
for (Map.Entry<UUID, StoredPlayerRecord> e : recordsByUuid.entrySet()) {
|
||||
out.put(e.getKey().toString(), e.getValue());
|
||||
}
|
||||
Files.writeString(playerMapFile.toPath(), gson.toJson(out), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.WARNING, "Failed to save player_map.json", e);
|
||||
}
|
||||
try {
|
||||
Map<String, Boolean> out = new LinkedHashMap<>();
|
||||
for (Map.Entry<UUID, Boolean> e : staffAlertPrefs.entrySet()) {
|
||||
out.put(e.getKey().toString(), e.getValue());
|
||||
}
|
||||
Files.writeString(staffPrefsFile.toPath(), gson.toJson(out), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
plugin.getLogger().log(Level.WARNING, "Failed to save staff_alerts.json", e);
|
||||
}
|
||||
}
|
||||
|
||||
public long recordIdentity(UUID uuid, String name, String fingerprint, long timestamp, boolean flagged, boolean banned) {
|
||||
if (uuid == null || fingerprint == null || fingerprint.isBlank()) {
|
||||
return -1L;
|
||||
}
|
||||
Set<UUID> existing = uuidsByFingerprint.computeIfAbsent(fingerprint, k -> ConcurrentHashMap.newKeySet());
|
||||
long clusterId = -1L;
|
||||
for (UUID member : existing) {
|
||||
StoredPlayerRecord mr = recordsByUuid.get(member);
|
||||
if (mr != null && mr.clusterId > 0L) {
|
||||
clusterId = mr.clusterId;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (clusterId <= 0L) {
|
||||
clusterId = nextClusterId.getAndIncrement();
|
||||
}
|
||||
final long assignedCluster = clusterId;
|
||||
StoredPlayerRecord rec = recordsByUuid.computeIfAbsent(uuid, k -> {
|
||||
StoredPlayerRecord r = new StoredPlayerRecord();
|
||||
r.uuid = uuid.toString();
|
||||
r.firstSeen = timestamp;
|
||||
return r;
|
||||
});
|
||||
rec.lastName = name;
|
||||
rec.fingerprint = fingerprint;
|
||||
rec.clusterId = assignedCluster;
|
||||
rec.lastSeen = timestamp;
|
||||
if (flagged) rec.flagged = true;
|
||||
if (banned) rec.banned = true;
|
||||
existing.add(uuid);
|
||||
saveAll();
|
||||
return assignedCluster;
|
||||
}
|
||||
|
||||
public Optional<String> getFingerprint(UUID uuid) {
|
||||
StoredPlayerRecord rec = recordsByUuid.get(uuid);
|
||||
return rec == null || rec.fingerprint == null ? Optional.empty() : Optional.of(rec.fingerprint);
|
||||
}
|
||||
|
||||
public Optional<IdentityRecord> getIdentityRecord(UUID uuid) {
|
||||
StoredPlayerRecord rec = recordsByUuid.get(uuid);
|
||||
if (rec == null || rec.fingerprint == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Set<UUID> cluster = uuidsByFingerprint.getOrDefault(rec.fingerprint, Collections.emptySet());
|
||||
List<String> all = new ArrayList<>();
|
||||
List<String> alts = new ArrayList<>();
|
||||
for (UUID member : cluster) {
|
||||
StoredPlayerRecord mr = recordsByUuid.get(member);
|
||||
String label = mr != null && mr.lastName != null ? mr.lastName : member.toString();
|
||||
all.add(label);
|
||||
if (!member.equals(uuid)) {
|
||||
alts.add(label);
|
||||
}
|
||||
}
|
||||
return Optional.of(new IdentityRecord(all, alts));
|
||||
}
|
||||
|
||||
public Set<UUID> getLinkedAccounts(UUID uuid) {
|
||||
StoredPlayerRecord rec = recordsByUuid.get(uuid);
|
||||
if (rec == null || rec.fingerprint == null) {
|
||||
return Collections.emptySet();
|
||||
}
|
||||
return Collections.unmodifiableSet(new LinkedHashSet<>(uuidsByFingerprint.getOrDefault(rec.fingerprint, Set.of())));
|
||||
}
|
||||
|
||||
public Map<UUID, StoredPlayerRecord> getAllRecords() {
|
||||
return Collections.unmodifiableMap(recordsByUuid);
|
||||
}
|
||||
|
||||
public Boolean getStaffAlertPreference(UUID uuid) {
|
||||
return staffAlertPrefs.get(uuid);
|
||||
}
|
||||
|
||||
public void setStaffAlertPreference(UUID uuid, boolean enabled) {
|
||||
staffAlertPrefs.put(uuid, enabled);
|
||||
saveAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum ProbeKeyType {
|
||||
TRANSLATE,
|
||||
KEYBIND,
|
||||
BOTH
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum ProbeMode {
|
||||
SIGN,
|
||||
ANVIL,
|
||||
BOTH;
|
||||
|
||||
public static ProbeMode parse(String raw, ProbeMode fallback) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
return valueOf(raw.trim().toUpperCase(java.util.Locale.ROOT));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum ProbeStatus {
|
||||
NOT_STARTED,
|
||||
RUNNING,
|
||||
CLEAN,
|
||||
FAILED
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum ProbeStepResult {
|
||||
WAITING,
|
||||
FAILED,
|
||||
SUCCEEDED
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public record ProxyEvaluation(
|
||||
boolean enabled,
|
||||
boolean snifferActive,
|
||||
ProxyMetrics metrics,
|
||||
int minSamples,
|
||||
int warnThresholdMs,
|
||||
int thresholdMs,
|
||||
double averageDiffMs,
|
||||
double minDiffMs,
|
||||
double maxDiffMs,
|
||||
double lastDiffMs,
|
||||
boolean suspected,
|
||||
boolean warning,
|
||||
String status
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record ProxyMetrics(
|
||||
long handshakeRttMs,
|
||||
long lastPingMs,
|
||||
String lastPingSource,
|
||||
long lastDiffMs,
|
||||
double averageDiffMs,
|
||||
long minDiffMs,
|
||||
long maxDiffMs,
|
||||
int sampleCount,
|
||||
long lastSampleAt,
|
||||
List<Long> recentDiffs,
|
||||
List<Long> recentPings,
|
||||
List<Long> recentHandshakeRtts
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Per-player sliding window tracking TCP handshake RTT vs in-game KeepAlive/Ping RTT for proxy/VPN heuristics.
|
||||
*/
|
||||
public final class ProxyState {
|
||||
private static final int MAX_HISTORY = 32;
|
||||
|
||||
private final Deque<Long> recentDiffs = new ArrayDeque<>();
|
||||
private final Deque<Long> recentPings = new ArrayDeque<>();
|
||||
private final Deque<Long> recentHandshakeRtts = new ArrayDeque<>();
|
||||
|
||||
private long handshakeRttMs;
|
||||
private long lastPingMs;
|
||||
private String lastPingSource;
|
||||
private long lastDiffMs;
|
||||
private long lastSampleAt;
|
||||
|
||||
public synchronized void recordHandshakeRtt(long rttMs) {
|
||||
if (rttMs <= 0L) {
|
||||
return;
|
||||
}
|
||||
this.handshakeRttMs = rttMs;
|
||||
recentHandshakeRtts.addLast(rttMs);
|
||||
while (recentHandshakeRtts.size() > MAX_HISTORY) {
|
||||
recentHandshakeRtts.removeFirst();
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void recordPingSample(long pingMs, String source) {
|
||||
if (pingMs < 0L) {
|
||||
return;
|
||||
}
|
||||
this.lastPingMs = pingMs;
|
||||
this.lastPingSource = source;
|
||||
this.lastSampleAt = System.currentTimeMillis();
|
||||
recentPings.addLast(pingMs);
|
||||
while (recentPings.size() > MAX_HISTORY) {
|
||||
recentPings.removeFirst();
|
||||
}
|
||||
if (handshakeRttMs > 0L) {
|
||||
long diff = Math.abs(pingMs - handshakeRttMs);
|
||||
this.lastDiffMs = diff;
|
||||
recentDiffs.addLast(diff);
|
||||
while (recentDiffs.size() > MAX_HISTORY) {
|
||||
recentDiffs.removeFirst();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized ProxyMetrics snapshot(int windowSize) {
|
||||
int limit = windowSize > 0 ? Math.min(windowSize, recentDiffs.size()) : recentDiffs.size();
|
||||
List<Long> diffs = tail(recentDiffs, limit);
|
||||
List<Long> pings = tail(recentPings, windowSize > 0 ? windowSize : recentPings.size());
|
||||
List<Long> handshakes = tail(recentHandshakeRtts, windowSize > 0 ? windowSize : recentHandshakeRtts.size());
|
||||
|
||||
long sum = 0L;
|
||||
long min = diffs.isEmpty() ? 0L : Long.MAX_VALUE;
|
||||
long max = diffs.isEmpty() ? 0L : Long.MIN_VALUE;
|
||||
for (long d : diffs) {
|
||||
sum += d;
|
||||
if (d < min) min = d;
|
||||
if (d > max) max = d;
|
||||
}
|
||||
double avg = diffs.isEmpty() ? 0.0 : (double) sum / diffs.size();
|
||||
return new ProxyMetrics(
|
||||
handshakeRttMs,
|
||||
lastPingMs,
|
||||
lastPingSource,
|
||||
lastDiffMs,
|
||||
avg,
|
||||
min,
|
||||
max,
|
||||
diffs.size(),
|
||||
lastSampleAt,
|
||||
diffs,
|
||||
pings,
|
||||
handshakes
|
||||
);
|
||||
}
|
||||
|
||||
private static List<Long> tail(Deque<Long> deque, int max) {
|
||||
if (deque.isEmpty() || max <= 0) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> all = new ArrayList<>(deque);
|
||||
if (all.size() <= max) {
|
||||
return List.copyOf(all);
|
||||
}
|
||||
return List.copyOf(all.subList(all.size() - max, all.size()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum SurgeGuardAction {
|
||||
OFF,
|
||||
DELAY,
|
||||
BYPASS
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum TimeRange {
|
||||
WEEK,
|
||||
MONTH,
|
||||
ALL
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum TranslationOutcome {
|
||||
TRANSLATED,
|
||||
REQUIRED_MISS,
|
||||
MISSING_SEGMENT,
|
||||
ZERO
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.gigazelensky.antispoof.data;
|
||||
|
||||
public enum VerificationSubsystem {
|
||||
TRANSLATABLE,
|
||||
ANVIL,
|
||||
COMMAND_BOOK,
|
||||
IDENTITY_LINKER,
|
||||
ASSET_PROBE,
|
||||
PROXY,
|
||||
ACTIVE_RECON
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.gigazelensky.antispoof.fingerprint;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
|
||||
public record Ipv4Endpoint(Inet4Address address, int port) {
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.gigazelensky.antispoof.fingerprint;
|
||||
|
||||
public enum OperatingSystem {
|
||||
LINUX("Linux", OsSignaturePresets.LINUX),
|
||||
WINDOWS("Windows", OsSignaturePresets.WINDOWS),
|
||||
APPLE("macOS", OsSignaturePresets.APPLE);
|
||||
|
||||
private final String displayName;
|
||||
private final TcpSignature referenceSignature;
|
||||
|
||||
OperatingSystem(String displayName, TcpSignature referenceSignature) {
|
||||
this.displayName = displayName;
|
||||
this.referenceSignature = referenceSignature;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public TcpSignature getReferenceSignature() {
|
||||
return referenceSignature;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.gigazelensky.antispoof.fingerprint;
|
||||
|
||||
import com.gigazelensky.antispoof.config.ConfigManager;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.data.OsInfo;
|
||||
import java.util.Optional;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* High-level OS detection service combining Bedrock/Floodgate detection and passive TCP SYN fingerprinting.
|
||||
*/
|
||||
public final class OsDetectorService {
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final ConfigManager config;
|
||||
|
||||
public OsDetectorService(AntiSpoofPlugin plugin, ConfigManager config) {
|
||||
this.plugin = plugin;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return config != null && config.isOsDetectionEnabled();
|
||||
}
|
||||
|
||||
public Optional<OsInfo> detectOs(Player player) {
|
||||
return detectOs(player, true);
|
||||
}
|
||||
|
||||
public Optional<OsInfo> detectOs(Player player, boolean includeBedrock) {
|
||||
if (player == null || !isEnabled()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (includeBedrock && plugin.isBedrock(player)) {
|
||||
OsInfo bedrock = new OsInfo("Bedrock", 1.0, "bedrock");
|
||||
plugin.cacheOsInfo(player.getUniqueId(), bedrock);
|
||||
return Optional.of(bedrock);
|
||||
}
|
||||
OsInfo cached = plugin.getOsInfo(player.getUniqueId());
|
||||
if (cached != null && !"Unknown".equalsIgnoreCase(cached.getOsName())) {
|
||||
return Optional.of(cached);
|
||||
}
|
||||
OsFingerprintManager fp = plugin.getOsFingerprintManager();
|
||||
if (fp != null && player.getAddress() != null) {
|
||||
Optional<OsInfo> detected = fp.classify(player.getAddress());
|
||||
if (detected.isPresent()) {
|
||||
plugin.cacheOsInfo(player.getUniqueId(), detected.get());
|
||||
return detected;
|
||||
}
|
||||
}
|
||||
return Optional.ofNullable(cached);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.gigazelensky.antispoof.fingerprint;
|
||||
|
||||
import com.gigazelensky.antispoof.data.OsInfo;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.time.Duration;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Coordinates passive Pcap4J TCP SYN sniffing and weighted OS signature classification.
|
||||
*/
|
||||
public final class OsFingerprintManager {
|
||||
private final TcpSynCache cache;
|
||||
private final PcapSnifferThread snifferThread;
|
||||
|
||||
public OsFingerprintManager(Logger logger, String interfaceName, int[] ports, Duration cacheTtl) {
|
||||
this.cache = new TcpSynCache(cacheTtl);
|
||||
this.snifferThread = new PcapSnifferThread(logger, interfaceName, ports, cache);
|
||||
}
|
||||
|
||||
public void start() {
|
||||
if (!snifferThread.isAlive()) {
|
||||
snifferThread.start();
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
snifferThread.shutdown();
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
public boolean isSnifferActive() {
|
||||
return snifferThread.isActive();
|
||||
}
|
||||
|
||||
public TcpSynCache getCache() {
|
||||
return cache;
|
||||
}
|
||||
|
||||
public Optional<OsInfo> classify(InetSocketAddress remote) {
|
||||
Optional<TcpSignature> optSig = cache.findSignature(remote);
|
||||
if (optSig.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(classifySignature(optSig.get()));
|
||||
}
|
||||
|
||||
public OsInfo classifySignature(TcpSignature observed) {
|
||||
OperatingSystem bestOs = null;
|
||||
double bestScore = -1.0;
|
||||
Map<OperatingSystem, Double> scores = new EnumMap<>(OperatingSystem.class);
|
||||
for (OperatingSystem os : OperatingSystem.values()) {
|
||||
double score = observed.similarityTo(os.getReferenceSignature());
|
||||
scores.put(os, score);
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestOs = os;
|
||||
}
|
||||
}
|
||||
if (bestOs == null || bestScore < 0.35) {
|
||||
return new OsInfo("Unknown", Math.max(0.0, bestScore), "tcp-syn");
|
||||
}
|
||||
return new OsInfo(bestOs.getDisplayName(), bestScore, "tcp-syn");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.gigazelensky.antispoof.fingerprint;
|
||||
|
||||
import java.util.EnumMap;
|
||||
|
||||
/**
|
||||
* Reference IPv4/TCP SYN signatures for Linux, Windows, and macOS (exact values from AntiSpoof 1.5.0).
|
||||
*/
|
||||
public final class OsSignaturePresets {
|
||||
public static final TcpSignature LINUX;
|
||||
public static final TcpSignature WINDOWS;
|
||||
public static final TcpSignature APPLE;
|
||||
|
||||
static {
|
||||
EnumMap<TcpFingerprintFeature, Object> linux = new EnumMap<>(TcpFingerprintFeature.class);
|
||||
linux.put(TcpFingerprintFeature.IP_TOTAL_LEN, 60);
|
||||
linux.put(TcpFingerprintFeature.IP_IDENTIFICATION, 61394);
|
||||
linux.put(TcpFingerprintFeature.IP_TIME_TO_LIVE, 50);
|
||||
linux.put(TcpFingerprintFeature.TCP_OPTIONS, "Maximum Segment Size|SACK Permitted|Timestamps|No Operation|Window Scale");
|
||||
linux.put(TcpFingerprintFeature.TCP_OFFSET, 10);
|
||||
linux.put(TcpFingerprintFeature.TCP_WINDOW_SCALING, 7);
|
||||
linux.put(TcpFingerprintFeature.TCP_WINDOW_SIZE, 64240);
|
||||
linux.put(TcpFingerprintFeature.TCP_TIMESTAMP, 687336770);
|
||||
linux.put(TcpFingerprintFeature.TCP_TIMESTAMP_ECHO_REPLY, 0);
|
||||
linux.put(TcpFingerprintFeature.TCP_MAXIMUM_SEGMENT_SIZE, 1460);
|
||||
LINUX = new TcpSignature(linux);
|
||||
|
||||
EnumMap<TcpFingerprintFeature, Object> windows = new EnumMap<>(TcpFingerprintFeature.class);
|
||||
windows.put(TcpFingerprintFeature.IP_TOTAL_LEN, 52);
|
||||
windows.put(TcpFingerprintFeature.IP_IDENTIFICATION, 44594);
|
||||
windows.put(TcpFingerprintFeature.IP_TIME_TO_LIVE, 111);
|
||||
windows.put(TcpFingerprintFeature.TCP_OPTIONS, "Maximum Segment Size|No Operation|Window Scale|No Operation|No Operation|SACK Permitted");
|
||||
windows.put(TcpFingerprintFeature.TCP_OFFSET, 8);
|
||||
windows.put(TcpFingerprintFeature.TCP_WINDOW_SCALING, 8);
|
||||
windows.put(TcpFingerprintFeature.TCP_WINDOW_SIZE, 64240);
|
||||
windows.put(TcpFingerprintFeature.TCP_MAXIMUM_SEGMENT_SIZE, 1452);
|
||||
WINDOWS = new TcpSignature(windows);
|
||||
|
||||
EnumMap<TcpFingerprintFeature, Object> apple = new EnumMap<>(TcpFingerprintFeature.class);
|
||||
apple.put(TcpFingerprintFeature.IP_TOTAL_LEN, 64);
|
||||
apple.put(TcpFingerprintFeature.IP_IDENTIFICATION, 0);
|
||||
apple.put(TcpFingerprintFeature.IP_TIME_TO_LIVE, 50);
|
||||
apple.put(TcpFingerprintFeature.TCP_OPTIONS, "");
|
||||
apple.put(TcpFingerprintFeature.TCP_OFFSET, 11);
|
||||
apple.put(TcpFingerprintFeature.TCP_WINDOW_SCALING, 6);
|
||||
apple.put(TcpFingerprintFeature.TCP_WINDOW_SIZE, 65535);
|
||||
apple.put(TcpFingerprintFeature.TCP_TIMESTAMP, 661931028);
|
||||
apple.put(TcpFingerprintFeature.TCP_TIMESTAMP_ECHO_REPLY, 0);
|
||||
apple.put(TcpFingerprintFeature.TCP_MAXIMUM_SEGMENT_SIZE, 1460);
|
||||
APPLE = new TcpSignature(apple);
|
||||
}
|
||||
|
||||
private OsSignaturePresets() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package com.gigazelensky.antispoof.fingerprint;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import org.pcap4j.core.BpfProgram;
|
||||
import org.pcap4j.core.PcapHandle;
|
||||
import org.pcap4j.core.PcapNetworkInterface;
|
||||
import org.pcap4j.core.Pcaps;
|
||||
import org.pcap4j.packet.IpV4Packet;
|
||||
import org.pcap4j.packet.Packet;
|
||||
import org.pcap4j.packet.TcpPacket;
|
||||
|
||||
/**
|
||||
* Passive Pcap4J TCP SYN/ACK sniffer thread used for OS fingerprinting and proxy handshake RTT measurement.
|
||||
* Gracefully degrades if libpcap/Npcap is unavailable or lacks capture permissions.
|
||||
*/
|
||||
public final class PcapSnifferThread extends Thread {
|
||||
private final Logger logger;
|
||||
private final String interfaceName;
|
||||
private final int[] targetPorts;
|
||||
private final TcpSynCache cache;
|
||||
private final Set<Consumer<TcpSynPacketRecord>> listeners = new CopyOnWriteArraySet<>();
|
||||
private volatile PcapHandle handle;
|
||||
private volatile boolean active;
|
||||
|
||||
public PcapSnifferThread(Logger logger, String interfaceName, int[] targetPorts, TcpSynCache cache) {
|
||||
super("AntiSpoof-PcapSniffer");
|
||||
setDaemon(true);
|
||||
this.logger = logger;
|
||||
this.interfaceName = interfaceName;
|
||||
this.targetPorts = targetPorts == null ? new int[0] : Arrays.stream(targetPorts).filter(p -> p > 0).distinct().toArray();
|
||||
this.cache = cache;
|
||||
}
|
||||
|
||||
public void addSynListener(Consumer<TcpSynPacketRecord> listener) {
|
||||
if (listener != null) {
|
||||
listeners.add(listener);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (targetPorts.length == 0) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
PcapNetworkInterface nif = resolveInterface();
|
||||
if (nif == null) {
|
||||
logger.info("[TCP Sniffer] No suitable capture interface found; passive TCP fingerprinting disabled.");
|
||||
return;
|
||||
}
|
||||
handle = nif.openLive(65536, PcapNetworkInterface.PromiscuousMode.NONPROMISCUOUS, 50);
|
||||
String filter = buildBpfFilter(targetPorts);
|
||||
handle.setFilter(filter, BpfProgram.BpfCompileMode.OPTIMIZE);
|
||||
active = true;
|
||||
logger.info("[TCP Sniffer] Listening on " + nif.getName() + " with filter: " + filter);
|
||||
|
||||
handle.loop(-1, (Packet packet) -> {
|
||||
if (!active || packet == null) {
|
||||
return;
|
||||
}
|
||||
IpV4Packet ip = packet.get(IpV4Packet.class);
|
||||
TcpPacket tcp = packet.get(TcpPacket.class);
|
||||
if (ip == null || tcp == null) {
|
||||
return;
|
||||
}
|
||||
TcpPacket.TcpHeader tcpHeader = tcp.getHeader();
|
||||
IpV4Packet.IpV4Header ipHeader = ip.getHeader();
|
||||
if (tcpHeader.getSyn() && !tcpHeader.getAck()) {
|
||||
TcpSynPacketRecord rec = new TcpSynPacketRecord(Instant.now(), ipHeader, tcpHeader);
|
||||
cache.recordSyn(rec);
|
||||
for (Consumer<TcpSynPacketRecord> l : listeners) {
|
||||
try {
|
||||
l.accept(rec);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
} else if (tcpHeader.getAck() && !tcpHeader.getSyn()) {
|
||||
Inet4Address src = ipHeader.getSrcAddr();
|
||||
cache.recordAck(src, tcpHeader.getSrcPort().valueAsInt(), System.currentTimeMillis());
|
||||
}
|
||||
});
|
||||
} catch (UnsatisfiedLinkError | NoClassDefFoundError e) {
|
||||
logger.info("[TCP Sniffer] Native libpcap/Npcap unavailable (" + e.getMessage() + "); falling back to non-pcap checks.");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (Throwable t) {
|
||||
if (active) {
|
||||
logger.log(Level.WARNING, "[TCP Sniffer] Stopped due to error: " + t.getMessage());
|
||||
}
|
||||
} finally {
|
||||
active = false;
|
||||
closeHandle();
|
||||
}
|
||||
}
|
||||
|
||||
private PcapNetworkInterface resolveInterface() throws Exception {
|
||||
if (interfaceName != null && !interfaceName.isBlank() && !"auto".equalsIgnoreCase(interfaceName)) {
|
||||
PcapNetworkInterface explicit = Pcaps.getDevByName(interfaceName);
|
||||
if (explicit != null) {
|
||||
return explicit;
|
||||
}
|
||||
}
|
||||
for (PcapNetworkInterface nif : Pcaps.findAllDevs()) {
|
||||
if (!nif.isLoopBack() && nif.isUp() && !nif.getAddresses().isEmpty()) {
|
||||
return nif;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String buildBpfFilter(int[] ports) {
|
||||
StringBuilder sb = new StringBuilder("ip and tcp and (");
|
||||
for (int i = 0; i < ports.length; i++) {
|
||||
if (i > 0) {
|
||||
sb.append(" or ");
|
||||
}
|
||||
sb.append("dst port ").append(ports[i]);
|
||||
}
|
||||
sb.append(") and (tcp[tcpflags] & (tcp-syn|tcp-ack) != 0)");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
active = false;
|
||||
closeHandle();
|
||||
interrupt();
|
||||
}
|
||||
|
||||
private void closeHandle() {
|
||||
PcapHandle h = handle;
|
||||
handle = null;
|
||||
if (h != null && h.isOpen()) {
|
||||
try {
|
||||
h.breakLoop();
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
try {
|
||||
h.close();
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.gigazelensky.antispoof.fingerprint;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.StringJoiner;
|
||||
import org.pcap4j.packet.IpV4Packet.IpV4Header;
|
||||
import org.pcap4j.packet.TcpMaximumSegmentSizeOption;
|
||||
import org.pcap4j.packet.TcpPacket.TcpHeader;
|
||||
import org.pcap4j.packet.TcpPacket.TcpOption;
|
||||
import org.pcap4j.packet.TcpTimestampsOption;
|
||||
import org.pcap4j.packet.TcpWindowScaleOption;
|
||||
import org.pcap4j.packet.namednumber.TcpOptionKind;
|
||||
|
||||
/**
|
||||
* Passive TCP/IPv4 SYN fingerprint features and exact matching weights.
|
||||
*/
|
||||
public enum TcpFingerprintFeature {
|
||||
IP_TOTAL_LEN(Integer.class, 5.0),
|
||||
IP_IDENTIFICATION(Integer.class, 3.0),
|
||||
IP_TIME_TO_LIVE(Integer.class, 2.0),
|
||||
TCP_OPTIONS(String.class, 5.0),
|
||||
TCP_OFFSET(Integer.class, 5.0),
|
||||
TCP_WINDOW_SCALING(Integer.class, 3.0),
|
||||
TCP_WINDOW_SIZE(Integer.class, 2.0),
|
||||
TCP_TIMESTAMP(Integer.class, 2.0),
|
||||
TCP_TIMESTAMP_ECHO_REPLY(Integer.class, 2.0),
|
||||
TCP_MAXIMUM_SEGMENT_SIZE(Integer.class, 1.0);
|
||||
|
||||
private final Class<?> valueType;
|
||||
private final double weight;
|
||||
|
||||
TcpFingerprintFeature(Class<?> valueType, double weight) {
|
||||
this.valueType = valueType;
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public Class<?> getValueType() {
|
||||
return valueType;
|
||||
}
|
||||
|
||||
public double getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public Optional<Object> extract(IpV4Header ip, TcpHeader tcp) {
|
||||
if (ip == null || tcp == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return switch (this) {
|
||||
case IP_TOTAL_LEN -> Optional.of(ip.getTotalLengthAsInt());
|
||||
case IP_IDENTIFICATION -> Optional.of(ip.getIdentificationAsInt());
|
||||
case IP_TIME_TO_LIVE -> Optional.of(ip.getTtlAsInt());
|
||||
case TCP_OFFSET -> Optional.of((int) tcp.getDataOffset());
|
||||
case TCP_WINDOW_SIZE -> Optional.of(tcp.getWindowAsInt());
|
||||
case TCP_OPTIONS -> {
|
||||
StringJoiner joiner = new StringJoiner("|");
|
||||
for (TcpOption opt : tcp.getOptions()) {
|
||||
if (opt != null && opt.getKind() != null) {
|
||||
joiner.add(opt.getKind().name());
|
||||
}
|
||||
}
|
||||
yield Optional.of(joiner.toString());
|
||||
}
|
||||
case TCP_WINDOW_SCALING -> {
|
||||
for (TcpOption opt : tcp.getOptions()) {
|
||||
if (opt instanceof TcpWindowScaleOption ws && opt.getKind().equals(TcpOptionKind.WINDOW_SCALE)) {
|
||||
yield Optional.of(ws.getShiftCountAsInt());
|
||||
}
|
||||
}
|
||||
yield Optional.empty();
|
||||
}
|
||||
case TCP_TIMESTAMP -> {
|
||||
for (TcpOption opt : tcp.getOptions()) {
|
||||
if (opt instanceof TcpTimestampsOption ts && opt.getKind().equals(TcpOptionKind.TIMESTAMPS)) {
|
||||
yield Optional.of(ts.getTsValue());
|
||||
}
|
||||
}
|
||||
yield Optional.empty();
|
||||
}
|
||||
case TCP_TIMESTAMP_ECHO_REPLY -> {
|
||||
for (TcpOption opt : tcp.getOptions()) {
|
||||
if (opt instanceof TcpTimestampsOption ts && opt.getKind().equals(TcpOptionKind.TIMESTAMPS)) {
|
||||
yield Optional.of(ts.getTsEchoReply());
|
||||
}
|
||||
}
|
||||
yield Optional.empty();
|
||||
}
|
||||
case TCP_MAXIMUM_SEGMENT_SIZE -> {
|
||||
for (TcpOption opt : tcp.getOptions()) {
|
||||
if (opt instanceof TcpMaximumSegmentSizeOption mss && opt.getKind().equals(TcpOptionKind.MAXIMUM_SEGMENT_SIZE)) {
|
||||
yield Optional.of(mss.getMaxSegSizeAsInt());
|
||||
}
|
||||
}
|
||||
yield Optional.empty();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public Optional<Object> getFrom(Map<TcpFingerprintFeature, Object> map) {
|
||||
Object val = map.get(this);
|
||||
if (val == null || !valueType.isInstance(val)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(valueType.cast(val));
|
||||
}
|
||||
|
||||
public double scoreSimilarity(Object observed, Object reference) {
|
||||
if (observed == null || reference == null) {
|
||||
return 0.0;
|
||||
}
|
||||
if (this == TCP_OPTIONS) {
|
||||
String a = String.valueOf(observed);
|
||||
String b = String.valueOf(reference);
|
||||
if (a.equals(b)) {
|
||||
return 1.0;
|
||||
}
|
||||
if (a.isEmpty() || b.isEmpty()) {
|
||||
return 0.0;
|
||||
}
|
||||
String[] pa = a.split("\\|");
|
||||
String[] pb = b.split("\\|");
|
||||
int matches = 0;
|
||||
int max = Math.max(pa.length, pb.length);
|
||||
for (int i = 0; i < Math.min(pa.length, pb.length); i++) {
|
||||
if (pa[i].equals(pb[i])) {
|
||||
matches++;
|
||||
}
|
||||
}
|
||||
return (double) matches / max;
|
||||
}
|
||||
if (observed instanceof Integer oi && reference instanceof Integer ri) {
|
||||
return switch (this) {
|
||||
case IP_TIME_TO_LIVE -> {
|
||||
int diff = Math.abs(oi - ri);
|
||||
if (diff <= 16) yield 1.0;
|
||||
if (diff <= 32) yield 0.5;
|
||||
yield 0.0;
|
||||
}
|
||||
case IP_IDENTIFICATION -> {
|
||||
boolean oz = oi == 0;
|
||||
boolean rz = ri == 0;
|
||||
yield (oz == rz) ? 1.0 : 0.0;
|
||||
}
|
||||
case TCP_TIMESTAMP -> (oi != 0 && ri != 0) ? 1.0 : (oi.equals(ri) ? 1.0 : 0.0);
|
||||
case TCP_MAXIMUM_SEGMENT_SIZE -> Math.abs(oi - ri) <= 60 ? 1.0 : 0.0;
|
||||
case TCP_WINDOW_SIZE -> Math.abs(oi - ri) <= 1024 ? 1.0 : 0.0;
|
||||
default -> oi.equals(ri) ? 1.0 : 0.0;
|
||||
};
|
||||
}
|
||||
return observed.equals(reference) ? 1.0 : 0.0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.gigazelensky.antispoof.fingerprint;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import org.pcap4j.packet.IpV4Packet.IpV4Header;
|
||||
import org.pcap4j.packet.TcpPacket.TcpHeader;
|
||||
|
||||
public record TcpSignature(Map<TcpFingerprintFeature, Object> features) {
|
||||
public TcpSignature {
|
||||
EnumMap<TcpFingerprintFeature, Object> copy = new EnumMap<>(TcpFingerprintFeature.class);
|
||||
if (features != null) {
|
||||
copy.putAll(features);
|
||||
}
|
||||
features = Collections.unmodifiableMap(copy);
|
||||
}
|
||||
|
||||
public static TcpSignature fromHeaders(IpV4Header ip, TcpHeader tcp) {
|
||||
EnumMap<TcpFingerprintFeature, Object> map = new EnumMap<>(TcpFingerprintFeature.class);
|
||||
for (TcpFingerprintFeature feature : TcpFingerprintFeature.values()) {
|
||||
feature.extract(ip, tcp).ifPresent(val -> map.put(feature, val));
|
||||
}
|
||||
return new TcpSignature(map);
|
||||
}
|
||||
|
||||
public double similarityTo(TcpSignature reference) {
|
||||
if (reference == null) {
|
||||
return 0.0;
|
||||
}
|
||||
double weightedScore = 0.0;
|
||||
double totalWeight = 0.0;
|
||||
for (TcpFingerprintFeature feature : TcpFingerprintFeature.values()) {
|
||||
Object obs = features.get(feature);
|
||||
Object ref = reference.features.get(feature);
|
||||
if (ref == null && obs == null) {
|
||||
continue;
|
||||
}
|
||||
totalWeight += feature.getWeight();
|
||||
if (obs != null && ref != null) {
|
||||
weightedScore += feature.getWeight() * feature.scoreSimilarity(obs, ref);
|
||||
}
|
||||
}
|
||||
return totalWeight == 0.0 ? 0.0 : weightedScore / totalWeight;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.gigazelensky.antispoof.fingerprint;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import org.pcap4j.packet.IpV4Packet.IpV4Header;
|
||||
import org.pcap4j.packet.TcpPacket.TcpHeader;
|
||||
|
||||
/**
|
||||
* Caffeine-backed cache mapping client IPv4 endpoints to observed TCP SYN signatures and handshake RTTs.
|
||||
*/
|
||||
public final class TcpSynCache {
|
||||
private final Cache<Ipv4Endpoint, TcpSignature> signatureByEndpoint;
|
||||
private final Cache<Inet4Address, TcpSignature> signatureByIp;
|
||||
private final Cache<Ipv4Endpoint, Long> synTimestampByEndpoint;
|
||||
private final Cache<Ipv4Endpoint, Long> handshakeRttByEndpoint;
|
||||
private final Cache<Inet4Address, Long> handshakeRttByIp;
|
||||
|
||||
public TcpSynCache(Duration ttl) {
|
||||
Duration effective = ttl == null ? Duration.ofMinutes(5) : ttl;
|
||||
this.signatureByEndpoint = Caffeine.newBuilder().expireAfterWrite(effective).maximumSize(10_000).build();
|
||||
this.signatureByIp = Caffeine.newBuilder().expireAfterWrite(effective).maximumSize(10_000).build();
|
||||
this.synTimestampByEndpoint = Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(30)).maximumSize(10_000).build();
|
||||
this.handshakeRttByEndpoint = Caffeine.newBuilder().expireAfterWrite(effective).maximumSize(10_000).build();
|
||||
this.handshakeRttByIp = Caffeine.newBuilder().expireAfterWrite(effective).maximumSize(10_000).build();
|
||||
}
|
||||
|
||||
public void recordSyn(TcpSynPacketRecord packet) {
|
||||
if (packet == null || packet.ipv4Header() == null || packet.tcpHeader() == null) {
|
||||
return;
|
||||
}
|
||||
IpV4Header ip = packet.ipv4Header();
|
||||
TcpHeader tcp = packet.tcpHeader();
|
||||
Inet4Address srcIp = ip.getSrcAddr();
|
||||
int srcPort = tcp.getSrcPort().valueAsInt();
|
||||
Ipv4Endpoint endpoint = new Ipv4Endpoint(srcIp, srcPort);
|
||||
TcpSignature sig = TcpSignature.fromHeaders(ip, tcp);
|
||||
signatureByEndpoint.put(endpoint, sig);
|
||||
signatureByIp.put(srcIp, sig);
|
||||
synTimestampByEndpoint.put(endpoint, packet.timestamp().toEpochMilli());
|
||||
}
|
||||
|
||||
public void recordAck(Inet4Address srcIp, int srcPort, long ackMillis) {
|
||||
if (srcIp == null) {
|
||||
return;
|
||||
}
|
||||
Ipv4Endpoint endpoint = new Ipv4Endpoint(srcIp, srcPort);
|
||||
Long synMillis = synTimestampByEndpoint.getIfPresent(endpoint);
|
||||
if (synMillis != null) {
|
||||
synTimestampByEndpoint.invalidate(endpoint);
|
||||
long rtt = ackMillis - synMillis;
|
||||
if (rtt >= 0L && rtt <= 15_000L) {
|
||||
handshakeRttByEndpoint.put(endpoint, rtt);
|
||||
handshakeRttByIp.put(srcIp, rtt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<TcpSignature> findSignature(InetSocketAddress remote) {
|
||||
if (remote == null || !(remote.getAddress() instanceof Inet4Address ipv4)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
TcpSignature exact = signatureByEndpoint.getIfPresent(new Ipv4Endpoint(ipv4, remote.getPort()));
|
||||
if (exact != null) {
|
||||
return Optional.of(exact);
|
||||
}
|
||||
return Optional.ofNullable(signatureByIp.getIfPresent(ipv4));
|
||||
}
|
||||
|
||||
public Optional<Long> findHandshakeRttMs(InetSocketAddress remote) {
|
||||
if (remote == null || !(remote.getAddress() instanceof Inet4Address ipv4)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Long exact = handshakeRttByEndpoint.getIfPresent(new Ipv4Endpoint(ipv4, remote.getPort()));
|
||||
if (exact != null) {
|
||||
return Optional.of(exact);
|
||||
}
|
||||
return Optional.ofNullable(handshakeRttByIp.getIfPresent(ipv4));
|
||||
}
|
||||
|
||||
public Optional<Long> findHandshakeRttMs(InetAddress addr) {
|
||||
if (!(addr instanceof Inet4Address ipv4)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(handshakeRttByIp.getIfPresent(ipv4));
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
signatureByEndpoint.invalidateAll();
|
||||
signatureByIp.invalidateAll();
|
||||
synTimestampByEndpoint.invalidateAll();
|
||||
handshakeRttByEndpoint.invalidateAll();
|
||||
handshakeRttByIp.invalidateAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.gigazelensky.antispoof.fingerprint;
|
||||
|
||||
import java.time.Instant;
|
||||
import org.pcap4j.packet.IpV4Packet.IpV4Header;
|
||||
import org.pcap4j.packet.TcpPacket.TcpHeader;
|
||||
|
||||
public record TcpSynPacketRecord(Instant timestamp, IpV4Header ipv4Header, TcpHeader tcpHeader) {
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.gigazelensky.antispoof.gui;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.util.TextUtil;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Base InventoryHolder menu for all AntiSpoof management screens (reconstructed from lIlIIlIlIIlIlll).
|
||||
*/
|
||||
public abstract class BaseGui implements InventoryHolder {
|
||||
protected final AntiSpoofPlugin plugin;
|
||||
protected final Player viewer;
|
||||
protected final Map<Integer, GuiItem> items = new HashMap<>();
|
||||
protected Inventory inventory;
|
||||
|
||||
protected BaseGui(AntiSpoofPlugin plugin, Player viewer) {
|
||||
this.plugin = plugin;
|
||||
this.viewer = viewer;
|
||||
}
|
||||
|
||||
public abstract String getPermission();
|
||||
|
||||
public abstract String getTitle();
|
||||
|
||||
public abstract int getSize();
|
||||
|
||||
protected abstract void populate();
|
||||
|
||||
public void open() {
|
||||
if (viewer == null || !viewer.isOnline()) {
|
||||
return;
|
||||
}
|
||||
String perm = getPermission();
|
||||
if (perm != null && !perm.isBlank() && !viewer.hasPermission(perm) && !viewer.hasPermission("antispoof.admin")) {
|
||||
viewer.sendMessage(TextUtil.toComponent("&cYou don't have permission to access this section."));
|
||||
return;
|
||||
}
|
||||
this.inventory = Bukkit.createInventory(this, getSize(), TextUtil.toComponent(getTitle()));
|
||||
refresh();
|
||||
viewer.openInventory(inventory);
|
||||
}
|
||||
|
||||
public void refresh() {
|
||||
if (inventory == null) {
|
||||
return;
|
||||
}
|
||||
inventory.clear();
|
||||
items.clear();
|
||||
populate();
|
||||
for (Map.Entry<Integer, GuiItem> e : items.entrySet()) {
|
||||
int slot = e.getKey();
|
||||
if (slot >= 0 && slot < inventory.getSize()) {
|
||||
inventory.setItem(slot, e.getValue().getIcon());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void setItem(int slot, GuiItem item) {
|
||||
if (slot >= 0 && slot < getSize() && item != null) {
|
||||
items.put(slot, item);
|
||||
}
|
||||
}
|
||||
|
||||
protected void fillEmpty(Material glass) {
|
||||
GuiItem filler = new GuiItem(new ItemBuilder(glass).name(" ").build());
|
||||
for (int i = 0; i < getSize(); i++) {
|
||||
items.putIfAbsent(i, filler);
|
||||
}
|
||||
}
|
||||
|
||||
public void handleClick(InventoryClickEvent event) {
|
||||
event.setCancelled(true);
|
||||
GuiItem item = items.get(event.getRawSlot());
|
||||
if (item != null) {
|
||||
item.handleClick(event);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull Inventory getInventory() {
|
||||
return inventory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.gigazelensky.antispoof.gui;
|
||||
|
||||
import com.gigazelensky.antispoof.config.BrandRuleConfig;
|
||||
import com.gigazelensky.antispoof.config.ConfigToggleWriter;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.util.TextUtil;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* Paginated Client Brands management GUI (reconstructed from IlIlIIIllIlllll).
|
||||
*/
|
||||
public final class ClientBrandsGui extends BaseGui {
|
||||
private static final int PAGE_SIZE = 28;
|
||||
private final int page;
|
||||
|
||||
public ClientBrandsGui(AntiSpoofPlugin plugin, Player viewer, int page) {
|
||||
super(plugin, viewer);
|
||||
this.page = Math.max(0, page);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermission() {
|
||||
return "antispoof.gui.detections";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTitle() {
|
||||
List<BrandRuleConfig> rules = new ArrayList<>(plugin.getConfigManager().getBrandRules().values());
|
||||
int totalPages = Math.max(1, (int) Math.ceil((double) rules.size() / PAGE_SIZE));
|
||||
return "ᭉF8&lClient Brands &8(&f" + (page + 1) + "&8/&7" + totalPages + "&8)";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSize() {
|
||||
return 45;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void populate() {
|
||||
List<BrandRuleConfig> rules = new ArrayList<>(plugin.getConfigManager().getBrandRules().values());
|
||||
int start = page * PAGE_SIZE;
|
||||
int end = Math.min(rules.size(), start + PAGE_SIZE);
|
||||
int slot = 0;
|
||||
for (int i = start; i < end; i++) {
|
||||
BrandRuleConfig rule = rules.get(i);
|
||||
setItem(slot++, new GuiItem(
|
||||
new ItemBuilder(rule.isEnabled() ? Material.LIME_DYE : Material.GRAY_DYE)
|
||||
.name("&b" + rule.getId())
|
||||
.lore(
|
||||
"&7Enabled: " + (rule.isEnabled() ? "&aYes" : "&cNo"),
|
||||
"&7Allowed: " + (rule.isAllowed() ? "&aYes" : "&cBlocked"),
|
||||
"&7Matchers: &f" + String.join(", ", rule.getBrandMatchers()),
|
||||
"&7Required Channels: &f" + (rule.getRequiredChannels().isEmpty() ? "None" : String.join(", ", rule.getRequiredChannels())),
|
||||
"",
|
||||
"&eLeft-click to toggle enabled"
|
||||
)
|
||||
.build(),
|
||||
e -> {
|
||||
boolean ok = ConfigToggleWriter.setValue(
|
||||
plugin.getConfigManager().getBrandsConfigFile(),
|
||||
"client-brands.brands." + rule.getId() + ".enabled",
|
||||
!rule.isEnabled(),
|
||||
plugin.getLogger()
|
||||
);
|
||||
if (ok) {
|
||||
plugin.getConfigManager().reload();
|
||||
refresh();
|
||||
} else {
|
||||
viewer.sendMessage(TextUtil.toComponent("&cFailed to persist brand toggle changes."));
|
||||
}
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
if (page > 0) {
|
||||
setItem(36, new GuiItem(new ItemBuilder(Material.ARROW).name("&ePrevious Page").build(), e -> new ClientBrandsGui(plugin, viewer, page - 1).open()));
|
||||
}
|
||||
setItem(40, new GuiItem(new ItemBuilder(Material.ARROW).name("&eBack to Main Menu").build(), e -> new MainMenuGui(plugin, viewer).open()));
|
||||
if (end < rules.size()) {
|
||||
setItem(44, new GuiItem(new ItemBuilder(Material.ARROW).name("&eNext Page").build(), e -> new ClientBrandsGui(plugin, viewer, page + 1).open()));
|
||||
}
|
||||
fillEmpty(Material.GRAY_STAINED_GLASS_PANE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.gigazelensky.antispoof.gui;
|
||||
|
||||
import com.gigazelensky.antispoof.config.ConfigManager;
|
||||
import com.gigazelensky.antispoof.config.ConfigToggleWriter;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.util.TextUtil;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* Live configuration toggle GUI (reconstructed from llIIlllllIIlllI).
|
||||
*/
|
||||
public final class ConfigGui extends BaseGui {
|
||||
public ConfigGui(AntiSpoofPlugin plugin, Player viewer) {
|
||||
super(plugin, viewer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermission() {
|
||||
return "antispoof.gui.config";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTitle() {
|
||||
return "&#AF42F3&lConfiguration";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSize() {
|
||||
return 36;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void populate() {
|
||||
ConfigManager cfg = plugin.getConfigManager();
|
||||
|
||||
addToggle(10, Material.GRASS_BLOCK, "&bVanilla Spoof Check", "vanillaspoof-check.enabled", cfg.getVanillaSpoofRule().isEnabled());
|
||||
addToggle(11, Material.PAPER, "&bNo Brand Check", "no-brand-check.enabled", cfg.getNoBrandRule().isEnabled());
|
||||
addToggle(12, Material.IRON_BARS, "&bBlocked Channels", "blocked-channels.enabled", cfg.getBlockedChannelRule().isEnabled());
|
||||
addToggle(13, Material.OAK_SIGN, "&bTranslatable Key Probes", "translatable-keys.enabled", cfg.isTranslatableEnabled());
|
||||
addToggle(14, Material.COMPASS, "&bProxy Detection", "proxy-detection.enabled", cfg.isProxyDetectionEnabled());
|
||||
addToggle(15, Material.REDSTONE_TORCH, "&bOS Detection", "os-detection.enabled", cfg.isOsDetectionEnabled());
|
||||
addToggle(16, Material.SPYGLASS, "&bTCP SYN Sniffer", "os-detection.use-tcp-sniffer", cfg.isOsUseTcpSniffer());
|
||||
|
||||
addToggle(19, Material.ENDER_EYE, "&dLunar Client Checks", "lunar.enabled", cfg.isLunarEnabled());
|
||||
addToggle(20, Material.FEATHER, "&dFeather Client Checks", "feather.enabled", cfg.isFeatherEnabled());
|
||||
addToggle(21, Material.GOLD_INGOT, "&dBadlion Client Checks", "badlion.enabled", cfg.isBadlionEnabled());
|
||||
addToggle(22, Material.NETHER_STAR, "&dLabyMod Checks", "labymod.enabled", cfg.isLabyModEnabled());
|
||||
addToggle(23, Material.SHIELD, "&eSurge Guard", "surge-guard.enabled", cfg.isSurgeGuardEnabled());
|
||||
addToggle(24, Material.WRITABLE_BOOK, "&aFile Logging", "logs.enabled", cfg.isLogsEnabled());
|
||||
addToggle(25, Material.BELL, "&aConsistent Staff Alerts", "alerts.consistent", cfg.isAlertsConsistent());
|
||||
|
||||
setItem(31, new GuiItem(
|
||||
new ItemBuilder(Material.ARROW).name("&eBack to Main Menu").build(),
|
||||
e -> new MainMenuGui(plugin, viewer).open()
|
||||
));
|
||||
|
||||
fillEmpty(Material.BLACK_STAINED_GLASS_PANE);
|
||||
}
|
||||
|
||||
private void addToggle(int slot, Material mat, String title, String configPath, boolean current) {
|
||||
setItem(slot, new GuiItem(
|
||||
new ItemBuilder(mat)
|
||||
.name(title)
|
||||
.lore(
|
||||
"&7Status: " + (current ? "&aENABLED" : "&cDISABLED"),
|
||||
"&7Key: &f" + configPath,
|
||||
"",
|
||||
"&eClick to toggle"
|
||||
)
|
||||
.glow(current)
|
||||
.hideAttributes()
|
||||
.build(),
|
||||
e -> {
|
||||
boolean ok = ConfigToggleWriter.setValue(plugin.getConfigManager().getConfigFile(), configPath, !current, plugin.getLogger());
|
||||
if (ok) {
|
||||
plugin.getConfigManager().reload();
|
||||
refresh();
|
||||
} else {
|
||||
viewer.sendMessage(TextUtil.toComponent("&cFailed to save configuration. Check console for details."));
|
||||
}
|
||||
}
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.gigazelensky.antispoof.gui;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
/**
|
||||
* Clickable slot entry in a BaseGui menu (reconstructed from lIIIlIIIlIlIIlI).
|
||||
*/
|
||||
public final class GuiItem {
|
||||
private final ItemStack icon;
|
||||
private final Consumer<InventoryClickEvent> clickHandler;
|
||||
|
||||
public GuiItem(ItemStack icon) {
|
||||
this(icon, null);
|
||||
}
|
||||
|
||||
public GuiItem(ItemStack icon, Consumer<InventoryClickEvent> clickHandler) {
|
||||
this.icon = icon;
|
||||
this.clickHandler = clickHandler;
|
||||
}
|
||||
|
||||
public ItemStack getIcon() {
|
||||
return icon;
|
||||
}
|
||||
|
||||
public void handleClick(InventoryClickEvent event) {
|
||||
if (clickHandler != null) {
|
||||
clickHandler.accept(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.gigazelensky.antispoof.gui;
|
||||
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
|
||||
/**
|
||||
* Routes clicks inside AntiSpoof BaseGui menus (reconstructed from IlIIllIIIlllIlI).
|
||||
*/
|
||||
public final class GuiListener implements Listener {
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
if (event.getView().getTopInventory() == null) {
|
||||
return;
|
||||
}
|
||||
InventoryHolder holder = event.getView().getTopInventory().getHolder();
|
||||
if (holder instanceof BaseGui gui) {
|
||||
event.setCancelled(true);
|
||||
if (event.getClickedInventory() != null && event.getClickedInventory().equals(event.getView().getTopInventory())) {
|
||||
gui.handleClick(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.gigazelensky.antispoof.gui;
|
||||
|
||||
import com.gigazelensky.antispoof.util.TextUtil;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.inventory.meta.SkullMeta;
|
||||
|
||||
/**
|
||||
* Fluent ItemStack builder for AntiSpoof management GUIs (reconstructed from IIIllIIlIIllIlI).
|
||||
*/
|
||||
public final class ItemBuilder {
|
||||
private final ItemStack stack;
|
||||
|
||||
public ItemBuilder(Material material) {
|
||||
this.stack = new ItemStack(material == null ? Material.STONE : material);
|
||||
}
|
||||
|
||||
public ItemBuilder(ItemStack base) {
|
||||
this.stack = base == null ? new ItemStack(Material.STONE) : base.clone();
|
||||
}
|
||||
|
||||
public ItemBuilder name(String name) {
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
if (meta != null && name != null) {
|
||||
meta.displayName(TextUtil.toComponent(name));
|
||||
stack.setItemMeta(meta);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder lore(String... lines) {
|
||||
return lore(Arrays.asList(lines));
|
||||
}
|
||||
|
||||
public ItemBuilder lore(List<String> lines) {
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
if (meta != null && lines != null) {
|
||||
List<Component> comps = new ArrayList<>(lines.size());
|
||||
for (String line : lines) {
|
||||
comps.add(TextUtil.toComponent(line));
|
||||
}
|
||||
meta.lore(comps);
|
||||
stack.setItemMeta(meta);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder glow(boolean enabled) {
|
||||
if (!enabled) {
|
||||
return this;
|
||||
}
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.addEnchant(Enchantment.UNBREAKING, 1, true);
|
||||
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
|
||||
stack.setItemMeta(meta);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder hideAttributes() {
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
|
||||
stack.setItemMeta(meta);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemBuilder skullOwner(OfflinePlayer owner) {
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
if (meta instanceof SkullMeta skull && owner != null) {
|
||||
skull.setOwningPlayer(owner);
|
||||
stack.setItemMeta(skull);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemStack build() {
|
||||
return stack;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.gigazelensky.antispoof.gui;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.data.TimeRange;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* Historical flag leaderboard & log browser GUI (reconstructed from llllllIIIlIIIII).
|
||||
*/
|
||||
public final class LogSnapshotGui extends BaseGui {
|
||||
public LogSnapshotGui(AntiSpoofPlugin plugin, Player viewer) {
|
||||
super(plugin, viewer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermission() {
|
||||
return "antispoof.gui.logs";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTitle() {
|
||||
return "&#A853F3&lLog Snapshot";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSize() {
|
||||
return 36;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void populate() {
|
||||
Map<UUID, Integer> board = plugin.getLogReaderParser().getFlagLeaderboard(TimeRange.ALL);
|
||||
int slot = 0;
|
||||
for (Map.Entry<UUID, Integer> e : board.entrySet()) {
|
||||
if (slot >= 27) break;
|
||||
OfflinePlayer op = Bukkit.getOfflinePlayer(e.getKey());
|
||||
String name = op.getName() != null ? op.getName() : e.getKey().toString();
|
||||
setItem(slot++, new GuiItem(
|
||||
new ItemBuilder(Material.PAPER)
|
||||
.name("&f" + name)
|
||||
.lore(
|
||||
"&7UUID: &8" + e.getKey(),
|
||||
"&7Total Flags: &c" + e.getValue()
|
||||
)
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
setItem(31, new GuiItem(
|
||||
new ItemBuilder(Material.ARROW).name("&eBack to Main Menu").build(),
|
||||
e -> new MainMenuGui(plugin, viewer).open()
|
||||
));
|
||||
fillEmpty(Material.GRAY_STAINED_GLASS_PANE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.gigazelensky.antispoof.gui;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* AntiSpoof Main Management Menu (reconstructed from IlIIIIIlIlIIIIl, DRM traps removed).
|
||||
*/
|
||||
public final class MainMenuGui extends BaseGui {
|
||||
public MainMenuGui(AntiSpoofPlugin plugin, Player viewer) {
|
||||
super(plugin, viewer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermission() {
|
||||
return "antispoof.gui";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTitle() {
|
||||
return "C7FD&lAntiSpoof &8- Main Menu";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSize() {
|
||||
return 27;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void populate() {
|
||||
setItem(10, new GuiItem(
|
||||
new ItemBuilder(Material.PLAYER_HEAD)
|
||||
.name(".A6FA&lOnline Players")
|
||||
.lore(
|
||||
"&7Inspect online players, client brands,",
|
||||
"&7channels, detected mods, OS, and proxy RTT.",
|
||||
"",
|
||||
"&7Online: &f" + Bukkit.getOnlinePlayers().size(),
|
||||
"&eClick to browse players"
|
||||
)
|
||||
.build(),
|
||||
e -> new PlayerListGui(plugin, viewer, 0).open()
|
||||
));
|
||||
|
||||
setItem(12, new GuiItem(
|
||||
new ItemBuilder(Material.COMPARATOR)
|
||||
.name("&#AF42F3&lConfiguration")
|
||||
.lore(
|
||||
"&7Toggle detection checks, client spoof",
|
||||
"&7rules, and OS/proxy verification live.",
|
||||
"",
|
||||
"&eClick to open configuration"
|
||||
)
|
||||
.build(),
|
||||
e -> new ConfigGui(plugin, viewer).open()
|
||||
));
|
||||
|
||||
setItem(14, new GuiItem(
|
||||
new ItemBuilder(Material.NAME_TAG)
|
||||
.name("ᭉF8&lClient Brands")
|
||||
.lore(
|
||||
"&7Manage configured client brand rules",
|
||||
"&7and channel requirements.",
|
||||
"",
|
||||
"&7Rules loaded: &f" + plugin.getConfigManager().getBrandRules().size(),
|
||||
"&eClick to open brands"
|
||||
)
|
||||
.build(),
|
||||
e -> new ClientBrandsGui(plugin, viewer, 0).open()
|
||||
));
|
||||
|
||||
setItem(16, new GuiItem(
|
||||
new ItemBuilder(Material.BOOK)
|
||||
.name("&#F38F42&lFlag Leaderboard & Logs")
|
||||
.lore(
|
||||
"&7Review historical flag counts and",
|
||||
"&7recent per-player log snapshots.",
|
||||
"",
|
||||
"&eClick to open logs"
|
||||
)
|
||||
.build(),
|
||||
e -> new LogSnapshotGui(plugin, viewer).open()
|
||||
));
|
||||
|
||||
setItem(22, new GuiItem(
|
||||
new ItemBuilder(Material.BARRIER).name("&cClose Menu").build(),
|
||||
e -> viewer.closeInventory()
|
||||
));
|
||||
|
||||
fillEmpty(Material.GRAY_STAINED_GLASS_PANE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.gigazelensky.antispoof.gui;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.data.OsInfo;
|
||||
import com.gigazelensky.antispoof.data.PlayerProfile;
|
||||
import com.gigazelensky.antispoof.data.ProxyEvaluation;
|
||||
import com.gigazelensky.antispoof.probe.ProxyDetectionManager;
|
||||
import com.gigazelensky.antispoof.util.TextUtil;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* Detailed per-player inspection GUI (reconstructed from IlllllIlIlllIIl).
|
||||
*/
|
||||
public final class PlayerInfoGui extends BaseGui {
|
||||
private final Player target;
|
||||
|
||||
public PlayerInfoGui(AntiSpoofPlugin plugin, Player viewer, Player target) {
|
||||
super(plugin, viewer);
|
||||
this.target = target;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermission() {
|
||||
return "antispoof.gui.playerinfo";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTitle() {
|
||||
return ".A6FAInfo: &f" + (target != null ? target.getName() : "Unknown");
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSize() {
|
||||
return 27;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void populate() {
|
||||
if (target == null || !target.isOnline()) {
|
||||
viewer.sendMessage(TextUtil.toComponent("&cThat player is no longer online."));
|
||||
viewer.closeInventory();
|
||||
return;
|
||||
}
|
||||
PlayerProfile profile = plugin.getPlayerProfiles().get(target.getUniqueId());
|
||||
String brand = plugin.getPlayerBrand(target);
|
||||
String ver = plugin.getPlayerVersion(target);
|
||||
String locale = plugin.getPlayerLocale(target);
|
||||
OsInfo os = plugin.getOsInfo(target.getUniqueId());
|
||||
|
||||
setItem(10, new GuiItem(new ItemBuilder(Material.PLAYER_HEAD)
|
||||
.skullOwner(target)
|
||||
.name("&bClient Identity")
|
||||
.lore(
|
||||
"&7Player: &f" + target.getName(),
|
||||
"&7Brand: &f" + (brand == null ? "Unknown" : brand),
|
||||
"&7Version: &f" + (ver == null ? "Unknown" : ver),
|
||||
"&7Locale: &f" + (locale == null ? "Unknown" : locale),
|
||||
"&7OS: &f" + (os == null ? "Unknown" : os.getOsName()),
|
||||
"&7Bedrock: &f" + plugin.isBedrock(target)
|
||||
)
|
||||
.build()));
|
||||
|
||||
List<String> channelLore = new ArrayList<>();
|
||||
if (profile == null || profile.getChannels().isEmpty()) {
|
||||
channelLore.add("&7None registered");
|
||||
} else {
|
||||
int shown = 0;
|
||||
for (String ch : profile.getChannels()) {
|
||||
if (shown++ >= 8) {
|
||||
channelLore.add("&7... and " + (profile.getChannels().size() - 8) + " more");
|
||||
break;
|
||||
}
|
||||
channelLore.add("&8- &f" + ch);
|
||||
}
|
||||
}
|
||||
setItem(12, new GuiItem(new ItemBuilder(Material.PAPER).name("&bPlugin Channels").lore(channelLore).build()));
|
||||
|
||||
List<String> modLore = new ArrayList<>();
|
||||
if (profile == null || profile.getDetectedMods().isEmpty()) {
|
||||
modLore.add("&aNo blocked/flagged mods detected");
|
||||
} else {
|
||||
for (String m : profile.getDetectedMods()) {
|
||||
modLore.add("&c- &f" + m);
|
||||
}
|
||||
}
|
||||
modLore.add("");
|
||||
modLore.add("&eClick to re-run mod probes");
|
||||
setItem(14, new GuiItem(
|
||||
new ItemBuilder(Material.ANVIL).name("&eDetected Mods").lore(modLore).build(),
|
||||
e -> {
|
||||
plugin.getTranslationProbeManager().runAllModProbes(target, viewer);
|
||||
viewer.sendMessage(TextUtil.toComponent("&aRe-running mod probes on &f" + target.getName()));
|
||||
}
|
||||
));
|
||||
|
||||
ProxyEvaluation proxyEval = profile != null
|
||||
? plugin.getProxyDetectionManager().evaluate(profile.getProxyState().snapshot(plugin.getConfigManager().getProxySampleWindow()))
|
||||
: null;
|
||||
setItem(16, new GuiItem(new ItemBuilder(Material.COMPASS)
|
||||
.name("&dProxy & Violations")
|
||||
.lore(
|
||||
"&7Proxy Status: &f" + (proxyEval == null ? "Unknown" : ProxyDetectionManager.formatStatusLabel(proxyEval.status())),
|
||||
"&7Threat Level: &e" + (profile == null ? 0 : profile.getThreatLevel()),
|
||||
"&7Violations: &c" + (profile == null ? 0 : profile.getViolations().size())
|
||||
)
|
||||
.build()));
|
||||
|
||||
setItem(22, new GuiItem(
|
||||
new ItemBuilder(Material.ARROW).name("&eBack to Players").build(),
|
||||
e -> new PlayerListGui(plugin, viewer, 0).open()
|
||||
));
|
||||
|
||||
fillEmpty(Material.GRAY_STAINED_GLASS_PANE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.gigazelensky.antispoof.gui;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.data.PlayerProfile;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* Paginated online player browser leading into PlayerInfoGui.
|
||||
*/
|
||||
public final class PlayerListGui extends BaseGui {
|
||||
private static final int PAGE_SIZE = 36;
|
||||
private final int page;
|
||||
|
||||
public PlayerListGui(AntiSpoofPlugin plugin, Player viewer, int page) {
|
||||
super(plugin, viewer);
|
||||
this.page = Math.max(0, page);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPermission() {
|
||||
return "antispoof.gui.playerinfo";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTitle() {
|
||||
int totalPages = Math.max(1, (int) Math.ceil((double) Bukkit.getOnlinePlayers().size() / PAGE_SIZE));
|
||||
return ".A6FAOnline Players &8(&f" + (page + 1) + "&8/&7" + totalPages + "&8)";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSize() {
|
||||
return 45;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void populate() {
|
||||
List<Player> players = new ArrayList<>(Bukkit.getOnlinePlayers());
|
||||
players.sort(Comparator.comparing(Player::getName, String.CASE_INSENSITIVE_ORDER));
|
||||
int start = page * PAGE_SIZE;
|
||||
int end = Math.min(players.size(), start + PAGE_SIZE);
|
||||
int slot = 0;
|
||||
for (int i = start; i < end; i++) {
|
||||
Player target = players.get(i);
|
||||
PlayerProfile prof = plugin.getPlayerProfiles().get(target.getUniqueId());
|
||||
String brand = plugin.getPlayerBrand(target);
|
||||
int flags = prof == null ? 0 : prof.getViolations().size();
|
||||
setItem(slot++, new GuiItem(
|
||||
new ItemBuilder(Material.PLAYER_HEAD)
|
||||
.skullOwner(target)
|
||||
.name("&b" + target.getName())
|
||||
.lore(
|
||||
"&7Brand: &f" + (brand == null ? "Unknown" : brand),
|
||||
"&7Flags: " + (flags > 0 ? "&c" + flags : "&a0"),
|
||||
"",
|
||||
"&eClick to inspect player"
|
||||
)
|
||||
.build(),
|
||||
e -> new PlayerInfoGui(plugin, viewer, target).open()
|
||||
));
|
||||
}
|
||||
|
||||
if (page > 0) {
|
||||
setItem(36, new GuiItem(new ItemBuilder(Material.ARROW).name("&ePrevious Page").build(), e -> new PlayerListGui(plugin, viewer, page - 1).open()));
|
||||
}
|
||||
setItem(40, new GuiItem(new ItemBuilder(Material.ARROW).name("&eBack to Main Menu").build(), e -> new MainMenuGui(plugin, viewer).open()));
|
||||
if (end < players.size()) {
|
||||
setItem(44, new GuiItem(new ItemBuilder(Material.ARROW).name("&eNext Page").build(), e -> new PlayerListGui(plugin, viewer, page + 1).open()));
|
||||
}
|
||||
fillEmpty(Material.GRAY_STAINED_GLASS_PANE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.gigazelensky.antispoof.hook;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* PlaceholderAPI expansion exposing %antispoof_*% placeholders (reconstructed from IllllIllIIIlIIl).
|
||||
*/
|
||||
public final class AntiSpoofPlaceholderExpansion extends PlaceholderExpansion {
|
||||
private final AntiSpoofPlugin plugin;
|
||||
|
||||
public AntiSpoofPlaceholderExpansion(AntiSpoofPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getIdentifier() {
|
||||
return "antispoof";
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getAuthor() {
|
||||
return "GigaZelensky";
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getVersion() {
|
||||
return plugin.getPluginMeta().getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean persist() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable String onRequest(OfflinePlayer player, @NotNull String params) {
|
||||
if (player == null) {
|
||||
return "";
|
||||
}
|
||||
Player online = player.getPlayer();
|
||||
return PlaceholderFormatter.resolveKey(plugin, online, player.getUniqueId(), params);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package com.gigazelensky.antispoof.hook;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.ViolationType;
|
||||
import com.gigazelensky.antispoof.data.ClientPlatform;
|
||||
import com.gigazelensky.antispoof.data.LogType;
|
||||
import com.gigazelensky.antispoof.data.PlayerProfile;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.EventExecutor;
|
||||
|
||||
/**
|
||||
* Integrates Lunar Client (Apollo), Badlion ModAPI (badlion:modapi), Feather Client,
|
||||
* LabyMod ServerAPI, and Floodgate/Geyser Bedrock detection (reconstructed from IIIllIlllIIIllI,
|
||||
* IlIllIlIlllIllI, lIIIlIIlllIlllI).
|
||||
*/
|
||||
public final class ClientApiHookManager implements Listener {
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final Map<ClientPlatform, Map<UUID, Set<String>>> modsByPlatform = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, ClientPlatform> detectedPlatform = new ConcurrentHashMap<>();
|
||||
|
||||
public ClientApiHookManager(AntiSpoofPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
for (ClientPlatform p : ClientPlatform.values()) {
|
||||
modsByPlatform.put(p, new ConcurrentHashMap<>());
|
||||
}
|
||||
}
|
||||
|
||||
public void registerHooks() {
|
||||
hookLabyModEvents();
|
||||
}
|
||||
|
||||
public void handleChannelPayload(UUID uuid, String channel, byte[] data) {
|
||||
if (uuid == null || channel == null) {
|
||||
return;
|
||||
}
|
||||
String lower = channel.toLowerCase(Locale.ROOT);
|
||||
if ("badlion:modapi".equals(lower) && plugin.getConfigManager().isBadlionEnabled()) {
|
||||
detectedPlatform.put(uuid, ClientPlatform.BADLION);
|
||||
if (plugin.getConfigManager().isDebug()) {
|
||||
plugin.getLogger().info("[Debug] Badlion Mod API channel registered by " + uuid);
|
||||
}
|
||||
parseJsonModList(uuid, ClientPlatform.BADLION, data);
|
||||
} else if ((lower.startsWith("lunarclient:") || lower.startsWith("apollo:")) && plugin.getConfigManager().isLunarEnabled()) {
|
||||
detectedPlatform.put(uuid, ClientPlatform.LUNAR);
|
||||
parseLunarApolloHandshake(uuid, data);
|
||||
} else if (lower.startsWith("feather:") && plugin.getConfigManager().isFeatherEnabled()) {
|
||||
detectedPlatform.put(uuid, ClientPlatform.FEATHER);
|
||||
parseJsonModList(uuid, ClientPlatform.FEATHER, data);
|
||||
} else if (lower.startsWith("labymod:") && plugin.getConfigManager().isLabyModEnabled()) {
|
||||
detectedPlatform.put(uuid, ClientPlatform.LABYMOD);
|
||||
parseJsonModList(uuid, ClientPlatform.LABYMOD, data);
|
||||
}
|
||||
}
|
||||
|
||||
private void parseLunarApolloHandshake(UUID uuid, byte[] data) {
|
||||
if (data == null || data.length == 0) {
|
||||
return;
|
||||
}
|
||||
String text = new String(data, StandardCharsets.UTF_8);
|
||||
PlayerProfile profile = plugin.getOrCreateProfile(uuid);
|
||||
Set<String> mods = modsByPlatform.get(ClientPlatform.LUNAR).computeIfAbsent(uuid, k -> ConcurrentHashMap.newKeySet());
|
||||
// Extract printable ASCII mod identifiers from protobuf payload
|
||||
StringBuilder tok = new StringBuilder();
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == ':') {
|
||||
tok.append(c);
|
||||
} else {
|
||||
recordCandidateMod(uuid, ClientPlatform.LUNAR, tok.toString(), mods, profile);
|
||||
tok.setLength(0);
|
||||
}
|
||||
}
|
||||
recordCandidateMod(uuid, ClientPlatform.LUNAR, tok.toString(), mods, profile);
|
||||
}
|
||||
|
||||
private void parseJsonModList(UUID uuid, ClientPlatform platform, byte[] data) {
|
||||
if (data == null || data.length == 0) {
|
||||
return;
|
||||
}
|
||||
String text = new String(data, StandardCharsets.UTF_8);
|
||||
PlayerProfile profile = plugin.getOrCreateProfile(uuid);
|
||||
Set<String> mods = modsByPlatform.get(platform).computeIfAbsent(uuid, k -> ConcurrentHashMap.newKeySet());
|
||||
for (String blocked : plugin.getConfigManager().getBlockedClientMods(platform)) {
|
||||
if (text.toLowerCase(Locale.ROOT).contains(blocked)) {
|
||||
mods.add(blocked);
|
||||
profile.addClientReportedMod(blocked);
|
||||
Player p = plugin.getServer().getPlayer(uuid);
|
||||
if (p != null) {
|
||||
String vt = platform == ClientPlatform.LUNAR ? ViolationType.LUNAR_MOD_BLOCKED : ViolationType.CLIENT_MOD_BLOCKED;
|
||||
plugin.flagPlayer(p, vt, platform.getDisplayName() + " blocked mod/addon: " + blocked);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void recordCandidateMod(UUID uuid, ClientPlatform platform, String token, Set<String> mods, PlayerProfile profile) {
|
||||
if (token.length() < 3 || token.length() > 48) {
|
||||
return;
|
||||
}
|
||||
String lower = token.toLowerCase(Locale.ROOT);
|
||||
if (lower.startsWith("lunarclient") || lower.startsWith("apollo")) {
|
||||
return;
|
||||
}
|
||||
if (plugin.getConfigManager().getBlockedClientMods(platform).contains(lower)) {
|
||||
mods.add(token);
|
||||
profile.addClientReportedMod(token);
|
||||
Player p = plugin.getServer().getPlayer(uuid);
|
||||
if (p != null) {
|
||||
plugin.flagPlayer(p, ViolationType.LUNAR_MOD_BLOCKED, "Lunar Client blocked mod: " + token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void hookLabyModEvents() {
|
||||
String[] candidateEvents = {
|
||||
"net.labymod.serverapi.server.bukkit.event.LabyModPlayerJoinEvent",
|
||||
"net.labymod.serverapi.server.bukkit.event.LabyModInstalledAddonsUpdateEvent",
|
||||
"net.labymod.serverapi.bukkit.event.LabyModPlayerJoinEvent"
|
||||
};
|
||||
boolean hooked = false;
|
||||
for (String className : candidateEvents) {
|
||||
try {
|
||||
Class<?> raw = Class.forName(className);
|
||||
if (!Event.class.isAssignableFrom(raw)) continue;
|
||||
Class<? extends Event> eventClass = (Class<? extends Event>) raw;
|
||||
EventExecutor exec = (listener, event) -> handleLabyModReflectiveEvent(event);
|
||||
Bukkit.getPluginManager().registerEvent(eventClass, this, EventPriority.MONITOR, exec, plugin, true);
|
||||
hooked = true;
|
||||
} catch (ClassNotFoundException ignored) {
|
||||
} catch (Throwable t) {
|
||||
if (plugin.getConfigManager().isDebug()) {
|
||||
plugin.getLogger().info("[Debug] Could not hook LabyMod event " + className + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hooked && plugin.getConfigManager().isDebug()) {
|
||||
plugin.getLogger().info("[Debug] Hooked LabyMod Server API events.");
|
||||
}
|
||||
}
|
||||
|
||||
private void handleLabyModReflectiveEvent(Event event) {
|
||||
try {
|
||||
Object labyPlayer = event.getClass().getMethod("labyModPlayer").invoke(event);
|
||||
if (labyPlayer == null) return;
|
||||
UUID uuid = (UUID) labyPlayer.getClass().getMethod("getUniqueId").invoke(labyPlayer);
|
||||
if (uuid == null) return;
|
||||
detectedPlatform.put(uuid, ClientPlatform.LABYMOD);
|
||||
plugin.getPlayerLogManager().log(uuid, LogType.INFO, "LabyMod ServerAPI event received: " + event.getEventName());
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isBedrockPlayer(Player player) {
|
||||
if (player == null) {
|
||||
return false;
|
||||
}
|
||||
// Check Floodgate API reflectively if present
|
||||
try {
|
||||
Class<?> apiCls = Class.forName("org.geysermc.floodgate.api.FloodgateApi");
|
||||
Object api = apiCls.getMethod("getInstance").invoke(null);
|
||||
if (api != null) {
|
||||
Object res = apiCls.getMethod("isFloodgatePlayer", UUID.class).invoke(api, player.getUniqueId());
|
||||
if (Boolean.TRUE.equals(res)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
// Fallback: Geyser UUID prefix check (00000000-0000-0000-...)
|
||||
return player.getUniqueId().getMostSignificantBits() == 0L;
|
||||
}
|
||||
|
||||
public ClientPlatform getDetectedPlatform(UUID uuid) {
|
||||
return detectedPlatform.get(uuid);
|
||||
}
|
||||
|
||||
public Set<String> getClientMods(ClientPlatform platform, UUID uuid) {
|
||||
Map<UUID, Set<String>> map = modsByPlatform.get(platform);
|
||||
if (map == null) return Set.of();
|
||||
return Collections.unmodifiableSet(map.getOrDefault(uuid, Set.of()));
|
||||
}
|
||||
|
||||
public Map<UUID, Set<String>> getAllPlatformPlayers(ClientPlatform platform) {
|
||||
return Collections.unmodifiableMap(modsByPlatform.getOrDefault(platform, Map.of()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.gigazelensky.antispoof.hook;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.data.OsInfo;
|
||||
import com.gigazelensky.antispoof.data.PlayerProfile;
|
||||
import com.gigazelensky.antispoof.data.ProxyEvaluation;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* Resolves %antispoof_<key>% placeholders for both PlaceholderAPI and punishment/alert commands
|
||||
* (reconstructed from lIIIIIlIllIllIl).
|
||||
*/
|
||||
public final class PlaceholderFormatter {
|
||||
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("%antispoof_([a-z0-9_]+)%");
|
||||
|
||||
private PlaceholderFormatter() {
|
||||
}
|
||||
|
||||
public static String resolveKey(AntiSpoofPlugin plugin, Player player, UUID uuid, String key) {
|
||||
if (plugin == null || key == null) {
|
||||
return "none";
|
||||
}
|
||||
UUID id = uuid != null ? uuid : (player != null ? player.getUniqueId() : null);
|
||||
if (id == null) {
|
||||
return "none";
|
||||
}
|
||||
PlayerProfile profile = plugin.getPlayerProfiles().get(id);
|
||||
return switch (key.toLowerCase(Locale.ROOT)) {
|
||||
case "brand", "client_brand" -> nonEmpty(plugin.getPlayerBrands().get(id), "Unknown");
|
||||
case "version", "client_version" -> nonEmpty(plugin.getPlayerVersions().get(id), "Unknown");
|
||||
case "locale" -> nonEmpty(plugin.getPlayerLocales().get(id), "Unknown");
|
||||
case "os", "operating_system" -> {
|
||||
OsInfo info = plugin.getOsInfo(id);
|
||||
yield info != null ? info.getOsName() : "Unknown";
|
||||
}
|
||||
case "os_confidence" -> {
|
||||
OsInfo info = plugin.getOsInfo(id);
|
||||
yield info != null ? String.format(Locale.ROOT, "%.0f%%", info.getConfidence() * 100.0) : "0%";
|
||||
}
|
||||
case "bedrock" -> String.valueOf(player != null && plugin.isBedrock(player));
|
||||
case "channels" -> profile == null || profile.getChannels().isEmpty() ? "none" : String.join(", ", profile.getChannels());
|
||||
case "mods", "detected_mods" -> profile == null || profile.getDetectedMods().isEmpty() ? "none" : String.join(", ", profile.getDetectedMods());
|
||||
case "violations" -> profile == null || profile.getViolations().isEmpty() ? "none" : String.join(", ", profile.getViolations());
|
||||
case "violation_count" -> String.valueOf(profile == null ? 0 : profile.getViolations().size());
|
||||
case "threat_level" -> String.valueOf(profile == null ? 0L : profile.getThreatLevel());
|
||||
case "host", "virtual_host" -> profile == null ? "Unknown" : nonEmpty(profile.getVirtualHost(), "Unknown");
|
||||
case "proxy_status" -> {
|
||||
if (profile == null || plugin.getProxyDetectionManager() == null) yield "Unknown";
|
||||
ProxyEvaluation eval = plugin.getProxyDetectionManager().evaluate(
|
||||
profile.getProxyState().snapshot(plugin.getConfigManager().getProxySampleWindow()));
|
||||
yield eval.status();
|
||||
}
|
||||
case "fingerprint" -> plugin.getIdentityLinkerManager() != null
|
||||
? plugin.getIdentityLinkerManager().getFingerprint(id).orElse("none")
|
||||
: "none";
|
||||
case "alts" -> plugin.getIdentityLinkerManager() != null
|
||||
? plugin.getIdentityLinkerManager().getIdentityRecord(id)
|
||||
.map(r -> r.getAltAccounts().isEmpty() ? "none" : String.join(", ", r.getAltAccounts()))
|
||||
.orElse("none")
|
||||
: "none";
|
||||
default -> "none";
|
||||
};
|
||||
}
|
||||
|
||||
public static String formatTemplate(AntiSpoofPlugin plugin, Player player, String template) {
|
||||
if (template == null || template.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
String out = plugin.getConfigManager().expandPrefixes(template);
|
||||
if (player != null) {
|
||||
out = out.replace("%player%", player.getName())
|
||||
.replace("%uuid%", player.getUniqueId().toString())
|
||||
.replace("%brand%", nonEmpty(plugin.getPlayerBrand(player), "Unknown"))
|
||||
.replace("%version%", nonEmpty(plugin.getPlayerVersion(player), "Unknown"));
|
||||
}
|
||||
Matcher m = PLACEHOLDER_PATTERN.matcher(out);
|
||||
StringBuffer sb = new StringBuffer();
|
||||
while (m.find()) {
|
||||
String val = resolveKey(plugin, player, player != null ? player.getUniqueId() : null, m.group(1));
|
||||
m.appendReplacement(sb, Matcher.quoteReplacement(val));
|
||||
}
|
||||
m.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String nonEmpty(String s, String fallback) {
|
||||
return s == null || s.isBlank() ? fallback : s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
package com.gigazelensky.antispoof.packet;
|
||||
|
||||
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
|
||||
import com.github.retrooper.packetevents.event.PacketListenerPriority;
|
||||
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.util.KnownPack;
|
||||
import com.github.retrooper.packetevents.wrapper.configuration.client.WrapperConfigClientPluginMessage;
|
||||
import com.github.retrooper.packetevents.wrapper.configuration.client.WrapperConfigClientSelectKnownPacks;
|
||||
import com.github.retrooper.packetevents.wrapper.handshaking.client.WrapperHandshakingClientHandshake;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPluginMessage;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientSettings;
|
||||
import com.gigazelensky.antispoof.config.BrandRuleConfig;
|
||||
import com.gigazelensky.antispoof.config.ConfigManager;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.ViolationType;
|
||||
import com.gigazelensky.antispoof.data.PlayerProfile;
|
||||
import com.gigazelensky.antispoof.util.SchedulerUtil;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerLoginEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
/**
|
||||
* Intercepts Handshake virtual host, Configuration & Play plugin messages (minecraft:brand,
|
||||
* minecraft:register, minecraft:unregister, mod API channels), and client locale settings
|
||||
* (reconstructed from llIIlIIIIlIllll + llIlIIIlIIIIlIl).
|
||||
*/
|
||||
public final class BrandChannelListener extends PacketListenerAbstract implements Listener {
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final Map<String, String> pendingVirtualHostByName = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, List<String>> configPacketTrace = new ConcurrentHashMap<>();
|
||||
|
||||
public BrandChannelListener(AntiSpoofPlugin plugin) {
|
||||
super(PacketListenerPriority.NORMAL);
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketReceive(PacketReceiveEvent event) {
|
||||
var type = event.getPacketType();
|
||||
if (type == PacketType.Handshaking.Client.HANDSHAKE) {
|
||||
WrapperHandshakingClientHandshake hs = new WrapperHandshakingClientHandshake(event);
|
||||
String host = hs.getServerAddress();
|
||||
int port = hs.getServerPort();
|
||||
String combined = (host == null ? "" : host) + ":" + port;
|
||||
if (event.getUser() != null && event.getUser().getName() != null) {
|
||||
pendingVirtualHostByName.put(event.getUser().getName().toLowerCase(Locale.ROOT), combined);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
UUID uuid = event.getUser() != null ? event.getUser().getUUID() : null;
|
||||
if (uuid == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (type == PacketType.Configuration.Client.PLUGIN_MESSAGE) {
|
||||
WrapperConfigClientPluginMessage msg = new WrapperConfigClientPluginMessage(event);
|
||||
recordConfigPacket(uuid, "PLUGIN_MSG(" + msg.getChannelName() + ",len=" + (msg.getData() == null ? 0 : msg.getData().length) + ")");
|
||||
handlePluginMessage(uuid, msg.getChannelName(), msg.getData());
|
||||
} else if (type == PacketType.Configuration.Client.CLIENT_SETTINGS) {
|
||||
recordConfigPacket(uuid, "CLIENT_SETTINGS");
|
||||
} else if (type == PacketType.Configuration.Client.SELECT_KNOWN_PACKS) {
|
||||
WrapperConfigClientSelectKnownPacks kp = new WrapperConfigClientSelectKnownPacks(event);
|
||||
List<String> packs = new ArrayList<>();
|
||||
if (kp.getKnownPacks() != null) {
|
||||
for (KnownPack p : kp.getKnownPacks()) {
|
||||
packs.add(p.getNamespace() + ":" + p.getId() + "@" + p.getVersion());
|
||||
}
|
||||
}
|
||||
recordConfigPacket(uuid, "KNOWN_PACKS" + packs);
|
||||
} else if (type == PacketType.Configuration.Client.CONFIGURATION_END_ACK) {
|
||||
recordConfigPacket(uuid, "CONFIG_END_ACK");
|
||||
List<String> trace = configPacketTrace.get(uuid);
|
||||
if (trace != null && plugin.getConfigManager().isDebug()) {
|
||||
plugin.getLogger().info("[ConfigTrace] " + event.getUser().getName() + " seq=" + trace);
|
||||
}
|
||||
} else if (type == PacketType.Play.Client.PLUGIN_MESSAGE) {
|
||||
WrapperPlayClientPluginMessage msg = new WrapperPlayClientPluginMessage(event);
|
||||
handlePluginMessage(uuid, msg.getChannelName(), msg.getData());
|
||||
} else if (type == PacketType.Play.Client.CLIENT_SETTINGS) {
|
||||
WrapperPlayClientSettings settings = new WrapperPlayClientSettings(event);
|
||||
if (settings.getLocale() != null && !settings.getLocale().isBlank()) {
|
||||
plugin.getPlayerLocales().put(uuid, settings.getLocale());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void recordConfigPacket(UUID uuid, String label) {
|
||||
configPacketTrace.computeIfAbsent(uuid, k -> java.util.Collections.synchronizedList(new ArrayList<>())).add(label);
|
||||
}
|
||||
|
||||
private void handlePluginMessage(UUID uuid, String channel, byte[] data) {
|
||||
if (channel == null || channel.isBlank()) {
|
||||
return;
|
||||
}
|
||||
String normChannel = channel.toLowerCase(Locale.ROOT);
|
||||
PlayerProfile profile = plugin.getOrCreateProfile(uuid);
|
||||
|
||||
if ("minecraft:brand".equals(normChannel) || "mc|brand".equals(normChannel)) {
|
||||
String brand = decodeVarIntString(data);
|
||||
if (!brand.isBlank()) {
|
||||
plugin.getPlayerBrands().put(uuid, brand);
|
||||
}
|
||||
profile.addChannel(normChannel, false);
|
||||
return;
|
||||
}
|
||||
|
||||
if ("minecraft:register".equals(normChannel) || "register".equals(normChannel)) {
|
||||
profile.setInitialChannelsRegistered(true);
|
||||
String payload = new String(data == null ? new byte[0] : data, StandardCharsets.UTF_8);
|
||||
for (String ch : payload.split("\0")) {
|
||||
if (!ch.isBlank()) {
|
||||
String lower = ch.trim().toLowerCase(Locale.ROOT);
|
||||
boolean filtered = !plugin.getConfigManager().getVanillaAllowedChannels().contains(lower);
|
||||
profile.addChannel(lower, filtered);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
boolean filtered = !plugin.getConfigManager().getVanillaAllowedChannels().contains(normChannel);
|
||||
profile.addChannel(normChannel, filtered);
|
||||
|
||||
// Forward client-specific channels (Badlion, Lunar Apollo, Feather, LabyMod) to ClientApiHookManager
|
||||
if (plugin.getClientApiHookManager() != null) {
|
||||
plugin.getClientApiHookManager().handleChannelPayload(uuid, normChannel, data);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onLogin(PlayerLoginEvent event) {
|
||||
String host = event.getHostname();
|
||||
if (host != null && !host.isBlank()) {
|
||||
PlayerProfile profile = plugin.getOrCreateProfile(event.getPlayer().getUniqueId());
|
||||
profile.setVirtualHost(host);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
UUID uuid = player.getUniqueId();
|
||||
PlayerProfile profile = plugin.getOrCreateProfile(uuid);
|
||||
|
||||
plugin.getSurgeGuardManager().recordJoin();
|
||||
if (profile.getVirtualHost() == null) {
|
||||
String fromHs = pendingVirtualHostByName.remove(player.getName().toLowerCase(Locale.ROOT));
|
||||
if (fromHs != null) {
|
||||
profile.setVirtualHost(fromHs);
|
||||
}
|
||||
}
|
||||
if (player.getClientBrandName() != null && !player.getClientBrandName().isBlank()) {
|
||||
plugin.getPlayerBrands().putIfAbsent(uuid, player.getClientBrandName());
|
||||
}
|
||||
plugin.getPlayerVersions().put(uuid, detectProtocolVersionLabel(player));
|
||||
if (player.locale() != null) {
|
||||
plugin.getPlayerLocales().putIfAbsent(uuid, player.locale().toString());
|
||||
}
|
||||
|
||||
// Attach TCP handshake RTT & passive OS fingerprint
|
||||
if (plugin.getProxyDetectionManager() != null) {
|
||||
plugin.getProxyDetectionManager().attachHandshakeRtt(player);
|
||||
}
|
||||
if (plugin.getOsDetectorService() != null) {
|
||||
plugin.getOsDetectorService().detectOs(player);
|
||||
}
|
||||
if (plugin.getActiveReconScanner() != null) {
|
||||
plugin.getActiveReconScanner().scanOnTrigger(player, "JOIN");
|
||||
}
|
||||
|
||||
long delayTicks = Math.max(20L, plugin.getConfigManager().getDelayInSeconds() * 20L);
|
||||
SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (!player.isOnline() || plugin.isBypassed(uuid)) {
|
||||
return;
|
||||
}
|
||||
evaluatePlayerChecks(player);
|
||||
if (!plugin.getSurgeGuardManager().isSurgeActive()) {
|
||||
if (plugin.getTranslationProbeManager() != null) {
|
||||
plugin.getTranslationProbeManager().runAllModProbes(player, null);
|
||||
}
|
||||
if (plugin.getKeySpoofRpProbeManager() != null && plugin.getKeySpoofRpProbeManager().isAvailable()) {
|
||||
SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (player.isOnline()) {
|
||||
plugin.getKeySpoofRpProbeManager().startProbe(player, null);
|
||||
}
|
||||
}, 35L);
|
||||
}
|
||||
if (plugin.getIdentityLinkerManager() != null && plugin.getIdentityLinkerManager().isEnabled()) {
|
||||
plugin.getIdentityLinkerManager().startProbe(player);
|
||||
}
|
||||
if (plugin.getAssetProbeListener() != null) {
|
||||
plugin.getAssetProbeListener().startProbes(player);
|
||||
}
|
||||
}
|
||||
}, delayTicks);
|
||||
}
|
||||
|
||||
public void evaluatePlayerChecks(Player player) {
|
||||
if (player == null || !player.isOnline()) {
|
||||
return;
|
||||
}
|
||||
UUID uuid = player.getUniqueId();
|
||||
ConfigManager cfg = plugin.getConfigManager();
|
||||
PlayerProfile profile = plugin.getOrCreateProfile(uuid);
|
||||
|
||||
String brand = plugin.getPlayerBrand(player);
|
||||
Set<String> channels = profile.getChannels();
|
||||
boolean bedrock = plugin.isBedrock(player);
|
||||
|
||||
// 1. Virtual host check
|
||||
if (cfg.getBlockedVirtualHostRule().isEnabled() && profile.getVirtualHost() != null) {
|
||||
String hostLower = profile.getVirtualHost().toLowerCase(Locale.ROOT);
|
||||
for (String blocked : cfg.getBlockedVirtualHosts()) {
|
||||
if (hostLower.contains(blocked)) {
|
||||
plugin.flagPlayer(player, ViolationType.BLOCKED_VIRTUAL_HOST, "Connected via blocked virtual host: " + profile.getVirtualHost());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Geyser spoof check
|
||||
if (cfg.getGeyserSpoofRule().isEnabled() && brand != null && brand.toLowerCase(Locale.ROOT).contains("geyser") && !bedrock) {
|
||||
plugin.flagPlayer(player, ViolationType.GEYSER_SPOOF, "Claimed Geyser brand without Floodgate/Bedrock session");
|
||||
}
|
||||
|
||||
// 3. No brand check
|
||||
if (cfg.getNoBrandRule().isEnabled() && (brand == null || brand.isBlank()) && !bedrock) {
|
||||
plugin.flagPlayer(player, ViolationType.NO_BRAND, "No client brand received after join delay");
|
||||
}
|
||||
|
||||
// 4. Vanilla spoof check (claims vanilla but registers non-vanilla channels)
|
||||
if (cfg.getVanillaSpoofRule().isEnabled() && brand != null && "vanilla".equalsIgnoreCase(brand.trim())) {
|
||||
List<String> extra = new ArrayList<>();
|
||||
for (String ch : channels) {
|
||||
if (!cfg.getVanillaAllowedChannels().contains(ch.toLowerCase(Locale.ROOT))) {
|
||||
extra.add(ch);
|
||||
}
|
||||
}
|
||||
if (!extra.isEmpty()) {
|
||||
plugin.flagPlayer(player, ViolationType.VANILLA_WITH_CHANNELS, "Vanilla brand with extra channels: " + String.join(", ", extra));
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Blocked channels check
|
||||
if (cfg.getBlockedChannelRule().isEnabled()) {
|
||||
for (String ch : channels) {
|
||||
if (cfg.getBlockedChannels().contains(ch.toLowerCase(Locale.ROOT))) {
|
||||
plugin.flagPlayer(player, ViolationType.BLOCKED_CHANNEL, "Blocked plugin channel registered: " + ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Channel whitelist check
|
||||
if (cfg.getChannelWhitelistRule().isEnabled() && !cfg.getWhitelistedChannels().isEmpty()) {
|
||||
for (String ch : channels) {
|
||||
if (!cfg.getWhitelistedChannels().contains(ch.toLowerCase(Locale.ROOT))) {
|
||||
plugin.flagPlayer(player, ViolationType.CHANNEL_WHITELIST, "Non-whitelisted plugin channel: " + ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Brand rule matching (required channels, blocked channels, allowed/unknown brand)
|
||||
if (brand != null && !brand.isBlank()) {
|
||||
String lowerBrand = brand.toLowerCase(Locale.ROOT);
|
||||
BrandRuleConfig matched = null;
|
||||
for (BrandRuleConfig rule : cfg.getBrandRules().values()) {
|
||||
if (!rule.isEnabled()) continue;
|
||||
for (String m : rule.getBrandMatchers()) {
|
||||
if (lowerBrand.contains(m.toLowerCase(Locale.ROOT))) {
|
||||
matched = rule;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched != null) break;
|
||||
}
|
||||
if (matched == null) {
|
||||
if (cfg.getUnknownBrandRule().isEnabled()) {
|
||||
plugin.flagPlayer(player, ViolationType.UNKNOWN_BRAND, "Unknown client brand: " + brand);
|
||||
}
|
||||
} else {
|
||||
if (!matched.isAllowed()) {
|
||||
plugin.flagPlayer(player, ViolationType.CLIENT_BRAND, "Disallowed client brand: " + brand);
|
||||
}
|
||||
for (String req : matched.getRequiredChannels()) {
|
||||
if (!channels.contains(req.toLowerCase(Locale.ROOT))) {
|
||||
plugin.flagPlayer(player, ViolationType.MISSING_REQUIRED_CHANNELS,
|
||||
"Brand '" + matched.getId() + "' missing required channel: " + req);
|
||||
}
|
||||
}
|
||||
for (String blk : matched.getBlockedChannels()) {
|
||||
if (channels.contains(blk.toLowerCase(Locale.ROOT))) {
|
||||
plugin.flagPlayer(player, ViolationType.BLOCKED_CHANNEL,
|
||||
"Brand '" + matched.getId() + "' registered forbidden channel: " + blk);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
UUID uuid = event.getPlayer().getUniqueId();
|
||||
configPacketTrace.remove(uuid);
|
||||
if (plugin.getProxyDetectionManager() != null) {
|
||||
plugin.getProxyDetectionManager().clearPlayer(uuid);
|
||||
}
|
||||
}
|
||||
|
||||
private String detectProtocolVersionLabel(Player player) {
|
||||
try {
|
||||
var user = com.github.retrooper.packetevents.PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (user != null && user.getClientVersion() != null) {
|
||||
return user.getClientVersion().getReleaseName();
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
return String.valueOf(player.getProtocolVersion());
|
||||
}
|
||||
|
||||
private static String decodeVarIntString(byte[] data) {
|
||||
if (data == null || data.length == 0) {
|
||||
return "";
|
||||
}
|
||||
int idx = 0;
|
||||
int len = 0;
|
||||
int shift = 0;
|
||||
while (idx < data.length && idx < 5) {
|
||||
byte b = data[idx++];
|
||||
len |= (b & 0x7F) << shift;
|
||||
if ((b & 0x80) == 0) break;
|
||||
shift += 7;
|
||||
}
|
||||
if (len > 0 && idx + len <= data.length) {
|
||||
return new String(data, idx, len, StandardCharsets.UTF_8).trim();
|
||||
}
|
||||
return new String(data, StandardCharsets.UTF_8).trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.gigazelensky.antispoof.probe;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.data.LogType;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* Asynchronous TCP port reachability probe for proxy/VPN exit detection (reconstructed from lllllIIIlIllIII).
|
||||
*/
|
||||
public final class ActiveReconScanner {
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final ExecutorService executor = Executors.newFixedThreadPool(4, r -> {
|
||||
Thread t = new Thread(r, "AntiSpoof-ActiveRecon");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
|
||||
public ActiveReconScanner(AntiSpoofPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void scanOnTrigger(Player player, String trigger) {
|
||||
if (player == null || !plugin.getConfigManager().isActiveReconEnabled()) {
|
||||
return;
|
||||
}
|
||||
List<Integer> ports = plugin.getConfigManager().getActiveReconPorts();
|
||||
if (ports.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
InetSocketAddress remote = player.getAddress();
|
||||
if (remote == null || remote.getAddress() == null) {
|
||||
if (plugin.getConfigManager().isDebug()) {
|
||||
plugin.getLogger().info("[ActiveRecon] Skipping scan for " + player.getName() + " (raw address unavailable).");
|
||||
}
|
||||
return;
|
||||
}
|
||||
InetAddress addr = remote.getAddress();
|
||||
if (addr.isLoopbackAddress() || addr.isSiteLocalAddress() || addr.isAnyLocalAddress()) {
|
||||
return;
|
||||
}
|
||||
int timeoutMs = plugin.getConfigManager().getActiveReconTimeoutMs();
|
||||
try {
|
||||
executor.submit(() -> {
|
||||
List<Integer> openPorts = new ArrayList<>();
|
||||
for (int port : ports) {
|
||||
if (port <= 0 || port > 65535) continue;
|
||||
try (Socket s = new Socket()) {
|
||||
s.connect(new InetSocketAddress(addr, port), timeoutMs);
|
||||
openPorts.add(port);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
if (!openPorts.isEmpty()) {
|
||||
plugin.getPlayerLogManager().log(
|
||||
player,
|
||||
LogType.PROBE,
|
||||
"[ActiveRecon:" + trigger + "] Open ports on " + addr.getHostAddress() + ": " + openPorts
|
||||
);
|
||||
}
|
||||
});
|
||||
} catch (RejectedExecutionException e) {
|
||||
plugin.getLogger().warning("[ActiveRecon] Executor rejected scan for " + player.getName() + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
executor.shutdownNow();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package com.gigazelensky.antispoof.probe;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.ViolationType;
|
||||
import com.gigazelensky.antispoof.data.LogType;
|
||||
import com.gigazelensky.antispoof.util.SchedulerUtil;
|
||||
import com.gigazelensky.antispoof.util.TextUtil;
|
||||
import io.papermc.paper.threadedregions.scheduler.ScheduledTask;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerResourcePackStatusEvent;
|
||||
|
||||
/**
|
||||
* Multi-Pack Differential Asset Probe Lab (ports original IIllIlIIIIIIlII TEXTURES/FONT/CORRUPTION
|
||||
* + zero-width bitmap overflow + mod shader/asset corruption vs missing-asset control baseline).
|
||||
*/
|
||||
public final class AssetProbeLabManager implements Listener {
|
||||
private static final int PACK_FORMAT_1_20_6 = 32;
|
||||
|
||||
private record ProbeSpec(String name, Map<String, byte[]> files) {
|
||||
}
|
||||
|
||||
private record ProbeResult(String name, String status, long totalMs, long reloadMs, boolean fetched) {
|
||||
}
|
||||
|
||||
private static final class LabRun {
|
||||
final UUID playerId;
|
||||
final CommandSender requester;
|
||||
final List<ProbeSpec> specs;
|
||||
final List<ProbeResult> results = new ArrayList<>();
|
||||
int index;
|
||||
UUID currentPackId;
|
||||
String currentToken;
|
||||
long sentAtMs;
|
||||
long downloadedAtMs;
|
||||
ScheduledTask timeoutTask;
|
||||
|
||||
LabRun(UUID playerId, CommandSender requester, List<ProbeSpec> specs) {
|
||||
this.playerId = playerId;
|
||||
this.requester = requester;
|
||||
this.specs = specs;
|
||||
}
|
||||
}
|
||||
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final ProbeHttpServer httpServer;
|
||||
private final Map<UUID, LabRun> activeRuns = new ConcurrentHashMap<>();
|
||||
|
||||
public AssetProbeLabManager(AntiSpoofPlugin plugin, ProbeHttpServer httpServer) {
|
||||
this.plugin = plugin;
|
||||
this.httpServer = httpServer;
|
||||
}
|
||||
|
||||
public boolean isAvailable() {
|
||||
return httpServer != null;
|
||||
}
|
||||
|
||||
public void startLab(Player player, CommandSender requester) {
|
||||
if (player == null || !player.isOnline() || plugin.isBedrock(player)) {
|
||||
return;
|
||||
}
|
||||
if (httpServer == null) {
|
||||
notifyTarget(requester, player, "&c[AssetLab] HTTP probe server is not running.");
|
||||
return;
|
||||
}
|
||||
|
||||
UUID uuid = player.getUniqueId();
|
||||
cancelRun(uuid, player);
|
||||
|
||||
List<ProbeSpec> specs = buildSpecs();
|
||||
LabRun run = new LabRun(uuid, requester, specs);
|
||||
activeRuns.put(uuid, run);
|
||||
|
||||
plugin.getLogger().info("[AssetLab] Starting " + specs.size() + "-pack differential Asset Probe on " + player.getName());
|
||||
notifyTarget(requester, player, "&b[AssetLab] &fRunning &e" + specs.size() + " &fAsset Probes (Control vs Meteor/OpSec/Fabric)...");
|
||||
dispatchNext(player, run);
|
||||
}
|
||||
|
||||
private List<ProbeSpec> buildSpecs() {
|
||||
List<ProbeSpec> list = new ArrayList<>();
|
||||
|
||||
// 0. CONTROL: Guaranteed non-existent bitmap (baseline on every client)
|
||||
list.add(new ProbeSpec("0_CONTROL_MISSING_BITMAP", mapOf(
|
||||
"assets/minecraft/font/default.json",
|
||||
"{\"providers\":[{\"type\":\"bitmap\",\"file\":\"antispoof_missing_999:nope.png\",\"ascent\":8,\"height\":8,\"chars\":[\"\\ue020\"]}]}"
|
||||
)));
|
||||
|
||||
// 1. Original AntiSpoof TEXTURES probe: bitmap referencing meteor-client:meteor.png (resolves to assets/meteor-client/textures/meteor.png)
|
||||
list.add(new ProbeSpec("1_BITMAP_METEOR_LOGO", mapOf(
|
||||
"assets/minecraft/font/default.json",
|
||||
"{\"providers\":[{\"type\":\"bitmap\",\"file\":\"meteor-client:meteor.png\",\"ascent\":8,\"height\":8,\"chars\":[\"\\ue020\"]}]}"
|
||||
)));
|
||||
|
||||
// 2. Zero-width bitmap overflow trap: 300 chars in 1 row -> if meteor-client:meteor.png exists (width < 300), cellWidth = width/300 = 0!
|
||||
StringBuilder chars300 = new StringBuilder();
|
||||
for (int i = 0; i < 300; i++) {
|
||||
chars300.append(String.format("\\u%04x", 0xE100 + i));
|
||||
}
|
||||
list.add(new ProbeSpec("2_BITMAP_METEOR_DIVZERO", mapOf(
|
||||
"assets/minecraft/font/default.json",
|
||||
"{\"providers\":[{\"type\":\"bitmap\",\"file\":\"meteor-client:meteor.png\",\"ascent\":8,\"height\":8,\"chars\":[\"" + chars300 + "\"]}]}"
|
||||
)));
|
||||
|
||||
// 3. Zero-width bitmap overflow on vanilla/fabric/opsec icons (icon.png & textures/icons)
|
||||
list.add(new ProbeSpec("3_BITMAP_METEOR_ICONS_DIVZERO", mapOf(
|
||||
"assets/minecraft/font/default.json",
|
||||
"{\"providers\":["
|
||||
+ "{\"type\":\"bitmap\",\"file\":\"meteor-client:icons/meteor.png\",\"ascent\":8,\"height\":8,\"chars\":[\"" + chars300 + "\"]},"
|
||||
+ "{\"type\":\"bitmap\",\"file\":\"meteor-client:textures/meteor.png\",\"ascent\":8,\"height\":8,\"chars\":[\"" + chars300 + "\"]}"
|
||||
+ "]}"
|
||||
)));
|
||||
|
||||
// 4. Original AntiSpoof FONT probe: TTF provider pointing at Meteor's PNG/TTF
|
||||
list.add(new ProbeSpec("4_TTF_METEOR_PROBE", mapOf(
|
||||
"assets/minecraft/font/default.json",
|
||||
"{\"providers\":[{\"type\":\"ttf\",\"file\":\"meteor-client:JetBrainsMono-Regular.ttf\",\"size\":11.0,\"oversample\":1.0,\"shift\":[0.0,0.0]}]}"
|
||||
)));
|
||||
|
||||
// 5. Original AntiSpoof CORRUPTION probe: corrupt Meteor shader + texture + font paths (Vanilla never reads these!)
|
||||
Map<String, byte[]> corruptFiles = new LinkedHashMap<>();
|
||||
byte[] garbage = "CORRUPT_NOT_VALID_GLSL_OR_PNG_{{{[[[".getBytes(StandardCharsets.UTF_8);
|
||||
corruptFiles.put("assets/meteor-client/shaders/pos_color.vert", garbage);
|
||||
corruptFiles.put("assets/meteor-client/shaders/pos_color.frag", garbage);
|
||||
corruptFiles.put("assets/meteor-client/shaders/text.frag", garbage);
|
||||
corruptFiles.put("assets/meteor-client/textures/meteor.png", garbage);
|
||||
corruptFiles.put("assets/meteor-client/fonts/JetBrainsMono-Regular.ttf", garbage);
|
||||
list.add(new ProbeSpec("5_CORRUPT_METEOR_ASSETS", corruptFiles));
|
||||
|
||||
// 6. Corrupt Sodium/Iris/Fabric shaders (Vanilla never reads these namespaces)
|
||||
Map<String, byte[]> corruptSodium = new LinkedHashMap<>();
|
||||
corruptSodium.put("assets/sodium/shaders/blocks/block_layer_opaque.vsh", garbage);
|
||||
corruptSodium.put("assets/sodium/shaders/blocks/block_layer_opaque.fsh", garbage);
|
||||
corruptSodium.put("assets/sodium/shaders/include/fog.glsl", garbage);
|
||||
list.add(new ProbeSpec("6_CORRUPT_SODIUM_SHADERS", corruptSodium));
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
private static Map<String, byte[]> mapOf(String path, String utf8) {
|
||||
Map<String, byte[]> m = new LinkedHashMap<>();
|
||||
m.put(path, utf8.getBytes(StandardCharsets.UTF_8));
|
||||
return m;
|
||||
}
|
||||
|
||||
private void dispatchNext(Player player, LabRun run) {
|
||||
if (!player.isOnline() || activeRuns.get(run.playerId) != run) {
|
||||
return;
|
||||
}
|
||||
if (run.index >= run.specs.size()) {
|
||||
finishRun(player, run);
|
||||
return;
|
||||
}
|
||||
|
||||
ProbeSpec spec = run.specs.get(run.index);
|
||||
UUID packId = UUID.randomUUID();
|
||||
String nonce = TranslationProbeManager.generateNonce();
|
||||
String token = "aslab-" + run.index + "-" + nonce + ".zip";
|
||||
|
||||
byte[] zip = ProbeHttpServer.buildMultiFilePack(PACK_FORMAT_1_20_6, "AssetLab " + spec.name(), spec.files());
|
||||
byte[] sha1 = ProbeHttpServer.sha1(zip);
|
||||
String url = httpServer.registerPack(run.playerId, token, zip, false);
|
||||
|
||||
run.currentPackId = packId;
|
||||
run.currentToken = token;
|
||||
run.sentAtMs = System.currentTimeMillis();
|
||||
run.downloadedAtMs = 0L;
|
||||
|
||||
plugin.getLogger().info("[AssetLab] [" + (run.index + 1) + "/" + run.specs.size() + "] Pushing " + spec.name()
|
||||
+ " to " + player.getName() + " bytes=" + zip.length);
|
||||
|
||||
SchedulerUtil.runEntity(plugin, player, () -> {
|
||||
if (!player.isOnline()) return;
|
||||
try {
|
||||
player.addResourcePack(packId, url, sha1, null, true);
|
||||
} catch (Throwable t) {
|
||||
plugin.getLogger().warning("[AssetLab] addResourcePack error on " + spec.name() + ": " + t.getMessage());
|
||||
recordAndAdvance(player, run, "SEND_ERROR", false);
|
||||
}
|
||||
});
|
||||
|
||||
SchedulerUtil.cancelQuietly(run.timeoutTask);
|
||||
int capturedIdx = run.index;
|
||||
run.timeoutTask = SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (activeRuns.get(run.playerId) == run && run.index == capturedIdx) {
|
||||
boolean fetched = httpServer.wasFetched(token);
|
||||
recordAndAdvance(player, run, "TIMEOUT", fetched);
|
||||
}
|
||||
}, 160L); // 8s per pack
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPackStatus(PlayerResourcePackStatusEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
if (player == null) return;
|
||||
LabRun run = activeRuns.get(player.getUniqueId());
|
||||
if (run == null || run.currentPackId == null || !run.currentPackId.equals(event.getID())) {
|
||||
return;
|
||||
}
|
||||
|
||||
PlayerResourcePackStatusEvent.Status st = event.getStatus();
|
||||
long now = System.currentTimeMillis();
|
||||
boolean fetched = httpServer.wasFetched(run.currentToken);
|
||||
|
||||
if (st == PlayerResourcePackStatusEvent.Status.ACCEPTED) {
|
||||
return;
|
||||
}
|
||||
if (st == PlayerResourcePackStatusEvent.Status.DOWNLOADED) {
|
||||
run.downloadedAtMs = now;
|
||||
return;
|
||||
}
|
||||
|
||||
// Terminal status: SUCCESSFULLY_LOADED, FAILED_RELOAD, FAILED_DOWNLOAD, DECLINED, INVALID_URL, DISCARDED
|
||||
SchedulerUtil.cancelQuietly(run.timeoutTask);
|
||||
recordAndAdvance(player, run, st.name(), fetched);
|
||||
}
|
||||
|
||||
private void recordAndAdvance(Player player, LabRun run, String status, boolean fetched) {
|
||||
ProbeSpec spec = run.specs.get(run.index);
|
||||
long now = System.currentTimeMillis();
|
||||
long totalMs = now - run.sentAtMs;
|
||||
long reloadMs = run.downloadedAtMs > 0 ? (now - run.downloadedAtMs) : -1L;
|
||||
|
||||
run.results.add(new ProbeResult(spec.name(), status, totalMs, reloadMs, fetched));
|
||||
plugin.getLogger().info("[AssetLab:RESULT] " + player.getName()
|
||||
+ " test=" + spec.name() + " status=" + status
|
||||
+ " totalMs=" + totalMs + " reloadMs=" + reloadMs + " fetched=" + fetched);
|
||||
|
||||
UUID packToRemove = run.currentPackId;
|
||||
run.currentPackId = null;
|
||||
run.index++;
|
||||
|
||||
SchedulerUtil.runEntity(plugin, player, () -> {
|
||||
if (player.isOnline() && packToRemove != null) {
|
||||
try {
|
||||
player.removeResourcePack(packToRemove);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Wait 30 ticks (1.5s) between packs so removals don't overlap
|
||||
SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (player.isOnline() && activeRuns.get(run.playerId) == run) {
|
||||
dispatchNext(player, run);
|
||||
}
|
||||
}, 30L);
|
||||
}
|
||||
|
||||
private void finishRun(Player player, LabRun run) {
|
||||
activeRuns.remove(run.playerId, run);
|
||||
SchedulerUtil.cancelQuietly(run.timeoutTask);
|
||||
httpServer.cleanupPlayer(run.playerId);
|
||||
|
||||
String controlStatus = run.results.isEmpty() ? "UNKNOWN" : run.results.get(0).status();
|
||||
List<String> diffs = new ArrayList<>();
|
||||
StringBuilder table = new StringBuilder("[AssetLab:SUMMARY] " + player.getName() + " control=" + controlStatus);
|
||||
|
||||
// Only compare bitmap-font probes against the bitmap control (`0_CONTROL_MISSING_BITMAP`)
|
||||
// to avoid false positives from non-bitmap packs that don't override font/default.json.
|
||||
for (int i = 0; i < run.results.size(); i++) {
|
||||
ProbeResult r = run.results.get(i);
|
||||
table.append("\n - ").append(r.name())
|
||||
.append(" => status=").append(r.status())
|
||||
.append(" reloadMs=").append(r.reloadMs())
|
||||
.append(" fetched=").append(r.fetched());
|
||||
boolean isBitmapProbe = r.name().contains("_BITMAP_");
|
||||
if (i > 0 && isBitmapProbe && "FAILED_RELOAD".equals(controlStatus) && "SUCCESSFULLY_LOADED".equals(r.status())) {
|
||||
diffs.add(r.name() + ":SUCCESSFULLY_LOADED(vs control FAILED_RELOAD)");
|
||||
}
|
||||
}
|
||||
plugin.getLogger().info(table.toString());
|
||||
|
||||
if (diffs.isEmpty()) {
|
||||
notifyTarget(run.requester, player, "&e[AssetLab] &fAll " + run.results.size()
|
||||
+ " packs returned same status (&f" + controlStatus + "&e) — check console for reloadMs diffs.");
|
||||
} else {
|
||||
String msg = String.join("; ", diffs);
|
||||
plugin.getLogger().warning("[AssetLab:DETECTED] " + player.getName() + " differential hit: " + msg);
|
||||
plugin.getPlayerLogManager().log(player, LogType.FLAG, "[AssetLab] Differential hit: " + msg);
|
||||
plugin.flagPlayer(player, ViolationType.ASSET_DETECTED, "Asset differential hit: " + msg);
|
||||
notifyTarget(run.requester, player, "&c&l[AssetLab] DETECTED &e" + player.getName() + "&c: &f" + msg);
|
||||
}
|
||||
|
||||
// Auto-chain into CommandBookProbe (exact AntiSpoof 1.5.0 OpSec book probe) on automatic join runs
|
||||
if (run.requester == null && player.isOnline() && plugin.getConfigManager().isCommandBookEnabled()
|
||||
&& plugin.getCommandBookProbeManager() != null) {
|
||||
SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (player.isOnline()) {
|
||||
plugin.getCommandBookProbeManager().runBookProbe(player, null);
|
||||
}
|
||||
}, 30L);
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyTarget(CommandSender requester, Player target, String legacyMsg) {
|
||||
Component comp = TextUtil.toComponent(legacyMsg);
|
||||
if (requester != null) {
|
||||
requester.sendMessage(comp);
|
||||
} else if (target != null && target.isOnline() && (target.isOp() || target.hasPermission("antispoof.alerts"))) {
|
||||
target.sendMessage(comp);
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelRun(UUID uuid, Player player) {
|
||||
LabRun prev = activeRuns.remove(uuid);
|
||||
if (prev == null) return;
|
||||
SchedulerUtil.cancelQuietly(prev.timeoutTask);
|
||||
if (prev.currentPackId != null && player != null && player.isOnline()) {
|
||||
try {
|
||||
player.removeResourcePack(prev.currentPackId);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
cancelRun(event.getPlayer().getUniqueId(), event.getPlayer());
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
for (LabRun r : activeRuns.values()) {
|
||||
SchedulerUtil.cancelQuietly(r.timeoutTask);
|
||||
}
|
||||
activeRuns.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.gigazelensky.antispoof.probe;
|
||||
|
||||
import com.gigazelensky.antispoof.config.AssetProbeRule;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.ViolationType;
|
||||
import com.gigazelensky.antispoof.data.LogType;
|
||||
import com.gigazelensky.antispoof.util.SchedulerUtil;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerResourcePackStatusEvent;
|
||||
|
||||
/**
|
||||
* Resource-pack asset detection probe (TEXTURES, FONT, CORRUPTION) (reconstructed from IIIIIIllllllIII).
|
||||
*/
|
||||
public final class AssetProbeListener implements Listener {
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final ProbeHttpServer httpServer;
|
||||
private final Map<UUID, AssetProbeRule> activeProbeByPlayer = new ConcurrentHashMap<>();
|
||||
|
||||
public AssetProbeListener(AntiSpoofPlugin plugin, ProbeHttpServer httpServer) {
|
||||
this.plugin = plugin;
|
||||
this.httpServer = httpServer;
|
||||
}
|
||||
|
||||
public void startProbes(Player player) {
|
||||
if (player == null || !player.isOnline() || httpServer == null) {
|
||||
return;
|
||||
}
|
||||
if (!plugin.getConfigManager().isAssetProbeEnabled() || plugin.isBedrock(player)) {
|
||||
return;
|
||||
}
|
||||
List<AssetProbeRule> rules = plugin.getConfigManager().getAssetProbeRules();
|
||||
for (AssetProbeRule rule : rules) {
|
||||
if (!rule.isEnabled()) {
|
||||
continue;
|
||||
}
|
||||
activeProbeByPlayer.put(player.getUniqueId(), rule);
|
||||
String token = "asset-" + rule.getId() + "-" + player.getUniqueId() + ".zip";
|
||||
byte[] zip = ProbeHttpServer.buildMinimalPack(
|
||||
"asset-" + rule.getId(),
|
||||
rule.getTargetPath(),
|
||||
"probe".getBytes(StandardCharsets.UTF_8)
|
||||
);
|
||||
byte[] hash = ProbeHttpServer.sha1(zip);
|
||||
UUID packId = UUID.nameUUIDFromBytes(token.getBytes(StandardCharsets.UTF_8));
|
||||
String url = httpServer.registerPack(player.getUniqueId(), token, zip, false);
|
||||
SchedulerUtil.runEntity(plugin, player, () -> {
|
||||
if (player.isOnline()) {
|
||||
try {
|
||||
player.addResourcePack(packId, url, hash, null, false);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPackStatus(PlayerResourcePackStatusEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
AssetProbeRule rule = activeProbeByPlayer.get(player.getUniqueId());
|
||||
if (rule == null) {
|
||||
return;
|
||||
}
|
||||
PlayerResourcePackStatusEvent.Status status = event.getStatus();
|
||||
if (status == PlayerResourcePackStatusEvent.Status.ACCEPTED || status == PlayerResourcePackStatusEvent.Status.DOWNLOADED) {
|
||||
return;
|
||||
}
|
||||
activeProbeByPlayer.remove(player.getUniqueId());
|
||||
if (status == PlayerResourcePackStatusEvent.Status.DECLINED) {
|
||||
plugin.flagPlayer(player, ViolationType.ASSET_DECLINED, "Declined asset probe pack (" + rule.getDisplayName() + ")");
|
||||
} else if (status == PlayerResourcePackStatusEvent.Status.FAILED_DOWNLOAD || status == PlayerResourcePackStatusEvent.Status.FAILED_RELOAD) {
|
||||
plugin.getPlayerLogManager().log(player, LogType.PROBE, "Asset probe triggered (" + rule.getCheckType() + "): " + rule.getDisplayName());
|
||||
plugin.flagPlayer(player, ViolationType.ASSET_DETECTED, "Detected mod asset: " + rule.getDisplayName());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
activeProbeByPlayer.remove(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.gigazelensky.antispoof.probe;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.protocol.chat.Node;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDeclareCommands;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.ViolationType;
|
||||
import com.gigazelensky.antispoof.data.LogType;
|
||||
import com.gigazelensky.antispoof.util.SchedulerUtil;
|
||||
import com.gigazelensky.antispoof.util.TextUtil;
|
||||
import io.papermc.paper.threadedregions.scheduler.ScheduledTask;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import net.kyori.adventure.inventory.Book;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.event.ClickEvent;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
/**
|
||||
* Exact AntiSpoof 1.5.0 Command-Book Probe (ported from IIlIIIlIlIIlIII.w + IIlIIIlIlIIlIII.r):
|
||||
* Sends DeclareCommands with a random literal command `/asverify_<nonce>` and opens a
|
||||
* Written Book containing ClickEvent(RUN_COMMAND, "/asverify_<nonce>") to test for OpSec /
|
||||
* ExploitFixer-style client-side command-book blockers.
|
||||
*/
|
||||
public final class CommandBookProbeManager implements Listener {
|
||||
private record ActiveBook(String commandToken, CommandSender requester, ScheduledTask timeoutTask) {
|
||||
}
|
||||
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final NamespacedKey probeTagKey;
|
||||
private final Map<UUID, ActiveBook> activeBooks = new ConcurrentHashMap<>();
|
||||
private volatile ScheduledTask cleanupTask;
|
||||
|
||||
public CommandBookProbeManager(AntiSpoofPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
this.probeTagKey = new NamespacedKey(plugin, "probe_book");
|
||||
}
|
||||
|
||||
public void start() {
|
||||
cleanupTask = SchedulerUtil.runGlobalTimer(plugin, () -> {
|
||||
activeBooks.keySet().removeIf(uuid -> plugin.getServer().getPlayer(uuid) == null);
|
||||
}, 200L, 200L);
|
||||
}
|
||||
|
||||
public void runBookProbe(Player player, CommandSender requester) {
|
||||
if (player == null || !player.isOnline()) {
|
||||
return;
|
||||
}
|
||||
if (plugin.isBedrock(player)) {
|
||||
if (requester != null) {
|
||||
requester.sendMessage(TextUtil.toComponent("&eSkipped Bedrock player: &f" + player.getName()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
UUID id = player.getUniqueId();
|
||||
ActiveBook prev = activeBooks.remove(id);
|
||||
if (prev != null) {
|
||||
SchedulerUtil.cancelQuietly(prev.timeoutTask());
|
||||
}
|
||||
|
||||
String token = "asverify_" + TranslationProbeManager.generateNonce();
|
||||
SchedulerUtil.runEntity(plugin, player, () -> {
|
||||
if (!player.isOnline()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// Exact IIlIIIlIlIIlIII.r: declare synthetic command node to client
|
||||
Node root = new Node((byte) 0, List.of(1), 0, null, (Integer) null, null, null);
|
||||
Node cmdNode = new Node((byte) 5, Collections.emptyList(), 0, token, (Integer) null, null, null);
|
||||
PacketEvents.getAPI().getPlayerManager().sendPacket(
|
||||
player,
|
||||
new WrapperPlayServerDeclareCommands(List.of(root, cmdNode), 0)
|
||||
);
|
||||
|
||||
// Exact IIlIIIlIlIIlIII.w: open verification book with RUN_COMMAND click event
|
||||
Component page = TextUtil.toComponent(
|
||||
"&0&lServer Verification\n\n&8Click the line below to continue.\n\n"
|
||||
+ "&1&l&nVerify my session\n\n&8When Minecraft asks, press &0Run Command&8."
|
||||
).clickEvent(ClickEvent.runCommand("/" + token));
|
||||
|
||||
Book probeBook = Book.book(
|
||||
Component.text("Server Verification"),
|
||||
Component.text("Server"),
|
||||
page
|
||||
);
|
||||
player.openBook(probeBook);
|
||||
|
||||
ScheduledTask timeout = SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
ActiveBook expired = activeBooks.remove(id);
|
||||
if (expired != null && player.isOnline()) {
|
||||
player.updateCommands();
|
||||
String msg = "[CommandBookProbe] " + player.getName() + " timed out (no click / blocked by OpSec?)";
|
||||
plugin.getLogger().warning(msg);
|
||||
plugin.flagPlayer(player, ViolationType.COMMAND_BOOK_BLOCKED, "Command-book verification not completed");
|
||||
if (requester != null) {
|
||||
requester.sendMessage(TextUtil.toComponent("&c[CommandBookProbe] &e" + player.getName() + " &ctimed out / blocked!"));
|
||||
}
|
||||
}
|
||||
}, 240L); // 12 seconds
|
||||
|
||||
activeBooks.put(id, new ActiveBook(token, requester, timeout));
|
||||
plugin.getLogger().info("[CommandBookProbe] Sent book probe /" + token + " to " + player.getName());
|
||||
plugin.getPlayerLogManager().log(player, LogType.PROBE, "Sent command-book verification probe (/" + token + ").");
|
||||
} catch (Throwable t) {
|
||||
plugin.flagPlayer(player, ViolationType.COMMAND_BOOK_BLOCKED, "Command-book probe rejected: " + t.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onCommand(PlayerCommandPreprocessEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
ActiveBook active = activeBooks.get(player.getUniqueId());
|
||||
if (active == null) return;
|
||||
|
||||
String raw = event.getMessage() == null ? "" : event.getMessage().trim();
|
||||
if (raw.equalsIgnoreCase("/" + active.commandToken())) {
|
||||
event.setCancelled(true);
|
||||
activeBooks.remove(player.getUniqueId());
|
||||
SchedulerUtil.cancelQuietly(active.timeoutTask());
|
||||
player.updateCommands();
|
||||
plugin.getLogger().info("[CommandBookProbe] " + player.getName() + " PASSED (clicked /" + active.commandToken() + ")");
|
||||
if (active.requester() != null) {
|
||||
active.requester().sendMessage(TextUtil.toComponent("&a[CommandBookProbe] &f" + player.getName() + " &aPASSED!"));
|
||||
} else {
|
||||
player.sendMessage(TextUtil.toComponent("&a[CommandBookProbe] &fVerification PASSED!"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
ActiveBook prev = activeBooks.remove(event.getPlayer().getUniqueId());
|
||||
if (prev != null) {
|
||||
SchedulerUtil.cancelQuietly(prev.timeoutTask());
|
||||
}
|
||||
}
|
||||
|
||||
public NamespacedKey getProbeTagKey() {
|
||||
return probeTagKey;
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
SchedulerUtil.cancelQuietly(cleanupTask);
|
||||
for (ActiveBook b : activeBooks.values()) {
|
||||
SchedulerUtil.cancelQuietly(b.timeoutTask());
|
||||
}
|
||||
activeBooks.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package com.gigazelensky.antispoof.probe;
|
||||
|
||||
import com.gigazelensky.antispoof.api.events.IdentityAnomalyType;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.IdentityAnomalyInternalEvent;
|
||||
import com.gigazelensky.antispoof.core.ViolationType;
|
||||
import com.gigazelensky.antispoof.data.IdentityProbeStage;
|
||||
import com.gigazelensky.antispoof.data.IdentityRecord;
|
||||
import com.gigazelensky.antispoof.data.LogType;
|
||||
import com.gigazelensky.antispoof.data.ProbeStepResult;
|
||||
import com.gigazelensky.antispoof.util.SchedulerUtil;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerResourcePackStatusEvent;
|
||||
|
||||
/**
|
||||
* Resource-pack cache-based cross-account identity linker & anti-spoof anomaly detector
|
||||
* (reconstructed from lIIllIlIIllIlll).
|
||||
*/
|
||||
public final class IdentityLinkerManager implements Listener {
|
||||
public static final Pattern MD5_HEX = Pattern.compile("^[0-9a-fA-F]{32}$");
|
||||
public static final Pattern SHA1_HEX = Pattern.compile("^[0-9a-fA-F]{40}$");
|
||||
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final ProbeHttpServer httpServer;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final Map<UUID, IdentitySession> sessions = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, String> liveFingerprints = new ConcurrentHashMap<>();
|
||||
|
||||
public static final class IdentitySession {
|
||||
public volatile IdentityProbeStage stage = IdentityProbeStage.WAITING_FOR_HIDER;
|
||||
public final ProbeStepResult[] bitResults;
|
||||
public final String[] probeTokens;
|
||||
public final UUID[] packIds;
|
||||
public volatile int currentBit;
|
||||
public volatile UUID hiderPackId;
|
||||
public volatile String hiderToken;
|
||||
public final long startedAt = System.currentTimeMillis();
|
||||
|
||||
public IdentitySession(int bitCount) {
|
||||
this.bitResults = new ProbeStepResult[bitCount];
|
||||
Arrays.fill(this.bitResults, ProbeStepResult.WAITING);
|
||||
this.probeTokens = new String[bitCount];
|
||||
this.packIds = new UUID[bitCount];
|
||||
}
|
||||
}
|
||||
|
||||
public IdentityLinkerManager(AntiSpoofPlugin plugin, ProbeHttpServer httpServer) {
|
||||
this.plugin = plugin;
|
||||
this.httpServer = httpServer;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return plugin.getConfigManager().isIdentityLinkerEnabled() && httpServer != null;
|
||||
}
|
||||
|
||||
public void startProbe(Player player) {
|
||||
if (player == null || !player.isOnline() || !isEnabled() || plugin.isBedrock(player)) {
|
||||
return;
|
||||
}
|
||||
int bits = plugin.getConfigManager().getIdentityProbeBitCount();
|
||||
IdentitySession session = new IdentitySession(bits);
|
||||
sessions.put(player.getUniqueId(), session);
|
||||
|
||||
if (plugin.getConfigManager().isIdentityRequireHider()) {
|
||||
session.stage = IdentityProbeStage.WAITING_FOR_HIDER;
|
||||
String token = "hider-" + player.getUniqueId() + "-" + System.nanoTime() + ".zip";
|
||||
byte[] zip = ProbeHttpServer.buildMinimalPack("hider", null, null);
|
||||
byte[] hash = ProbeHttpServer.sha1(zip);
|
||||
UUID packUuid = UUID.nameUUIDFromBytes(token.getBytes(StandardCharsets.UTF_8));
|
||||
session.hiderPackId = packUuid;
|
||||
session.hiderToken = token;
|
||||
String url = httpServer.registerPack(player.getUniqueId(), token, zip, false);
|
||||
sendPack(player, packUuid, url, hash);
|
||||
} else {
|
||||
beginCacheProbing(player, session);
|
||||
}
|
||||
}
|
||||
|
||||
private void beginCacheProbing(Player player, IdentitySession session) {
|
||||
session.stage = IdentityProbeStage.PROBING_CACHE;
|
||||
session.currentBit = 0;
|
||||
sendNextProbeBit(player, session);
|
||||
}
|
||||
|
||||
private void sendNextProbeBit(Player player, IdentitySession session) {
|
||||
if (!player.isOnline()) {
|
||||
sessions.remove(player.getUniqueId());
|
||||
return;
|
||||
}
|
||||
int bit = session.currentBit;
|
||||
if (bit >= session.bitResults.length) {
|
||||
finalizeFingerprint(player, session);
|
||||
return;
|
||||
}
|
||||
String token = "id-bit-" + bit + ".zip";
|
||||
byte[] zip = ProbeHttpServer.buildMinimalPack("id-bit-" + bit, "assets/antispoof/bit_" + bit + ".txt", ("bit-" + bit).getBytes(StandardCharsets.UTF_8));
|
||||
byte[] hash = ProbeHttpServer.sha1(zip);
|
||||
UUID packUuid = UUID.nameUUIDFromBytes(("antispoof-probe-bit-" + bit).getBytes(StandardCharsets.UTF_8));
|
||||
session.probeTokens[bit] = token;
|
||||
session.packIds[bit] = packUuid;
|
||||
// Return 305 on HTTP fetch so uncached clients fail while cached clients succeed immediately!
|
||||
String url = httpServer.registerPack(player.getUniqueId(), token, zip, true);
|
||||
sendPack(player, packUuid, url, hash);
|
||||
}
|
||||
|
||||
private void sendPack(Player player, UUID packUuid, String url, byte[] sha1) {
|
||||
SchedulerUtil.runEntity(plugin, player, () -> {
|
||||
if (!player.isOnline()) return;
|
||||
try {
|
||||
player.addResourcePack(packUuid, url, sha1, null, false);
|
||||
} catch (Throwable ignored) {
|
||||
try {
|
||||
player.setResourcePack(url, sha1);
|
||||
} catch (Throwable ignored2) {
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPackStatus(PlayerResourcePackStatusEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
IdentitySession session = sessions.get(player.getUniqueId());
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
PlayerResourcePackStatusEvent.Status status = event.getStatus();
|
||||
if (status == PlayerResourcePackStatusEvent.Status.ACCEPTED || status == PlayerResourcePackStatusEvent.Status.DOWNLOADED) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.stage == IdentityProbeStage.WAITING_FOR_HIDER) {
|
||||
if (status == PlayerResourcePackStatusEvent.Status.DECLINED) {
|
||||
Map<String, Object> ctx = new LinkedHashMap<>();
|
||||
ctx.put("stage", session.stage.name());
|
||||
ctx.put("status", status.name());
|
||||
plugin.getEventBus().publish(new IdentityAnomalyInternalEvent(
|
||||
player,
|
||||
IdentityAnomalyType.HIDER_PACK_REJECTED,
|
||||
"Player declined identity hider resource pack",
|
||||
ctx
|
||||
));
|
||||
plugin.flagPlayer(player, ViolationType.HIDER_PACK_REJECTED, "Declined identity hider resource pack");
|
||||
sessions.remove(player.getUniqueId());
|
||||
return;
|
||||
}
|
||||
if (status == PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED) {
|
||||
if (session.hiderToken != null && !httpServer.wasFetched(session.hiderToken)) {
|
||||
Map<String, Object> ctx = new LinkedHashMap<>();
|
||||
ctx.put("token", session.hiderToken);
|
||||
plugin.getEventBus().publish(new IdentityAnomalyInternalEvent(
|
||||
player,
|
||||
IdentityAnomalyType.RESOURCE_PACK_SPOOF,
|
||||
"Client reported SUCCESSFULLY_LOADED without downloading hider pack",
|
||||
ctx
|
||||
));
|
||||
plugin.flagPlayer(player, ViolationType.RESOURCE_PACK_SPOOF, "Spoofed resource pack load without HTTP fetch");
|
||||
}
|
||||
beginCacheProbing(player, session);
|
||||
} else {
|
||||
sessions.remove(player.getUniqueId());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.stage == IdentityProbeStage.PROBING_CACHE) {
|
||||
int bit = session.currentBit;
|
||||
if (bit < session.bitResults.length) {
|
||||
session.bitResults[bit] = (status == PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED)
|
||||
? ProbeStepResult.SUCCEEDED
|
||||
: ProbeStepResult.FAILED;
|
||||
session.currentBit++;
|
||||
sendNextProbeBit(player, session);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (session.stage == IdentityProbeStage.MARKING_NEW) {
|
||||
sessions.remove(player.getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
private void finalizeFingerprint(Player player, IdentitySession session) {
|
||||
int hits = 0;
|
||||
StringBuilder bits = new StringBuilder(session.bitResults.length);
|
||||
for (ProbeStepResult res : session.bitResults) {
|
||||
if (res == ProbeStepResult.SUCCEEDED) {
|
||||
bits.append('1');
|
||||
hits++;
|
||||
} else {
|
||||
bits.append('0');
|
||||
}
|
||||
}
|
||||
String fingerprint;
|
||||
if (hits == 0) {
|
||||
// New client — assign random fingerprint and mark cache
|
||||
byte[] rnd = new byte[16];
|
||||
random.nextBytes(rnd);
|
||||
fingerprint = ProbeHttpServer.sha1Hex(rnd).substring(0, 16);
|
||||
session.stage = IdentityProbeStage.MARKING_NEW;
|
||||
} else {
|
||||
fingerprint = ProbeHttpServer.sha1Hex(bits.toString().getBytes(StandardCharsets.UTF_8)).substring(0, 16);
|
||||
sessions.remove(player.getUniqueId());
|
||||
}
|
||||
|
||||
liveFingerprints.put(player.getUniqueId(), fingerprint);
|
||||
boolean banned = checkLiteBansBanned(player.getUniqueId());
|
||||
plugin.getPlayerStorageManager().recordIdentity(
|
||||
player.getUniqueId(),
|
||||
player.getName(),
|
||||
fingerprint,
|
||||
System.currentTimeMillis(),
|
||||
false,
|
||||
banned
|
||||
);
|
||||
plugin.getPlayerLogManager().log(player, LogType.PROBE, "Identity fingerprint resolved: " + fingerprint + " (cacheHits=" + hits + ")");
|
||||
|
||||
// Check linked alt accounts
|
||||
Optional<IdentityRecord> record = getIdentityRecord(player.getUniqueId());
|
||||
if (record.isPresent() && !record.get().getAltAccounts().isEmpty()) {
|
||||
plugin.getPlayerLogManager().log(player, LogType.INFO, "Linked alts: " + String.join(", ", record.get().getAltAccounts()));
|
||||
}
|
||||
}
|
||||
|
||||
private boolean checkLiteBansBanned(UUID uuid) {
|
||||
if (!plugin.getConfigManager().isUseLiteBansApi()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Class<?> dbCls = Class.forName("litebans.api.Database");
|
||||
Object db = dbCls.getMethod("get").invoke(null);
|
||||
if (db == null) return false;
|
||||
Object res = dbCls.getMethod("isPlayerBanned", UUID.class, String.class).invoke(db, uuid, null);
|
||||
return Boolean.TRUE.equals(res);
|
||||
} catch (Throwable t) {
|
||||
plugin.getLogger().info("[Identity Linker] banned-account-actions.use-litebans-api is enabled, but LiteBans API is unavailable; continuing with remaining ban checks.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
UUID id = event.getPlayer().getUniqueId();
|
||||
sessions.remove(id);
|
||||
if (httpServer != null) {
|
||||
httpServer.cleanupPlayer(id);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isRunning(UUID uuid) {
|
||||
return sessions.containsKey(uuid);
|
||||
}
|
||||
|
||||
public Optional<String> getFingerprint(UUID uuid) {
|
||||
String live = liveFingerprints.get(uuid);
|
||||
if (live != null) {
|
||||
return Optional.of(live);
|
||||
}
|
||||
return plugin.getPlayerStorageManager().getFingerprint(uuid);
|
||||
}
|
||||
|
||||
public Optional<IdentityRecord> getIdentityRecord(UUID uuid) {
|
||||
return plugin.getPlayerStorageManager().getIdentityRecord(uuid);
|
||||
}
|
||||
|
||||
public ProbeHttpServer getHttpServer() {
|
||||
return httpServer;
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
sessions.clear();
|
||||
if (httpServer != null) {
|
||||
try {
|
||||
httpServer.stop();
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,791 @@
|
||||
package com.gigazelensky.antispoof.probe;
|
||||
|
||||
import com.github.retrooper.packetevents.PacketEvents;
|
||||
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
|
||||
import com.github.retrooper.packetevents.event.PacketListenerPriority;
|
||||
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
|
||||
import com.github.retrooper.packetevents.protocol.component.ComponentTypes;
|
||||
import com.github.retrooper.packetevents.protocol.item.ItemStack;
|
||||
import com.github.retrooper.packetevents.protocol.item.type.ItemTypes;
|
||||
import com.github.retrooper.packetevents.protocol.nbt.NBTByte;
|
||||
import com.github.retrooper.packetevents.protocol.nbt.NBTCompound;
|
||||
import com.github.retrooper.packetevents.protocol.nbt.NBTInt;
|
||||
import com.github.retrooper.packetevents.protocol.nbt.NBTList;
|
||||
import com.github.retrooper.packetevents.protocol.nbt.NBTString;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.protocol.world.blockentity.BlockEntityTypes;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.WrappedBlockState;
|
||||
import com.github.retrooper.packetevents.protocol.world.states.type.StateTypes;
|
||||
import com.github.retrooper.packetevents.util.Vector3i;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientNameItem;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientUpdateSign;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerBlockChange;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerBlockEntityData;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerCloseWindow;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerOpenSignEditor;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerOpenWindow;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetSlot;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.ViolationType;
|
||||
import com.gigazelensky.antispoof.data.LogType;
|
||||
import com.gigazelensky.antispoof.util.SchedulerUtil;
|
||||
import com.gigazelensky.antispoof.util.TextUtil;
|
||||
import io.papermc.paper.threadedregions.scheduler.ScheduledTask;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerResourcePackStatusEvent;
|
||||
|
||||
/**
|
||||
* Multi-Vector Key Spoof Detection Lab Suite:
|
||||
*
|
||||
* Phase 1 (Pre-RP Edge-Case Sign Probe):
|
||||
* - D3: 1.20.6 new vanilla key (`item.minecraft.mace`) -> catches outdated static vanilla whitelists
|
||||
* - D1: Nested mod `translate` inside vanilla `chat.type.text` `with` -> catches top-level-only hooks
|
||||
* - D2: Nested mod `keybind` inside vanilla `chat.type.text` `with` -> catches missing nested keybind hooks
|
||||
* - D4: Nested vanilla `keybind` (`key.jump`) inside `chat.type.text` `with` -> verifies keybind integrity
|
||||
*
|
||||
* Phase 2 (Server RP Mod-Key Override & Mod-Namespace Collision Trap):
|
||||
* Pushes a tiny Server RP containing:
|
||||
* - C2: assets/minecraft/lang/en_us.json -> "key.meteor-client.open-gui": "OVR_MC_<nonce>"
|
||||
* - C2b: assets/minecraft/lang/en_us.json -> "category.meteor-client": "CAT_MC_<nonce>"
|
||||
* - C1: assets/meteor-client/lang/en_us.json -> "probe.meteor.ns.<nonce>": "MNS_<nonce>"
|
||||
* - C3: assets/opsec/lang/en_us.json -> "probe.opsec.ns.<nonce>": "ONS_<nonce>"
|
||||
* Real Vanilla MUST resolve ALL FOUR from the Server RP (Sign + Anvil)!
|
||||
* If OpSec blocks mod keys BEFORE Server RP override (C2/C2b) OR filters mod namespaces (C1/C3) -> CAUGHT!
|
||||
*
|
||||
* Phase 3 (Post-Remove Cache-Eviction Trap):
|
||||
* Calls player.removeResourcePack(packId), waits 25 ticks for client reload, then re-probes
|
||||
* `key.meteor-client.open-gui` & `category.meteor-client`.
|
||||
* If OpSec cached Server RP overrides without evicting on pack removal -> leaks "Open GUI" -> CAUGHT!
|
||||
*/
|
||||
public final class KeySpoofRpProbeManager extends PacketListenerAbstract implements Listener {
|
||||
private static final int PACK_FORMAT_1_20_6 = 32;
|
||||
private static final int ANVIL_MENU_TYPE_ID = 8;
|
||||
|
||||
private enum Stage {
|
||||
PHASE1_EDGE_SIGN,
|
||||
PHASE2_WAIT_RP,
|
||||
PHASE2_RP_SIGN,
|
||||
PHASE2_RP_ANVIL,
|
||||
PHASE3_POST_REMOVE_SIGN,
|
||||
DONE
|
||||
}
|
||||
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final ProbeHttpServer httpServer;
|
||||
private final Map<UUID, ProbeSession> sessions = new ConcurrentHashMap<>();
|
||||
private final AtomicInteger anvilWindowIdGen = new AtomicInteger(121);
|
||||
|
||||
private static final class ProbeSession {
|
||||
final UUID playerId;
|
||||
final UUID packId;
|
||||
final String token;
|
||||
final String nonce;
|
||||
final CommandSender requester;
|
||||
final long startMs;
|
||||
|
||||
// Phase 2 expected Server-RP values
|
||||
final String keyC2 = "key.meteor-client.open-gui";
|
||||
final String expC2;
|
||||
final String keyC2b = "category.meteor-client";
|
||||
final String expC2b;
|
||||
final String keyC1;
|
||||
final String expC1;
|
||||
final String keyC3;
|
||||
final String expC3;
|
||||
|
||||
volatile Stage stage = Stage.PHASE1_EDGE_SIGN;
|
||||
volatile long rpSentAtMs;
|
||||
volatile long rpAcceptedAtMs;
|
||||
volatile boolean packLoaded;
|
||||
|
||||
// Active sign probe state
|
||||
volatile Vector3i fakePos;
|
||||
volatile String activeSignNonce;
|
||||
volatile String activeVanillaKey;
|
||||
volatile String activeCanaryKey;
|
||||
volatile ScheduledTask signCloseTask;
|
||||
volatile ScheduledTask signTimeoutTask;
|
||||
|
||||
// Active anvil state
|
||||
volatile int anvilWindowId = -1;
|
||||
volatile String anvilNonce;
|
||||
volatile ScheduledTask anvilCloseTask;
|
||||
volatile ScheduledTask anvilTimeoutTask;
|
||||
|
||||
// Pack load timeout
|
||||
volatile ScheduledTask packTimeoutTask;
|
||||
|
||||
final List<String> detections = new ArrayList<>();
|
||||
|
||||
ProbeSession(UUID playerId, UUID packId, String token, String nonce, CommandSender requester) {
|
||||
this.playerId = playerId;
|
||||
this.packId = packId;
|
||||
this.token = token;
|
||||
this.nonce = nonce;
|
||||
this.requester = requester;
|
||||
this.startMs = System.currentTimeMillis();
|
||||
this.expC2 = "OVR_MC_" + nonce;
|
||||
this.expC2b = "CAT_MC_" + nonce;
|
||||
this.keyC1 = "probe.meteor.ns." + nonce;
|
||||
this.expC1 = "MNS_" + nonce;
|
||||
this.keyC3 = "probe.opsec.ns." + nonce;
|
||||
this.expC3 = "ONS_" + nonce;
|
||||
}
|
||||
}
|
||||
|
||||
public KeySpoofRpProbeManager(AntiSpoofPlugin plugin, ProbeHttpServer httpServer) {
|
||||
super(PacketListenerPriority.HIGH);
|
||||
this.plugin = plugin;
|
||||
this.httpServer = httpServer;
|
||||
}
|
||||
|
||||
public boolean isAvailable() {
|
||||
return httpServer != null && plugin.getConfigManager().isKeySpoofProbeEnabled();
|
||||
}
|
||||
|
||||
public void startProbe(Player player, CommandSender requester) {
|
||||
if (player == null || !player.isOnline() || plugin.isBedrock(player)) {
|
||||
return;
|
||||
}
|
||||
if (httpServer == null) {
|
||||
if (requester != null) {
|
||||
requester.sendMessage(TextUtil.toComponent("&c[KeySpoofLab] Probe HTTP server is not running!"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
UUID uuid = player.getUniqueId();
|
||||
cancelSession(uuid, player, false);
|
||||
|
||||
String nonce = TranslationProbeManager.generateNonce();
|
||||
UUID packId = UUID.randomUUID();
|
||||
String token = "kslab-" + nonce + ".zip";
|
||||
ProbeSession session = new ProbeSession(uuid, packId, token, nonce, requester);
|
||||
sessions.put(uuid, session);
|
||||
|
||||
plugin.getLogger().info("[KeySpoofLab] Starting 3-phase probe for " + player.getName() + " nonce=" + nonce);
|
||||
notifyTarget(requester, player, "&b[KeySpoofLab] &fRunning 3-phase OpSec trap suite on &e" + player.getName() + "&7...");
|
||||
|
||||
// Start Phase 1 immediately (Pre-RP Edge-Case & Nested Translate/Keybind Probe)
|
||||
dispatchPhase1EdgeSign(player, session);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// PHASE 1: Pre-RP Edge-Case & Nested Translate/Keybind Sign Probe
|
||||
// =========================================================================
|
||||
private void dispatchPhase1EdgeSign(Player player, ProbeSession s) {
|
||||
s.stage = Stage.PHASE1_EDGE_SIGN;
|
||||
String signNonce = TranslationProbeManager.generateNonce();
|
||||
String vanillaKey = TranslationProbeManager.randomVanillaBaselineKey();
|
||||
s.activeSignNonce = signNonce;
|
||||
s.activeVanillaKey = vanillaKey;
|
||||
|
||||
String[] lineJsons = new String[]{
|
||||
// Line 0 (D3): 1.20.5/1.20.6 new vanilla key `item.minecraft.mace`
|
||||
buildDoubleProbeJson("item.minecraft.mace", signNonce, vanillaKey),
|
||||
// Line 1 (D1): Nested mod `translate` inside vanilla `chat.type.text` `with`
|
||||
"{\"translate\":\"chat.type.text\",\"with\":[{\"translate\":\"key.meteor-client.open-gui\"},{\"text\":\"" + signNonce + "\"}]}",
|
||||
// Line 2 (D2): Nested mod `keybind` inside vanilla `chat.type.text` `with`
|
||||
"{\"translate\":\"chat.type.text\",\"with\":[{\"keybind\":\"key.meteor-client.open-gui\"},{\"text\":\"" + signNonce + "\"}]}",
|
||||
// Line 3 (D4): Nested vanilla `keybind` (`key.jump`) inside vanilla `chat.type.text` `with`
|
||||
"{\"translate\":\"chat.type.text\",\"with\":[{\"keybind\":\"key.jump\"},{\"text\":\"" + signNonce + "\"}]}"
|
||||
};
|
||||
|
||||
sendFakeSign(player, s, lineJsons, () -> {
|
||||
s.detections.add("P1_EDGE_SIGN_TIMEOUT");
|
||||
startPhase2ResourcePack(player, s);
|
||||
});
|
||||
}
|
||||
|
||||
private void evaluatePhase1Sign(Player player, ProbeSession s, String[] lines) {
|
||||
String l0 = safeLine(lines, 0);
|
||||
String l1 = safeLine(lines, 1);
|
||||
String l2 = safeLine(lines, 2);
|
||||
String l3 = safeLine(lines, 3);
|
||||
String n = s.activeSignNonce;
|
||||
|
||||
// D3: `item.minecraft.mace` MUST resolve (not fallback starting with ⟦)
|
||||
boolean d3Ok = !l0.isEmpty() && !l0.startsWith(TranslationProbeManager.MARKER_START) && !"item.minecraft.mace".equals(l0);
|
||||
// D1: Real Vanilla returns "<key.meteor-client.open-gui> <nonce>"
|
||||
String expectedD1 = "<key.meteor-client.open-gui> " + n;
|
||||
boolean d1Clean = expectedD1.equals(l1);
|
||||
// D2: Real Vanilla returns "<key.meteor-client.open-gui> <nonce>"
|
||||
String expectedD2 = "<key.meteor-client.open-gui> " + n;
|
||||
boolean d2Clean = expectedD2.equals(l2);
|
||||
// D4: Real Vanilla returns "<Space> <nonce>" (or bound key, NOT "<key.jump> <nonce>")
|
||||
boolean d4Ok = l3.startsWith("<") && l3.endsWith("> " + n) && !("<key.jump> " + n).equals(l3);
|
||||
|
||||
plugin.getLogger().info("[KeySpoofLab:P1] " + player.getName()
|
||||
+ " D3(1.20.6_mace) ok=" + d3Ok + " raw=\"" + l0 + "\"");
|
||||
plugin.getLogger().info("[KeySpoofLab:P1] " + player.getName()
|
||||
+ " D1(nested_mod_translate) clean=" + d1Clean + " expected=\"" + expectedD1 + "\" raw=\"" + l1 + "\"");
|
||||
plugin.getLogger().info("[KeySpoofLab:P1] " + player.getName()
|
||||
+ " D2(nested_mod_keybind) clean=" + d2Clean + " expected=\"" + expectedD2 + "\" raw=\"" + l2 + "\"");
|
||||
plugin.getLogger().info("[KeySpoofLab:P1] " + player.getName()
|
||||
+ " D4(nested_vanilla_kb) ok=" + d4Ok + " raw=\"" + l3 + "\"");
|
||||
|
||||
if (!d3Ok) s.detections.add("D3_VANILLA_1206_MACE_BLOCKED(raw=\"" + l0 + "\")");
|
||||
if (!d1Clean) s.detections.add("D1_NESTED_MOD_TRANSLATE_LEAK(raw=\"" + l1 + "\")");
|
||||
if (!d2Clean) s.detections.add("D2_NESTED_MOD_KEYBIND_LEAK(raw=\"" + l2 + "\")");
|
||||
if (!d4Ok) s.detections.add("D4_VANILLA_KEYBIND_BROKEN(raw=\"" + l3 + "\")");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// PHASE 2: Server RP Mod-Key Override (C2/C2b) & Mod-Namespace Trap (C1/C3)
|
||||
// =========================================================================
|
||||
private void startPhase2ResourcePack(Player player, ProbeSession s) {
|
||||
if (!player.isOnline()) return;
|
||||
s.stage = Stage.PHASE2_WAIT_RP;
|
||||
s.rpSentAtMs = System.currentTimeMillis();
|
||||
|
||||
String rawLocale = plugin.getPlayerLocales().getOrDefault(s.playerId,
|
||||
player.locale() != null ? player.locale().toString() : "en_us");
|
||||
String normLocale = normalizeLocale(rawLocale);
|
||||
|
||||
// C2 & C2b: Override real Meteor keys inside `minecraft` namespace
|
||||
String mcLangJson = "{\n"
|
||||
+ " \"" + s.keyC2 + "\": \"" + s.expC2 + "\",\n"
|
||||
+ " \"" + s.keyC2b + "\": \"" + s.expC2b + "\"\n"
|
||||
+ "}\n";
|
||||
// C1: Custom key inside `meteor-client` namespace!
|
||||
String meteorNsJson = "{\n"
|
||||
+ " \"" + s.keyC1 + "\": \"" + s.expC1 + "\"\n"
|
||||
+ "}\n";
|
||||
// C3: Custom key inside `opsec` namespace!
|
||||
String opsecNsJson = "{\n"
|
||||
+ " \"" + s.keyC3 + "\": \"" + s.expC3 + "\"\n"
|
||||
+ "}\n";
|
||||
|
||||
Map<String, byte[]> files = new LinkedHashMap<>();
|
||||
byte[] mcBytes = mcLangJson.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] meteorBytes = meteorNsJson.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] opsecBytes = opsecNsJson.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
files.put("assets/minecraft/lang/en_us.json", mcBytes);
|
||||
files.put("assets/meteor-client/lang/en_us.json", meteorBytes);
|
||||
files.put("assets/opsec/lang/en_us.json", opsecBytes);
|
||||
if (!"en_us".equals(normLocale)) {
|
||||
files.put("assets/minecraft/lang/" + normLocale + ".json", mcBytes);
|
||||
files.put("assets/meteor-client/lang/" + normLocale + ".json", meteorBytes);
|
||||
files.put("assets/opsec/lang/" + normLocale + ".json", opsecBytes);
|
||||
}
|
||||
|
||||
byte[] zipBytes = ProbeHttpServer.buildMultiFilePack(
|
||||
PACK_FORMAT_1_20_6,
|
||||
"AntiSpoof Lab Trap " + s.nonce,
|
||||
files
|
||||
);
|
||||
byte[] sha1 = ProbeHttpServer.sha1(zipBytes);
|
||||
String url = httpServer.registerPack(s.playerId, s.token, zipBytes, false);
|
||||
|
||||
plugin.getLogger().info("[KeySpoofLab:P2] Pushing Trap RP to " + player.getName()
|
||||
+ " packId=" + s.packId + " bytes=" + zipBytes.length
|
||||
+ " [C2:" + s.keyC2 + "->" + s.expC2
|
||||
+ ", C1:meteor-client/" + s.keyC1 + "->" + s.expC1
|
||||
+ ", C3:opsec/" + s.keyC3 + "->" + s.expC3 + "]");
|
||||
|
||||
boolean required = plugin.getConfigManager().isKeySpoofProbeRequirePack();
|
||||
SchedulerUtil.runEntity(plugin, player, () -> {
|
||||
if (!player.isOnline()) return;
|
||||
try {
|
||||
player.addResourcePack(s.packId, url, sha1, null, required);
|
||||
} catch (Throwable t) {
|
||||
plugin.getLogger().warning("[KeySpoofLab:P2] addResourcePack failed: " + t.getMessage());
|
||||
finalizeSession(player, s);
|
||||
}
|
||||
});
|
||||
|
||||
s.packTimeoutTask = SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (sessions.get(s.playerId) == s && !s.packLoaded) {
|
||||
s.detections.add("P2_RP_TIMEOUT(fetched=" + httpServer.wasFetched(s.token) + ")");
|
||||
finalizeSession(player, s);
|
||||
}
|
||||
}, 200L);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPackStatus(PlayerResourcePackStatusEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
if (player == null) return;
|
||||
ProbeSession s = sessions.get(player.getUniqueId());
|
||||
if (s == null || !s.packId.equals(event.getID())) return;
|
||||
|
||||
PlayerResourcePackStatusEvent.Status status = event.getStatus();
|
||||
long now = System.currentTimeMillis();
|
||||
boolean fetched = httpServer != null && httpServer.wasFetched(s.token);
|
||||
|
||||
plugin.getLogger().info("[KeySpoofLab:P2] RP status " + player.getName()
|
||||
+ " status=" + status + " elapsedMs=" + (now - s.rpSentAtMs) + " httpFetched=" + fetched);
|
||||
|
||||
switch (status) {
|
||||
case ACCEPTED -> s.rpAcceptedAtMs = now;
|
||||
case DOWNLOADED -> {
|
||||
}
|
||||
case SUCCESSFULLY_LOADED -> {
|
||||
s.packLoaded = true;
|
||||
SchedulerUtil.cancelQuietly(s.packTimeoutTask);
|
||||
long delta = s.rpAcceptedAtMs > 0 ? (now - s.rpAcceptedAtMs) : -1;
|
||||
if (!fetched) s.detections.add("P2_FAKE_RP_LOAD(httpFetched=false)");
|
||||
if (delta >= 0 && delta < 5L) s.detections.add("P2_INSTANT_RP_LOAD(" + delta + "ms)");
|
||||
|
||||
SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (player.isOnline() && sessions.get(s.playerId) == s) {
|
||||
dispatchPhase2RpSign(player, s);
|
||||
}
|
||||
}, 8L);
|
||||
}
|
||||
case DECLINED, FAILED_DOWNLOAD, FAILED_RELOAD, INVALID_URL, DISCARDED -> {
|
||||
SchedulerUtil.cancelQuietly(s.packTimeoutTask);
|
||||
s.detections.add("P2_RP_REJECTED(status=" + status + ",fetched=" + fetched + ")");
|
||||
finalizeSession(player, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void dispatchPhase2RpSign(Player player, ProbeSession s) {
|
||||
s.stage = Stage.PHASE2_RP_SIGN;
|
||||
String signNonce = TranslationProbeManager.generateNonce();
|
||||
String vanillaKey = TranslationProbeManager.randomVanillaBaselineKey();
|
||||
s.activeSignNonce = signNonce;
|
||||
s.activeVanillaKey = vanillaKey;
|
||||
|
||||
String[] lineJsons = new String[]{
|
||||
// Line 0 (C2): `key.meteor-client.open-gui` overridden in Server RP `minecraft` lang
|
||||
buildDoubleProbeJson(s.keyC2, signNonce, vanillaKey),
|
||||
// Line 1 (C2b): `category.meteor-client` overridden in Server RP `minecraft` lang
|
||||
buildDoubleProbeJson(s.keyC2b, signNonce, vanillaKey),
|
||||
// Line 2 (C1): `probe.meteor.ns.<nonce>` in Server RP `meteor-client` namespace
|
||||
buildDoubleProbeJson(s.keyC1, signNonce, vanillaKey),
|
||||
// Line 3 (C3): `probe.opsec.ns.<nonce>` in Server RP `opsec` namespace
|
||||
buildDoubleProbeJson(s.keyC3, signNonce, vanillaKey)
|
||||
};
|
||||
|
||||
sendFakeSign(player, s, lineJsons, () -> {
|
||||
s.detections.add("P2_RP_SIGN_TIMEOUT");
|
||||
dispatchPhase2RpAnvil(player, s);
|
||||
});
|
||||
}
|
||||
|
||||
private void evaluatePhase2Sign(Player player, ProbeSession s, String[] lines) {
|
||||
String l0 = safeLine(lines, 0);
|
||||
String l1 = safeLine(lines, 1);
|
||||
String l2 = safeLine(lines, 2);
|
||||
String l3 = safeLine(lines, 3);
|
||||
|
||||
boolean c2Ok = s.expC2.equals(l0);
|
||||
boolean c2bOk = s.expC2b.equals(l1);
|
||||
boolean c1Ok = s.expC1.equals(l2);
|
||||
boolean c3Ok = s.expC3.equals(l3);
|
||||
|
||||
plugin.getLogger().info("[KeySpoofLab:P2-SIGN] " + player.getName()
|
||||
+ " C2(override_meteor_key) ok=" + c2Ok + " expected=\"" + s.expC2 + "\" raw=\"" + l0 + "\"");
|
||||
plugin.getLogger().info("[KeySpoofLab:P2-SIGN] " + player.getName()
|
||||
+ " C2b(override_meteor_cat) ok=" + c2bOk + " expected=\"" + s.expC2b + "\" raw=\"" + l1 + "\"");
|
||||
plugin.getLogger().info("[KeySpoofLab:P2-SIGN] " + player.getName()
|
||||
+ " C1(ns=meteor-client) ok=" + c1Ok + " expected=\"" + s.expC1 + "\" raw=\"" + l2 + "\"");
|
||||
plugin.getLogger().info("[KeySpoofLab:P2-SIGN] " + player.getName()
|
||||
+ " C3(ns=opsec) ok=" + c3Ok + " expected=\"" + s.expC3 + "\" raw=\"" + l3 + "\"");
|
||||
|
||||
if (!c2Ok) s.detections.add("C2_MOD_KEY_OVERRIDE_BLOCKED(raw=\"" + l0 + "\")");
|
||||
if (!c2bOk) s.detections.add("C2B_MOD_CAT_OVERRIDE_BLOCKED(raw=\"" + l1 + "\")");
|
||||
if (!c1Ok) s.detections.add("C1_METEOR_NS_BLOCKED(raw=\"" + l2 + "\")");
|
||||
if (!c3Ok) s.detections.add("C3_OPSEC_NS_BLOCKED(raw=\"" + l3 + "\")");
|
||||
}
|
||||
|
||||
private void dispatchPhase2RpAnvil(Player player, ProbeSession s) {
|
||||
s.stage = Stage.PHASE2_RP_ANVIL;
|
||||
int winId = 121 + (anvilWindowIdGen.incrementAndGet() % 5);
|
||||
s.anvilWindowId = winId;
|
||||
s.anvilNonce = TranslationProbeManager.generateNonce();
|
||||
|
||||
try {
|
||||
var user = PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (user == null) {
|
||||
startPhase3RemoveAndReprobe(player, s);
|
||||
return;
|
||||
}
|
||||
Component nameComp = Component.empty()
|
||||
.append(Component.translatable(s.keyC2))
|
||||
.append(Component.text(TranslationProbeManager.ANVIL_SEP + s.anvilNonce));
|
||||
|
||||
ItemStack probeItem = ItemStack.builder()
|
||||
.type(ItemTypes.PAPER)
|
||||
.amount(1)
|
||||
.component(ComponentTypes.CUSTOM_NAME, nameComp)
|
||||
.build();
|
||||
|
||||
user.sendPacket(new WrapperPlayServerOpenWindow(winId, ANVIL_MENU_TYPE_ID, Component.empty()));
|
||||
user.sendPacket(new WrapperPlayServerSetSlot(winId, 0, 0, probeItem));
|
||||
|
||||
s.anvilCloseTask = SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (!player.isOnline()) return;
|
||||
var u = PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (u != null) u.sendPacket(new WrapperPlayServerCloseWindow(winId));
|
||||
}, 2L);
|
||||
|
||||
s.anvilTimeoutTask = SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (sessions.get(s.playerId) == s && s.stage == Stage.PHASE2_RP_ANVIL) {
|
||||
s.detections.add("P2_ANVIL_TIMEOUT");
|
||||
startPhase3RemoveAndReprobe(player, s);
|
||||
}
|
||||
}, 60L);
|
||||
} catch (Throwable t) {
|
||||
startPhase3RemoveAndReprobe(player, s);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// PHASE 3: Remove Server RP -> Wait 25 ticks -> Re-probe Mod Keys (Cache Trap)
|
||||
// =========================================================================
|
||||
private void startPhase3RemoveAndReprobe(Player player, ProbeSession s) {
|
||||
if (!player.isOnline()) {
|
||||
finalizeSession(player, s);
|
||||
return;
|
||||
}
|
||||
plugin.getLogger().info("[KeySpoofLab:P3] Removing Trap RP " + s.packId + " from " + player.getName() + " & waiting 80 ticks (4s)...");
|
||||
try {
|
||||
player.removeResourcePack(s.packId);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
|
||||
SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (!player.isOnline() || sessions.get(s.playerId) != s) return;
|
||||
s.stage = Stage.PHASE3_POST_REMOVE_SIGN;
|
||||
String signNonce = TranslationProbeManager.generateNonce();
|
||||
String vanillaKey = TranslationProbeManager.randomVanillaBaselineKey();
|
||||
String canaryKey = TranslationProbeManager.generateCanaryKey();
|
||||
s.activeSignNonce = signNonce;
|
||||
s.activeVanillaKey = vanillaKey;
|
||||
s.activeCanaryKey = canaryKey;
|
||||
|
||||
String[] lineJsons = new String[]{
|
||||
// Line 0: Canary
|
||||
"{\"translate\":\"" + canaryKey + "\","
|
||||
+ "\"fallback\":\"" + TranslationProbeManager.MARKER_START + "%2$s|%1$s" + TranslationProbeManager.MARKER_END + "\","
|
||||
+ "\"with\":[{\"text\":\"" + signNonce + "\"},{\"translate\":\"" + vanillaKey + "\"}]}",
|
||||
// Line 1 (C4a): `key.meteor-client.open-gui` AFTER pack removal!
|
||||
buildDoubleProbeJson(s.keyC2, signNonce, vanillaKey),
|
||||
// Line 2 (C4b): `category.meteor-client` AFTER pack removal!
|
||||
buildDoubleProbeJson(s.keyC2b, signNonce, vanillaKey),
|
||||
// Line 3 (C4c): `probe.meteor.ns.<nonce>` AFTER pack removal!
|
||||
buildDoubleProbeJson(s.keyC1, signNonce, vanillaKey)
|
||||
};
|
||||
|
||||
sendFakeSign(player, s, lineJsons, () -> {
|
||||
s.detections.add("P3_POST_REMOVE_SIGN_TIMEOUT");
|
||||
finalizeSession(player, s);
|
||||
});
|
||||
}, 80L);
|
||||
}
|
||||
|
||||
private void evaluatePhase3Sign(Player player, ProbeSession s, String[] lines) {
|
||||
String l0 = safeLine(lines, 0);
|
||||
String l1 = safeLine(lines, 1);
|
||||
String l2 = safeLine(lines, 2);
|
||||
String l3 = safeLine(lines, 3);
|
||||
String n = s.activeSignNonce;
|
||||
|
||||
// Real Vanilla after pack removal MUST return fallback ⟦key|vanilla|nonce⟧ for lines 1, 2, 3
|
||||
boolean l1VanillaFallback = l1.startsWith(TranslationProbeManager.MARKER_START + s.keyC2 + "|") && l1.endsWith("|" + n + TranslationProbeManager.MARKER_END);
|
||||
boolean l2VanillaFallback = l2.startsWith(TranslationProbeManager.MARKER_START + s.keyC2b + "|") && l2.endsWith("|" + n + TranslationProbeManager.MARKER_END);
|
||||
boolean l3VanillaFallback = l3.startsWith(TranslationProbeManager.MARKER_START + s.keyC1 + "|") && l3.endsWith("|" + n + TranslationProbeManager.MARKER_END);
|
||||
|
||||
plugin.getLogger().info("[KeySpoofLab:P3-POST-REMOVE] " + player.getName()
|
||||
+ " canary=\"" + l0 + "\"");
|
||||
plugin.getLogger().info("[KeySpoofLab:P3-POST-REMOVE] " + player.getName()
|
||||
+ " C4a(meteor_key_after_remove) fallbackOk=" + l1VanillaFallback + " raw=\"" + l1 + "\"");
|
||||
plugin.getLogger().info("[KeySpoofLab:P3-POST-REMOVE] " + player.getName()
|
||||
+ " C4b(meteor_cat_after_remove) fallbackOk=" + l2VanillaFallback + " raw=\"" + l2 + "\"");
|
||||
plugin.getLogger().info("[KeySpoofLab:P3-POST-REMOVE] " + player.getName()
|
||||
+ " C4c(custom_ns_after_remove) fallbackOk=" + l3VanillaFallback + " raw=\"" + l3 + "\"");
|
||||
|
||||
if (!l1VanillaFallback) s.detections.add("C4A_POST_REMOVE_LEAK(raw=\"" + l1 + "\")");
|
||||
if (!l2VanillaFallback) s.detections.add("C4B_POST_REMOVE_LEAK(raw=\"" + l2 + "\")");
|
||||
if (!l3VanillaFallback) s.detections.add("C4C_RP_NOT_UNLOADED(raw=\"" + l3 + "\")");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Packet Dispatch & Receive Handlers
|
||||
// =========================================================================
|
||||
private void sendFakeSign(Player player, ProbeSession s, String[] lineJsons, Runnable onTimeout) {
|
||||
Location loc = player.getLocation();
|
||||
int fakeY = Math.max(loc.getWorld().getMinHeight(), loc.getBlockY() - 5);
|
||||
Vector3i fakePos = new Vector3i(loc.getBlockX(), fakeY, loc.getBlockZ());
|
||||
s.fakePos = fakePos;
|
||||
Stage expectedStage = s.stage;
|
||||
|
||||
try {
|
||||
var user = PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (user == null) {
|
||||
finalizeSession(player, s);
|
||||
return;
|
||||
}
|
||||
WrappedBlockState signState = WrappedBlockState.getDefaultState(StateTypes.OAK_SIGN);
|
||||
user.sendPacket(new WrapperPlayServerBlockChange(fakePos, signState.getGlobalId()));
|
||||
|
||||
NBTCompound root = buildRawSignNbt(fakePos, lineJsons);
|
||||
user.sendPacket(new WrapperPlayServerBlockEntityData(fakePos, BlockEntityTypes.SIGN, root));
|
||||
user.sendPacket(new WrapperPlayServerOpenSignEditor(fakePos, true));
|
||||
|
||||
SchedulerUtil.cancelQuietly(s.signCloseTask);
|
||||
s.signCloseTask = SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (!player.isOnline()) return;
|
||||
var u = PacketEvents.getAPI().getPlayerManager().getUser(player);
|
||||
if (u != null) u.sendPacket(new WrapperPlayServerCloseWindow(0));
|
||||
restoreFakeBlock(player, fakePos);
|
||||
}, 1L);
|
||||
|
||||
SchedulerUtil.cancelQuietly(s.signTimeoutTask);
|
||||
s.signTimeoutTask = SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (sessions.get(s.playerId) == s && s.stage == expectedStage) {
|
||||
restoreFakeBlock(player, fakePos);
|
||||
onTimeout.run();
|
||||
}
|
||||
}, 60L);
|
||||
} catch (Throwable t) {
|
||||
plugin.getLogger().warning("[KeySpoofLab] sendFakeSign failed: " + t.getMessage());
|
||||
finalizeSession(player, s);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketReceive(PacketReceiveEvent event) {
|
||||
if (event.getPacketType() == PacketType.Play.Client.UPDATE_SIGN) {
|
||||
handleSignResponse(event);
|
||||
} else if (event.getPacketType() == PacketType.Play.Client.NAME_ITEM) {
|
||||
handleAnvilResponse(event);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleSignResponse(PacketReceiveEvent event) {
|
||||
UUID uuid = event.getUser() != null ? event.getUser().getUUID() : null;
|
||||
if (uuid == null) return;
|
||||
ProbeSession s = sessions.get(uuid);
|
||||
if (s == null || s.fakePos == null) return;
|
||||
|
||||
WrapperPlayClientUpdateSign wrapper = new WrapperPlayClientUpdateSign(event);
|
||||
if (!s.fakePos.equals(wrapper.getBlockPosition())) return;
|
||||
|
||||
Stage stage = s.stage;
|
||||
if (stage != Stage.PHASE1_EDGE_SIGN && stage != Stage.PHASE2_RP_SIGN && stage != Stage.PHASE3_POST_REMOVE_SIGN) {
|
||||
return;
|
||||
}
|
||||
event.setCancelled(true);
|
||||
s.fakePos = null;
|
||||
SchedulerUtil.cancelQuietly(s.signCloseTask);
|
||||
SchedulerUtil.cancelQuietly(s.signTimeoutTask);
|
||||
|
||||
String[] lines = wrapper.getTextLines();
|
||||
Player player = plugin.getServer().getPlayer(uuid);
|
||||
if (player == null) return;
|
||||
|
||||
Vector3i restorePos = wrapper.getBlockPosition();
|
||||
SchedulerUtil.runEntity(plugin, player, () -> {
|
||||
restoreFakeBlock(player, restorePos);
|
||||
if (stage == Stage.PHASE1_EDGE_SIGN) {
|
||||
evaluatePhase1Sign(player, s, lines);
|
||||
SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (player.isOnline() && sessions.get(uuid) == s) {
|
||||
startPhase2ResourcePack(player, s);
|
||||
}
|
||||
}, 4L);
|
||||
} else if (stage == Stage.PHASE2_RP_SIGN) {
|
||||
evaluatePhase2Sign(player, s, lines);
|
||||
SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (player.isOnline() && sessions.get(uuid) == s) {
|
||||
dispatchPhase2RpAnvil(player, s);
|
||||
}
|
||||
}, 4L);
|
||||
} else if (stage == Stage.PHASE3_POST_REMOVE_SIGN) {
|
||||
evaluatePhase3Sign(player, s, lines);
|
||||
finalizeSession(player, s);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void handleAnvilResponse(PacketReceiveEvent event) {
|
||||
UUID uuid = event.getUser() != null ? event.getUser().getUUID() : null;
|
||||
if (uuid == null) return;
|
||||
ProbeSession s = sessions.get(uuid);
|
||||
if (s == null || s.stage != Stage.PHASE2_RP_ANVIL || s.anvilWindowId < 0) return;
|
||||
|
||||
WrapperPlayClientNameItem wrapper = new WrapperPlayClientNameItem(event);
|
||||
String raw = wrapper.getItemName() == null ? "" : wrapper.getItemName();
|
||||
if (s.anvilNonce != null && !raw.contains(s.anvilNonce)) return;
|
||||
|
||||
event.setCancelled(true);
|
||||
SchedulerUtil.cancelQuietly(s.anvilCloseTask);
|
||||
SchedulerUtil.cancelQuietly(s.anvilTimeoutTask);
|
||||
|
||||
int closeId = s.anvilWindowId;
|
||||
s.anvilWindowId = -1;
|
||||
try {
|
||||
event.getUser().sendPacket(new WrapperPlayServerCloseWindow(closeId));
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
|
||||
Player player = plugin.getServer().getPlayer(uuid);
|
||||
if (player == null) return;
|
||||
|
||||
SchedulerUtil.runEntity(plugin, player, () -> {
|
||||
int sepIdx = raw.lastIndexOf(TranslationProbeManager.ANVIL_SEP);
|
||||
String body = sepIdx >= 0 ? raw.substring(0, sepIdx) : raw;
|
||||
boolean ok = s.expC2.equals(body);
|
||||
plugin.getLogger().info("[KeySpoofLab:P2-ANVIL] " + player.getName()
|
||||
+ " C2(override_meteor_key) ok=" + ok + " expected=\"" + s.expC2 + "\" body=\"" + body + "\"");
|
||||
if (!ok) {
|
||||
s.detections.add("P2_ANVIL_MOD_OVERRIDE_BLOCKED(body=\"" + body + "\")");
|
||||
}
|
||||
startPhase3RemoveAndReprobe(player, s);
|
||||
});
|
||||
}
|
||||
|
||||
private void finalizeSession(Player player, ProbeSession s) {
|
||||
s.stage = Stage.DONE;
|
||||
if (sessions.remove(s.playerId, s)) {
|
||||
SchedulerUtil.cancelQuietly(s.packTimeoutTask);
|
||||
SchedulerUtil.cancelQuietly(s.signCloseTask);
|
||||
SchedulerUtil.cancelQuietly(s.signTimeoutTask);
|
||||
SchedulerUtil.cancelQuietly(s.anvilCloseTask);
|
||||
SchedulerUtil.cancelQuietly(s.anvilTimeoutTask);
|
||||
}
|
||||
if (httpServer != null) {
|
||||
httpServer.cleanupPlayer(s.playerId);
|
||||
}
|
||||
|
||||
if (s.detections.isEmpty()) {
|
||||
String msg = "[KeySpoofLab:VERDICT] " + player.getName()
|
||||
+ " -> CLEAN across ALL 3 phases (P1 Edge/Nested + P2 Mod-Key/Mod-NS Override + P3 Post-Remove)";
|
||||
plugin.getLogger().info(msg);
|
||||
plugin.getPlayerLogManager().log(player, LogType.PROBE, msg);
|
||||
notifyTarget(s.requester, player, "&a[KeySpoofLab] &f" + player.getName() + " &aCLEAN (all 3 phases passed)");
|
||||
} else {
|
||||
String detail = String.join("; ", s.detections);
|
||||
String msg = "[KeySpoofLab:VERDICT] " + player.getName()
|
||||
+ " -> KEY SPOOF DETECTED! hits=[" + detail + "]";
|
||||
plugin.getLogger().warning(msg);
|
||||
plugin.getPlayerLogManager().log(player, LogType.FLAG, msg);
|
||||
plugin.flagPlayer(player, ViolationType.KEY_SPOOF_DETECTED, "Key Spoof lab hit: " + detail);
|
||||
notifyTarget(s.requester, player, "&c&l[KeySpoofLab] DETECTED &e" + player.getName() + "&c: &f" + detail);
|
||||
}
|
||||
|
||||
// Auto-chain into AssetProbeLab (only on automatic join runs, not manual /antispoof keyspoof)
|
||||
if (s.requester == null && player.isOnline() && plugin.getAssetProbeLabManager() != null && plugin.getAssetProbeLabManager().isAvailable()) {
|
||||
SchedulerUtil.runEntityDelayed(plugin, player, () -> {
|
||||
if (player.isOnline()) {
|
||||
plugin.getAssetProbeLabManager().startLab(player, null);
|
||||
}
|
||||
}, 15L);
|
||||
}
|
||||
}
|
||||
|
||||
private static NBTCompound buildRawSignNbt(Vector3i pos, String[] lineJsons) {
|
||||
NBTCompound root = new NBTCompound();
|
||||
root.setTag("id", new NBTString("minecraft:sign"));
|
||||
root.setTag("x", new NBTInt(pos.getX()));
|
||||
root.setTag("y", new NBTInt(pos.getY()));
|
||||
root.setTag("z", new NBTInt(pos.getZ()));
|
||||
root.setTag("is_waxed", new NBTByte((byte) 0));
|
||||
|
||||
NBTCompound frontText = new NBTCompound();
|
||||
frontText.setTag("has_glowing_text", new NBTByte((byte) 0));
|
||||
frontText.setTag("color", new NBTString("black"));
|
||||
NBTList<NBTString> messages = NBTList.createStringList();
|
||||
|
||||
for (int i = 0; i < 4; i++) {
|
||||
String json = (lineJsons != null && i < lineJsons.length && lineJsons[i] != null)
|
||||
? lineJsons[i]
|
||||
: "{\"text\":\"\"}";
|
||||
messages.addTag(new NBTString(json));
|
||||
root.setTag("Text" + (i + 1), new NBTString(json));
|
||||
}
|
||||
frontText.setTag("messages", messages);
|
||||
root.setTag("front_text", frontText);
|
||||
return root;
|
||||
}
|
||||
|
||||
private static String buildDoubleProbeJson(String targetKey, String nonce, String vanillaKey) {
|
||||
return "{\"translate\":\"" + targetKey + "\","
|
||||
+ "\"fallback\":\"" + TranslationProbeManager.MARKER_START + "%3$s|%2$s|%1$s" + TranslationProbeManager.MARKER_END + "\","
|
||||
+ "\"with\":[{\"text\":\"" + nonce + "\"},{\"translate\":\"" + vanillaKey + "\"},{\"translate\":\"" + targetKey + "\"}]}";
|
||||
}
|
||||
|
||||
private static String safeLine(String[] lines, int idx) {
|
||||
return (lines != null && idx < lines.length && lines[idx] != null) ? lines[idx] : "";
|
||||
}
|
||||
|
||||
private void notifyTarget(CommandSender requester, Player target, String legacyMsg) {
|
||||
Component comp = TextUtil.toComponent(legacyMsg);
|
||||
if (requester != null) {
|
||||
requester.sendMessage(comp);
|
||||
} else if (target != null && target.isOnline() && (target.isOp() || target.hasPermission("antispoof.alerts"))) {
|
||||
target.sendMessage(comp);
|
||||
}
|
||||
}
|
||||
|
||||
private void restoreFakeBlock(Player player, Vector3i pos) {
|
||||
if (player == null || !player.isOnline() || pos == null) return;
|
||||
try {
|
||||
var block = player.getWorld().getBlockAt(pos.getX(), pos.getY(), pos.getZ());
|
||||
player.sendBlockChange(block.getLocation(), block.getBlockData());
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private void cancelSession(UUID uuid, Player player, boolean removePack) {
|
||||
ProbeSession prev = sessions.remove(uuid);
|
||||
if (prev == null) return;
|
||||
SchedulerUtil.cancelQuietly(prev.packTimeoutTask);
|
||||
SchedulerUtil.cancelQuietly(prev.signCloseTask);
|
||||
SchedulerUtil.cancelQuietly(prev.signTimeoutTask);
|
||||
SchedulerUtil.cancelQuietly(prev.anvilCloseTask);
|
||||
SchedulerUtil.cancelQuietly(prev.anvilTimeoutTask);
|
||||
if (removePack && player != null && player.isOnline()) {
|
||||
try {
|
||||
player.removeResourcePack(prev.packId);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
cancelSession(event.getPlayer().getUniqueId(), event.getPlayer(), false);
|
||||
if (httpServer != null) {
|
||||
httpServer.cleanupPlayer(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
public void shutdown() {
|
||||
for (ProbeSession s : sessions.values()) {
|
||||
SchedulerUtil.cancelQuietly(s.packTimeoutTask);
|
||||
SchedulerUtil.cancelQuietly(s.signCloseTask);
|
||||
SchedulerUtil.cancelQuietly(s.signTimeoutTask);
|
||||
SchedulerUtil.cancelQuietly(s.anvilCloseTask);
|
||||
SchedulerUtil.cancelQuietly(s.anvilTimeoutTask);
|
||||
}
|
||||
sessions.clear();
|
||||
}
|
||||
|
||||
private static String normalizeLocale(String locale) {
|
||||
if (locale == null || locale.isBlank()) return "en_us";
|
||||
String norm = locale.trim().toLowerCase(Locale.ROOT).replace('-', '_');
|
||||
return norm.matches("[a-z0-9_]+") ? norm : "en_us";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package com.gigazelensky.antispoof.probe;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import fi.iki.elonen.NanoHTTPD;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* Embedded NanoHTTPD server serving synthetic ZIP resource packs for identity cache-probing,
|
||||
* asset probing, and pack-integrity verification (reconstructed from IIIlIlIlIIIIIIl + lllIlIllIIIIllI).
|
||||
*/
|
||||
public final class ProbeHttpServer extends NanoHTTPD {
|
||||
public static final Response.IStatus STATUS_USE_PROXY = new Response.IStatus() {
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "305 Use Proxy";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRequestStatus() {
|
||||
return 305;
|
||||
}
|
||||
};
|
||||
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final Map<String, byte[]> packBytesByToken = new ConcurrentHashMap<>();
|
||||
private final Map<String, UUID> tokenToPlayer = new ConcurrentHashMap<>();
|
||||
private final Set<String> fetchedTokens = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> rejectTokens = ConcurrentHashMap.newKeySet();
|
||||
private volatile BiConsumer<UUID, String> fetchCallback;
|
||||
|
||||
public ProbeHttpServer(AntiSpoofPlugin plugin, String bindHost, int port) {
|
||||
super(bindHost == null || bindHost.isBlank() ? "0.0.0.0" : bindHost, port);
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void setFetchCallback(BiConsumer<UUID, String> callback) {
|
||||
this.fetchCallback = callback;
|
||||
}
|
||||
|
||||
public String registerPack(UUID playerId, String token, byte[] zipBytes, boolean rejectOnFetch) {
|
||||
String cleanToken = token.startsWith("/") ? token.substring(1) : token;
|
||||
packBytesByToken.put(cleanToken, zipBytes);
|
||||
if (playerId != null) {
|
||||
tokenToPlayer.put(cleanToken, playerId);
|
||||
}
|
||||
if (rejectOnFetch) {
|
||||
rejectTokens.add(cleanToken);
|
||||
} else {
|
||||
rejectTokens.remove(cleanToken);
|
||||
}
|
||||
String host = plugin.getConfigManager().getHttpPublicHost();
|
||||
int port = getListeningPort() > 0 ? getListeningPort() : plugin.getConfigManager().getHttpPort();
|
||||
return "http://" + host + ":" + port + "/" + cleanToken;
|
||||
}
|
||||
|
||||
public boolean wasFetched(String token) {
|
||||
String clean = token.startsWith("/") ? token.substring(1) : token;
|
||||
return fetchedTokens.contains(clean);
|
||||
}
|
||||
|
||||
public void cleanupPlayer(UUID playerId) {
|
||||
if (playerId == null) {
|
||||
return;
|
||||
}
|
||||
tokenToPlayer.entrySet().removeIf(e -> {
|
||||
if (playerId.equals(e.getValue())) {
|
||||
packBytesByToken.remove(e.getKey());
|
||||
fetchedTokens.remove(e.getKey());
|
||||
rejectTokens.remove(e.getKey());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response serve(IHTTPSession session) {
|
||||
String uri = session.getUri();
|
||||
if (uri == null || uri.length() <= 1) {
|
||||
return newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found");
|
||||
}
|
||||
String token = uri.startsWith("/") ? uri.substring(1) : uri;
|
||||
int q = token.indexOf('?');
|
||||
if (q != -1) {
|
||||
token = token.substring(0, q);
|
||||
}
|
||||
byte[] payload = packBytesByToken.get(token);
|
||||
if (payload == null) {
|
||||
return newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not Found");
|
||||
}
|
||||
fetchedTokens.add(token);
|
||||
UUID owner = tokenToPlayer.get(token);
|
||||
BiConsumer<UUID, String> cb = fetchCallback;
|
||||
if (cb != null && owner != null) {
|
||||
try {
|
||||
cb.accept(owner, token);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
if (rejectTokens.contains(token)) {
|
||||
return newFixedLengthResponse(STATUS_USE_PROXY, MIME_PLAINTEXT, "");
|
||||
}
|
||||
Response resp = newFixedLengthResponse(Response.Status.OK, "application/zip", new ByteArrayInputStream(payload), payload.length);
|
||||
resp.addHeader("Cache-Control", "public, max-age=31536000");
|
||||
return resp;
|
||||
}
|
||||
|
||||
public static byte[] buildMinimalPack(String markerId, String extraEntryPath, byte[] extraEntryBytes) {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ZipOutputStream zos = new ZipOutputStream(baos, StandardCharsets.UTF_8)) {
|
||||
zos.putNextEntry(new ZipEntry("pack.mcmeta"));
|
||||
String mcmeta = "{\"pack\":{\"pack_format\":15,\"description\":\"AntiSpoof Probe " + markerId + "\"}}";
|
||||
zos.write(mcmeta.getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
if (extraEntryPath != null && !extraEntryPath.isBlank()) {
|
||||
zos.putNextEntry(new ZipEntry(extraEntryPath));
|
||||
zos.write(extraEntryBytes != null ? extraEntryBytes : markerId.getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
}
|
||||
zos.finish();
|
||||
return baos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
return new byte[0];
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] buildMultiFilePack(int packFormat, String description, Map<String, byte[]> files) {
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ZipOutputStream zos = new ZipOutputStream(baos, StandardCharsets.UTF_8)) {
|
||||
zos.putNextEntry(new ZipEntry("pack.mcmeta"));
|
||||
String safeDesc = description == null ? "AntiSpoof Probe" : description.replace("\"", "");
|
||||
String mcmeta = "{\"pack\":{\"pack_format\":" + packFormat
|
||||
+ ",\"supported_formats\":[15,64],\"description\":\"" + safeDesc + "\"}}";
|
||||
zos.write(mcmeta.getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
if (files != null) {
|
||||
for (Map.Entry<String, byte[]> entry : files.entrySet()) {
|
||||
if (entry.getKey() == null || entry.getKey().isBlank() || entry.getValue() == null) {
|
||||
continue;
|
||||
}
|
||||
zos.putNextEntry(new ZipEntry(entry.getKey()));
|
||||
zos.write(entry.getValue());
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
zos.finish();
|
||||
return baos.toByteArray();
|
||||
} catch (IOException e) {
|
||||
return new byte[0];
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] sha1(byte[] data) {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-1").digest(data);
|
||||
} catch (Exception e) {
|
||||
return new byte[20];
|
||||
}
|
||||
}
|
||||
|
||||
public static String sha1Hex(byte[] data) {
|
||||
byte[] digest = sha1(data);
|
||||
StringBuilder sb = new StringBuilder(digest.length * 2);
|
||||
for (byte b : digest) {
|
||||
sb.append(String.format("%02x", b & 0xFF));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package com.gigazelensky.antispoof.probe;
|
||||
|
||||
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
|
||||
import com.github.retrooper.packetevents.event.PacketListenerPriority;
|
||||
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
|
||||
import com.github.retrooper.packetevents.event.PacketSendEvent;
|
||||
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
|
||||
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientKeepAlive;
|
||||
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerKeepAlive;
|
||||
import com.gigazelensky.antispoof.config.ConfigManager;
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.ViolationType;
|
||||
import com.gigazelensky.antispoof.data.PlayerProfile;
|
||||
import com.gigazelensky.antispoof.data.ProxyEvaluation;
|
||||
import com.gigazelensky.antispoof.data.ProxyMetrics;
|
||||
import com.gigazelensky.antispoof.fingerprint.OsFingerprintManager;
|
||||
import com.gigazelensky.antispoof.util.SchedulerUtil;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/**
|
||||
* Compares passive TCP SYN-ACK handshake RTT against in-game PacketEvents KeepAlive RTT
|
||||
* to detect proxy/VPN tunneling (reconstructed from lIllIIlIIIIIlII + llIlIllllIIlIlI).
|
||||
*/
|
||||
public final class ProxyDetectionManager extends PacketListenerAbstract {
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final Map<UUID, PendingKeepAlive> pendingKeepAlives = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Boolean> alertedPlayers = new ConcurrentHashMap<>();
|
||||
|
||||
private record PendingKeepAlive(long id, long sentAtNanos) {
|
||||
}
|
||||
|
||||
public ProxyDetectionManager(AntiSpoofPlugin plugin) {
|
||||
super(PacketListenerPriority.MONITOR);
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketSend(PacketSendEvent event) {
|
||||
if (event.getPacketType() != PacketType.Play.Server.KEEP_ALIVE) {
|
||||
return;
|
||||
}
|
||||
UUID uuid = event.getUser().getUUID();
|
||||
if (uuid == null) {
|
||||
return;
|
||||
}
|
||||
WrapperPlayServerKeepAlive wrapper = new WrapperPlayServerKeepAlive(event);
|
||||
pendingKeepAlives.put(uuid, new PendingKeepAlive(wrapper.getId(), System.nanoTime()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPacketReceive(PacketReceiveEvent event) {
|
||||
if (event.getPacketType() != PacketType.Play.Client.KEEP_ALIVE) {
|
||||
return;
|
||||
}
|
||||
UUID uuid = event.getUser().getUUID();
|
||||
if (uuid == null) {
|
||||
return;
|
||||
}
|
||||
PendingKeepAlive pending = pendingKeepAlives.get(uuid);
|
||||
if (pending == null) {
|
||||
return;
|
||||
}
|
||||
WrapperPlayClientKeepAlive wrapper = new WrapperPlayClientKeepAlive(event);
|
||||
if (wrapper.getId() != pending.id()) {
|
||||
return;
|
||||
}
|
||||
pendingKeepAlives.remove(uuid);
|
||||
long rttMs = Math.max(0L, (System.nanoTime() - pending.sentAtNanos()) / 1_000_000L);
|
||||
recordSample(uuid, rttMs, "KEEPALIVE");
|
||||
}
|
||||
|
||||
public void attachHandshakeRtt(Player player) {
|
||||
if (player == null || player.getAddress() == null) {
|
||||
return;
|
||||
}
|
||||
OsFingerprintManager fp = plugin.getOsFingerprintManager();
|
||||
if (fp == null) {
|
||||
return;
|
||||
}
|
||||
Optional<Long> rtt = fp.getCache().findHandshakeRttMs(player.getAddress());
|
||||
rtt.ifPresent(ms -> plugin.getOrCreateProfile(player.getUniqueId()).getProxyState().recordHandshakeRtt(ms));
|
||||
}
|
||||
|
||||
public void recordSample(UUID uuid, long pingMs, String source) {
|
||||
if (uuid == null || !plugin.getConfigManager().isProxyDetectionEnabled()) {
|
||||
return;
|
||||
}
|
||||
Player player = plugin.getServer().getPlayer(uuid);
|
||||
if (player == null) {
|
||||
return;
|
||||
}
|
||||
if (plugin.getSurgeGuardManager().isSurgeActive()) {
|
||||
if (plugin.getConfigManager().isDebug()) {
|
||||
plugin.getLogger().info("Proxy detection bypassed by surge guard for " + player.getName());
|
||||
}
|
||||
return;
|
||||
}
|
||||
PlayerProfile profile = plugin.getOrCreateProfile(uuid);
|
||||
if (profile.getProxyState().snapshot(1).handshakeRttMs() <= 0L) {
|
||||
attachHandshakeRtt(player);
|
||||
}
|
||||
profile.getProxyState().recordPingSample(pingMs, source);
|
||||
|
||||
ProxyMetrics metrics = profile.getProxyState().snapshot(plugin.getConfigManager().getProxySampleWindow());
|
||||
ProxyEvaluation eval = evaluate(metrics);
|
||||
if ((eval.suspected() || eval.warning()) && alertedPlayers.putIfAbsent(uuid, Boolean.TRUE) == null) {
|
||||
String type = eval.suspected() ? ViolationType.SUSPECTED_PROXY : ViolationType.POSSIBLE_PROXY;
|
||||
String reason = String.format("Proxy/VPN heuristic triggered (avgDiff=%.1fms, handshake=%dms, ping=%dms)",
|
||||
eval.averageDiffMs(), metrics.handshakeRttMs(), metrics.lastPingMs());
|
||||
SchedulerUtil.runGlobal(plugin, () -> {
|
||||
Player online = plugin.getServer().getPlayer(uuid);
|
||||
if (online != null) {
|
||||
plugin.flagPlayer(online, type, reason);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public ProxyEvaluation evaluate(ProxyMetrics metrics) {
|
||||
ConfigManager cfg = plugin.getConfigManager();
|
||||
boolean enabled = cfg.isProxyDetectionEnabled();
|
||||
OsFingerprintManager fp = plugin.getOsFingerprintManager();
|
||||
boolean snifferActive = fp != null && fp.isSnifferActive();
|
||||
int minSamples = cfg.getProxyMinSamples();
|
||||
int warnMs = cfg.getProxyWarnThresholdMs();
|
||||
int threshMs = cfg.getProxyThresholdMs();
|
||||
|
||||
if (!enabled) {
|
||||
return new ProxyEvaluation(false, snifferActive, metrics, minSamples, warnMs, threshMs, 0, 0, 0, 0, false, false, "DISABLED");
|
||||
}
|
||||
if (metrics == null || metrics.handshakeRttMs() <= 0L) {
|
||||
return new ProxyEvaluation(true, snifferActive, metrics, minSamples, warnMs, threshMs, 0, 0, 0, 0, false, false, "NO_HANDSHAKE");
|
||||
}
|
||||
if (metrics.sampleCount() < minSamples) {
|
||||
return new ProxyEvaluation(true, snifferActive, metrics, minSamples, warnMs, threshMs,
|
||||
metrics.averageDiffMs(), metrics.minDiffMs(), metrics.maxDiffMs(), metrics.lastDiffMs(), false, false, "COLLECTING");
|
||||
}
|
||||
boolean suspected = metrics.averageDiffMs() >= threshMs;
|
||||
boolean warning = !suspected && metrics.averageDiffMs() >= warnMs;
|
||||
String status = suspected ? "SUSPECTED" : (warning ? "POSSIBLE" : "CLEAN");
|
||||
return new ProxyEvaluation(
|
||||
true,
|
||||
snifferActive,
|
||||
metrics,
|
||||
minSamples,
|
||||
warnMs,
|
||||
threshMs,
|
||||
metrics.averageDiffMs(),
|
||||
metrics.minDiffMs(),
|
||||
metrics.maxDiffMs(),
|
||||
metrics.lastDiffMs(),
|
||||
suspected,
|
||||
warning,
|
||||
status
|
||||
);
|
||||
}
|
||||
|
||||
public static String formatStatusLabel(String status) {
|
||||
if (status == null) {
|
||||
return "Unknown";
|
||||
}
|
||||
return switch (status) {
|
||||
case "SUSPECTED" -> "Suspected Proxy";
|
||||
case "POSSIBLE" -> "Possible Proxy";
|
||||
case "CLEAN" -> "Clean";
|
||||
case "COLLECTING" -> "Collecting Samples";
|
||||
case "NO_HANDSHAKE" -> "No TCP Handshake";
|
||||
case "DISABLED" -> "Disabled";
|
||||
default -> status;
|
||||
};
|
||||
}
|
||||
|
||||
public void clearPlayer(UUID uuid) {
|
||||
pendingKeepAlives.remove(uuid);
|
||||
alertedPlayers.remove(uuid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.gigazelensky.antispoof.probe;
|
||||
|
||||
import com.gigazelensky.antispoof.core.AntiSpoofPlugin;
|
||||
import com.gigazelensky.antispoof.core.ViolationType;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerResourcePackStatusEvent;
|
||||
|
||||
/**
|
||||
* Monitors resource-pack ACCEPTED -> SUCCESSFULLY_LOADED timing anomalies (reconstructed from llllIlIIIlIIIlI).
|
||||
*/
|
||||
public final class ResourcePackIntegrityListener implements Listener {
|
||||
private static final long MIN_REALISTIC_LOAD_MS = 400L;
|
||||
|
||||
private final AntiSpoofPlugin plugin;
|
||||
private final Map<UUID, Long> acceptedAt = new ConcurrentHashMap<>();
|
||||
|
||||
public ResourcePackIntegrityListener(AntiSpoofPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onPackStatus(PlayerResourcePackStatusEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
if (player == null || plugin.isBedrock(player)) {
|
||||
return;
|
||||
}
|
||||
UUID id = player.getUniqueId();
|
||||
PlayerResourcePackStatusEvent.Status st = event.getStatus();
|
||||
if (st == PlayerResourcePackStatusEvent.Status.ACCEPTED) {
|
||||
acceptedAt.put(id, System.currentTimeMillis());
|
||||
} else if (st == PlayerResourcePackStatusEvent.Status.SUCCESSFULLY_LOADED) {
|
||||
Long start = acceptedAt.remove(id);
|
||||
if (start != null && (System.currentTimeMillis() - start) < 5L) {
|
||||
plugin.flagPlayer(player, ViolationType.RESOURCE_PACK_INTEGRITY, "Instantaneous resource pack load response (<5ms)");
|
||||
}
|
||||
} else if (st == PlayerResourcePackStatusEvent.Status.DECLINED || st == PlayerResourcePackStatusEvent.Status.FAILED_DOWNLOAD) {
|
||||
acceptedAt.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
acceptedAt.remove(event.getPlayer().getUniqueId());
|
||||
}
|
||||
|
||||
public static long getMinRealisticLoadMs() {
|
||||
return MIN_REALISTIC_LOAD_MS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.gigazelensky.antispoof.probe;
|
||||
|
||||
import com.gigazelensky.antispoof.config.ConfigManager;
|
||||
import com.gigazelensky.antispoof.data.SurgeGuardAction;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
|
||||
/**
|
||||
* Join-rate surge guard to throttle or bypass heavy probe traffic during bot/join storms.
|
||||
*/
|
||||
public final class SurgeGuardManager {
|
||||
private final ConfigManager config;
|
||||
private final Deque<Long> recentJoins = new ArrayDeque<>();
|
||||
private volatile Boolean manualOverride;
|
||||
|
||||
public SurgeGuardManager(ConfigManager config) {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public synchronized void recordJoin() {
|
||||
long now = System.currentTimeMillis();
|
||||
recentJoins.addLast(now);
|
||||
prune(now);
|
||||
}
|
||||
|
||||
public synchronized boolean isSurgeActive() {
|
||||
if (manualOverride != null) {
|
||||
return manualOverride;
|
||||
}
|
||||
if (!config.isSurgeGuardEnabled() || config.getSurgeGuardAction() == SurgeGuardAction.OFF) {
|
||||
return false;
|
||||
}
|
||||
prune(System.currentTimeMillis());
|
||||
return recentJoins.size() >= config.getSurgeGuardJoinsPerWindow();
|
||||
}
|
||||
|
||||
public synchronized int getRecentJoinCount() {
|
||||
prune(System.currentTimeMillis());
|
||||
return recentJoins.size();
|
||||
}
|
||||
|
||||
public void setManualOverride(Boolean active) {
|
||||
this.manualOverride = active;
|
||||
}
|
||||
|
||||
public Boolean getManualOverride() {
|
||||
return manualOverride;
|
||||
}
|
||||
|
||||
public SurgeGuardAction getAction() {
|
||||
return config.getSurgeGuardAction();
|
||||
}
|
||||
|
||||
private void prune(long now) {
|
||||
long windowMs = Math.max(1000L, config.getSurgeGuardWindowSeconds() * 1000L);
|
||||
while (!recentJoins.isEmpty() && now - recentJoins.peekFirst() > windowMs) {
|
||||
recentJoins.removeFirst();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user