commit d66f60533e7ca80c38b9d220b0ed433197f5d61b Author: notme_ssa Date: Sun Nov 29 20:07:47 2026 +0700 Initial commit: OpenAntiSpoof-FullOpsec diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..accb851 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.gradle/ +build/ +out/ +.idea/ +*.iml +*.ipr +*.iws +.vscode/ +.DS_Store +Thumbs.db diff --git a/OPSEC-AUDIT.md b/OPSEC-AUDIT.md new file mode 100644 index 0000000..3c4b044 --- /dev/null +++ b/OPSEC-AUDIT.md @@ -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 `` 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` `` 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 `), **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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d7adae8 --- /dev/null +++ b/README.md @@ -0,0 +1,82 @@ +

+
+ OpenAntiSpoof-FullOpsec +
+ by notme_ssa +

+ +--- + +

+ jak + hack + deobf2 + deobf +

+ +--- + +## 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.`), hex nonces, and vanilla baselines (`fallback: "⟦%3$s|%2$s|%1$s⟧"`), plus auto-closing Anvil `NAME_ITEM` probes (`\t`). +- **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_`) 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 `. +- **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` diff --git a/assets/deobf.jpg b/assets/deobf.jpg new file mode 100644 index 0000000..fa8dbde Binary files /dev/null and b/assets/deobf.jpg differ diff --git a/assets/deobf2.png b/assets/deobf2.png new file mode 100644 index 0000000..1d4014d Binary files /dev/null and b/assets/deobf2.png differ diff --git a/assets/hack.jpg b/assets/hack.jpg new file mode 100644 index 0000000..c4252ef Binary files /dev/null and b/assets/hack.jpg differ diff --git a/assets/jak.jpg b/assets/jak.jpg new file mode 100644 index 0000000..162bfe5 Binary files /dev/null and b/assets/jak.jpg differ diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..ce1586b --- /dev/null +++ b/build.gradle.kts @@ -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().configureEach { + options.encoding = "UTF-8" + options.release.set(21) +} + +tasks.jar { + archiveBaseName.set("AntiSpoof") + archiveVersion.set("1.5.0") +} diff --git a/gradle/gradle/wrapper/gradle-wrapper.jar b/gradle/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9fa7f28 Binary files /dev/null and b/gradle/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/gradle/wrapper/gradle-wrapper.properties b/gradle/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..91c4fc6 --- /dev/null +++ b/gradle/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..61285a6 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..19a6bde --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..249efbb --- /dev/null +++ b/gradlew @@ -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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..3185a43 --- /dev/null +++ b/gradlew.bat @@ -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% diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..08b1e33 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "AntiSpoof" diff --git a/src/main/java/com/gigazelensky/antispoof/api/AntiSpoofAPI.java b/src/main/java/com/gigazelensky/antispoof/api/AntiSpoofAPI.java new file mode 100644 index 0000000..133cbec --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/api/AntiSpoofAPI.java @@ -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 pluginRef = new AtomicReference<>(); + private final List registrations = new CopyOnWriteArrayList<>(); + private final Map 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 getClientBrand(Player player) { + return player == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerBrand(player)); + } + + public Optional getClientBrand(UUID uniqueId) { + return uniqueId == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerBrands().get(uniqueId)); + } + + public Optional getPlayerVersion(Player player) { + return player == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerVersion(player)); + } + + public Optional getPlayerVersion(UUID uniqueId) { + return uniqueId == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerVersions().get(uniqueId)); + } + + public Optional getLocale(Player player) { + return player == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerLocale(player)); + } + + public Optional getLocale(UUID uniqueId) { + return uniqueId == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerLocale(uniqueId)); + } + + public Optional> getFlagReasons(Player player) { + if (player == null) { + return Optional.empty(); + } + List reasons = requirePlugin().getFlagReasons(player); + return reasons != null && !reasons.isEmpty() ? Optional.of(List.copyOf(reasons)) : Optional.empty(); + } + + public Optional getFingerprint(UUID uniqueId) { + if (uniqueId == null) { + return Optional.empty(); + } + IdentityLinkerManager linker = requirePlugin().getIdentityLinkerManager(); + return linker == null ? Optional.empty() : linker.getFingerprint(uniqueId); + } + + public Optional getIdentitySnapshot(Player player) { + return player == null ? Optional.empty() : getIdentitySnapshot(player.getUniqueId()); + } + + public Optional getIdentitySnapshot(UUID uniqueId) { + if (uniqueId == null) { + return Optional.empty(); + } + AntiSpoofPlugin plugin = requirePlugin(); + IdentityLinkerManager linker = plugin.getIdentityLinkerManager(); + if (linker == null) { + return Optional.empty(); + } + Optional 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 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 getPlayerSnapshot(Player player) { + return player == null ? Optional.empty() : getPlayerSnapshot(player.getUniqueId()); + } + + public Optional getProxySnapshot(Player player) { + return player == null ? Optional.empty() : getProxySnapshot(player.getUniqueId()); + } + + public Optional 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 getProxyStatus(UUID uniqueId) { + return getProxySnapshot(uniqueId).map(ProxySnapshot::status); + } + + public Optional getProxyStatus(Player player) { + return player == null ? Optional.empty() : getProxyStatus(player.getUniqueId()); + } + + public Optional> getChannels(Player player) { + return player == null ? Optional.empty() : getChannels(player.getUniqueId()); + } + + public Optional> getChannels(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getChannels())); + } + + public Optional> getAllChannels(Player player) { + return player == null ? Optional.empty() : getAllChannels(player.getUniqueId()); + } + + public Optional> getAllChannels(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getAllChannels())); + } + + public Optional> getFilteredChannels(Player player) { + return player == null ? Optional.empty() : getFilteredChannels(player.getUniqueId()); + } + + public Optional> getFilteredChannels(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getFilteredChannels())); + } + + public Optional> getDetectedMods(Player player) { + return player == null ? Optional.empty() : getDetectedMods(player.getUniqueId()); + } + + public Optional> getDetectedMods(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getDetectedMods())); + } + + public Optional> getAlertedMods(Player player) { + return player == null ? Optional.empty() : getAlertedMods(player.getUniqueId()); + } + + public Optional> getAlertedMods(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getAlertedMods())); + } + + public Optional> getAlertedKeys(Player player) { + return player == null ? Optional.empty() : getAlertedKeys(player.getUniqueId()); + } + + public Optional> getAlertedKeys(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getAlertedKeys())); + } + + public Optional> getAlertedCombinations(Player player) { + return player == null ? Optional.empty() : getAlertedCombinations(player.getUniqueId()); + } + + public Optional> getAlertedCombinations(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getAlertedCombinations())); + } + + public Optional> getViolations(Player player) { + return player == null ? Optional.empty() : getViolations(player.getUniqueId()); + } + + public Optional> getViolations(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getViolations())); + } + + public Optional> getSessionViolations(Player player) { + return player == null ? Optional.empty() : getSessionViolations(player.getUniqueId()); + } + + public Optional> getSessionViolations(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getSessionViolations())); + } + + public Optional> getLastTranslatedKeys(Player player) { + return player == null ? Optional.empty() : getLastTranslatedKeys(player.getUniqueId()); + } + + public Optional> getLastTranslatedKeys(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getLastTranslatedKeys())); + } + + public Optional> getLastMissingKeys(Player player) { + return player == null ? Optional.empty() : getLastMissingKeys(player.getUniqueId()); + } + + public Optional> getLastMissingKeys(UUID uniqueId) { + return getProfile(uniqueId).map(p -> copyStrings(p.getLastMissingKeys())); + } + + public Optional getProbeStatus(Player player) { + return player == null ? Optional.empty() : getProbeStatus(player.getUniqueId()); + } + + public Optional getProbeStatus(UUID uniqueId) { + return getProfile(uniqueId).map(PlayerProfile::getProbeStatus); + } + + public Optional isAlreadyPunished(Player player) { + return player == null ? Optional.empty() : isAlreadyPunished(player.getUniqueId()); + } + + public Optional isAlreadyPunished(UUID uniqueId) { + return getProfile(uniqueId).map(PlayerProfile::isAlreadyPunished); + } + + public Optional isInitialChannelsRegistered(Player player) { + return player == null ? Optional.empty() : isInitialChannelsRegistered(player.getUniqueId()); + } + + public Optional isInitialChannelsRegistered(UUID uniqueId) { + return getProfile(uniqueId).map(PlayerProfile::isInitialChannelsRegistered); + } + + public Optional getJoinTime(Player player) { + return player == null ? Optional.empty() : getJoinTime(player.getUniqueId()); + } + + public Optional 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 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 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 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 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 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 getHistoricalViolationCount(UUID uniqueId) { + return uniqueId == null ? CompletableFuture.completedFuture(0) : requirePlugin().getHistoricalViolationCount(uniqueId); + } + + public Set 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 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 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 channels = List.copyOf(new ArrayList<>(profile.getChannels())); + List detectedMods = List.copyOf(new ArrayList<>(profile.getDetectedMods())); + List violations = List.copyOf(new ArrayList<>(profile.getViolations())); + List 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 getProfile(UUID uniqueId) { + return uniqueId == null ? Optional.empty() : Optional.ofNullable(requirePlugin().getPlayerProfiles().get(uniqueId)); + } + + private static List copyStrings(Iterable src) { + if (src == null) { + return List.of(); + } + List 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]+", " "); + } +} diff --git a/src/main/java/com/gigazelensky/antispoof/api/ApiLifecycle.java b/src/main/java/com/gigazelensky/antispoof/api/ApiLifecycle.java new file mode 100644 index 0000000..ca21832 --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/api/ApiLifecycle.java @@ -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(); + } +} diff --git a/src/main/java/com/gigazelensky/antispoof/api/IdentitySnapshot.java b/src/main/java/com/gigazelensky/antispoof/api/IdentitySnapshot.java new file mode 100644 index 0000000..87980a9 --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/api/IdentitySnapshot.java @@ -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 allAccounts, + List 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(); + } +} diff --git a/src/main/java/com/gigazelensky/antispoof/api/PlayerSnapshot.java b/src/main/java/com/gigazelensky/antispoof/api/PlayerSnapshot.java new file mode 100644 index 0000000..25ed86e --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/api/PlayerSnapshot.java @@ -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 channels, + List filteredChannels, + List detectedMods, + List violations, + ProxySnapshot proxy, + boolean alreadyPunished, + Instant joinTime +) { +} diff --git a/src/main/java/com/gigazelensky/antispoof/api/ProxySnapshot.java b/src/main/java/com/gigazelensky/antispoof/api/ProxySnapshot.java new file mode 100644 index 0000000..a88da90 --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/api/ProxySnapshot.java @@ -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 recentDiffs, + List recentPings, + List 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); + } +} diff --git a/src/main/java/com/gigazelensky/antispoof/api/events/AntiSpoofPrePunishmentEvent.java b/src/main/java/com/gigazelensky/antispoof/api/events/AntiSpoofPrePunishmentEvent.java new file mode 100644 index 0000000..3c35ef5 --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/api/events/AntiSpoofPrePunishmentEvent.java @@ -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; + } +} diff --git a/src/main/java/com/gigazelensky/antispoof/api/events/AntiSpoofViolationEvent.java b/src/main/java/com/gigazelensky/antispoof/api/events/AntiSpoofViolationEvent.java new file mode 100644 index 0000000..281159b --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/api/events/AntiSpoofViolationEvent.java @@ -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 getBrand() { + return Optional.ofNullable(brand); + } + + public Optional getSnapshot() { + return Optional.ofNullable(snapshot); + } + + @Override + public @NotNull HandlerList getHandlers() { + return HANDLERS; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } +} diff --git a/src/main/java/com/gigazelensky/antispoof/api/events/IdentityAnomalyEvent.java b/src/main/java/com/gigazelensky/antispoof/api/events/IdentityAnomalyEvent.java new file mode 100644 index 0000000..64ab6b5 --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/api/events/IdentityAnomalyEvent.java @@ -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 context; + + public IdentityAnomalyEvent( + Player player, + IdentityAnomalyType type, + String description, + Map 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 getContext() { + return context; + } +} diff --git a/src/main/java/com/gigazelensky/antispoof/api/events/IdentityAnomalyType.java b/src/main/java/com/gigazelensky/antispoof/api/events/IdentityAnomalyType.java new file mode 100644 index 0000000..9db9f58 --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/api/events/IdentityAnomalyType.java @@ -0,0 +1,7 @@ +package com.gigazelensky.antispoof.api.events; + +public enum IdentityAnomalyType { + HIDER_PACK_REJECTED, + PROBE_COUNT_MISMATCH, + RESOURCE_PACK_SPOOF +} diff --git a/src/main/java/com/gigazelensky/antispoof/api/events/PunishmentTier.java b/src/main/java/com/gigazelensky/antispoof/api/events/PunishmentTier.java new file mode 100644 index 0000000..77fdc68 --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/api/events/PunishmentTier.java @@ -0,0 +1,18 @@ +package com.gigazelensky.antispoof.api.events; + +import java.util.List; +import java.util.Objects; + +public record PunishmentTier( + String violationType, + List 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; + } +} diff --git a/src/main/java/com/gigazelensky/antispoof/command/AntiSpoofCommand.java b/src/main/java/com/gigazelensky/antispoof/command/AntiSpoofCommand.java new file mode 100644 index 0000000..4655a9a --- /dev/null +++ b/src/main/java/com/gigazelensky/antispoof/command/AntiSpoofCommand.java @@ -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 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 ", "Show player's plugin channels"), + new SubcommandHelp("brand ", "Show player's client brand"), + new SubcommandHelp("host ", "Show the hostname:port used by a player"), + new SubcommandHelp("os ", "Show the player's detected OS"), + new SubcommandHelp("mods ", "Show detected mods for a player"), + new SubcommandHelp("translate ", "Send a translate test key"), + new SubcommandHelp("keybind ", "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