November Recode 2.0 AntiBot module 1 files, 172 lines

November Recode 2.0 AntiBot: Full Source Analysis

November Recode 2.0's AntiBot module is a spawn-and-tab-list bot filter with three modes: WATCHDOG, TAB_TICKS and NPC.

feature/module/impl/combat/AntiBotModule.java · GitHub source ↗

Published 2026-08-12 · Updated 2026-08-12

Analysis

Overview

November Recode 2.0's AntiBot module is a spawn-and-tab-list bot filter with three modes: WATCHDOG, TAB_TICKS and NPC. It keeps a concurrent set of flagged entity ids, rebuilt from the player entity list on every walking update, and exposes a public bot(int) predicate that the KillAura module calls from its validTarget filter. WATCHDOG flags invisible players missing from the tab list and then picks one bot within 10 blocks vertically to watch, with a packet listener that reacts to its destroy or spawn; TAB_TICKS flags players older than a configured age that never appeared in the tab list; NPC flags names carrying CIT-, [NPC] or color-code markers plus players missing from the tab list.

Architecture

The module declares a Mode setting with WATCHDOG, TAB_TICKS and NPC values, plus a tabTicks number setting and a noTab boolean that are only visible for their modes. bots is a ConcurrentSet of entity ids, aboveEntityId and aboveDespawn track the watched bot in WATCHDOG mode, and disable() clears all three. The update listener skips the first five ticks after the player spawns, then rebuilds the set from mc.theWorld.playerEntities, and the packetIn listener handles S13PacketDestroyEntities and S0CPacketSpawnPlayer, both gated to WATCHDOG mode. The tabList helper scans the send queue's player info map for a matching game profile name, and bot(int) is the query the combat module calls.

Bot detection heuristics

WATCHDOG flags every invisible player that is not in the tab list, then scans the flagged set for the first entity within 10 blocks vertically of the local player, stores its id in aboveEntityId and prints a chat message naming it. The packet listener then reacts to that specific id: an S13 destroy prints 'was removed from the world. Staff?' and clears aboveEntityId, while an S0C spawn adds the new entity id to bots when aboveDespawn is set. aboveDespawn is never assigned true anywhere in the class, so the spawn branch is unreachable dead code, and the 'todo i have no clue' comment marks the mode as unfinished.

TAB_TICKS flags any player whose ticksExisted exceeds the tabTicks setting (default 50) while the tab list never contained their name, which targets bots that are spawned server-side and never registered as players. NPC mode flags names starting with CIT-, containing [NPC], or containing a section-sign color code, plus any player missing from the tab list when noTab is on, which covers NPC plugins and renamed entities. All three modes share the tabList scan, so a player that appears in the tab list under the same name is always treated as real.

Interaction with killaura targeting

KillAuraModule.validTarget fetches the AntiBotModule instance from the November module registry and rejects any entity whose id is in the bot set while the module is toggled on. The check runs before the range and line-of-sight tests, so a flagged entity is removed from the candidate stream entirely and never influences the sort comparator. Because the bot set is keyed by entity id and rebuilt every walking tick, an entity that stops matching its mode's heuristic, for example by appearing in the tab list, is attackable on the next tick. The WATCHDOG autoblock interaction is separate: the killaura's own WATCHDOG block mode cancels C02 attacks during hurt time, while this module only removes candidates.

source AntiBotModule.java (module logic)

AntiBotModule.java172 lines · JavaOriginal ↗
1
/* November.lol © 2023 */
2
package lol.november.feature.module.impl.combat;
3
4
import io.netty.util.internal.ConcurrentSet;
5
import java.util.Set;
6
import lol.november.feature.module.Category;
7
import lol.november.feature.module.Module;
8
import lol.november.feature.module.Register;
9
import lol.november.feature.setting.Setting;
10
import lol.november.listener.bus.Listener;
11
import lol.november.listener.bus.Subscribe;
12
import lol.november.listener.event.net.EventPacket;
13
import lol.november.listener.event.player.EventUpdate;
14
import lol.november.utility.chat.Printer;
15
import net.minecraft.client.network.NetworkPlayerInfo;
16
import net.minecraft.entity.Entity;
17
import net.minecraft.entity.player.EntityPlayer;
18
import net.minecraft.network.play.server.S0CPacketSpawnPlayer;
19
import net.minecraft.network.play.server.S13PacketDestroyEntities;
20
21
/**
22
 * @author Gavin
23
 * @since 2.0.0
24
 */
25
@Register(
26
  name = "AntiBot",
27
  description = "Prevents you from attacking bots",
28
  category = Category.COMBAT
29
)
30
public class AntiBotModule extends Module {
31
32
  private final Setting<Mode> mode = new Setting<>("Mode", Mode.WATCHDOG);
33
34
  private final Setting<Integer> tabTicks = new Setting<>(
35
    () -> mode.getValue() == Mode.TAB_TICKS,
36
    "Tab Ticks",
37
    50,
38
    1,
39
    0,
40
    500
41
  );
42
  private final Setting<Boolean> noTab = new Setting<>(
43
    () -> mode.getValue() == Mode.NPC,
44
    "No Tab List",
45
    true
46
  );
47
48
  private final Set<Integer> bots = new ConcurrentSet<>();
49
  private int aboveEntityId = -1;
50
  private boolean aboveDespawn;
51
52
  @Override
53
  public void disable() {
54
    super.disable();
55
    bots.clear();
56
    aboveEntityId = -1;
57
    aboveDespawn = false;
58
  }
59
60
  @Subscribe
61
  private final Listener<EventUpdate> update = event -> {
62
    if (mc.thePlayer.ticksExisted < 5) {
63
      bots.clear();
64
65
      if (mode.getValue() == Mode.WATCHDOG) {
66
        aboveEntityId = -1;
67
        aboveDespawn = false;
68
      }
69
70
      return;
71
    }
72
73
    switch (mode.getValue()) {
74
      case WATCHDOG -> {
75
        // todo i have no clue
76
77
        for (EntityPlayer player : mc.theWorld.playerEntities) {
78
          if (player == null || player.equals(mc.thePlayer)) continue;
79
80
          if (!tabList(player) && player.isInvisible()) {
81
            bots.add(player.getEntityId());
82
          }
83
        }
84
85
        if (aboveEntityId != -1) return;
86
        for (int bot : bots) {
87
          Entity entity = mc.theWorld.getEntityByID(bot);
88
          if (!(entity instanceof EntityPlayer)) {
89
            bots.remove(bot);
90
            continue;
91
          }
92
93
          if (Math.abs(entity.posY - mc.thePlayer.posY) <= 10.0) {
94
            aboveEntityId = entity.getEntityId();
95
            Printer.print(
96
              "Detected bot above you: " +
97
              aboveEntityId +
98
              " (" +
99
              entity.getName() +
100
              ")"
101
            );
102
            break;
103
          }
104
        }
105
      }
106
      case TAB_TICKS -> {
107
        for (EntityPlayer player : mc.theWorld.playerEntities) {
108
          if (player == null || player.equals(mc.thePlayer)) continue;
109
110
          if (
111
            player.ticksExisted > tabTicks.getValue() && !tabList(player)
112
          ) bots.add(player.getEntityId());
113
        }
114
      }
115
      case NPC -> {
116
        for (EntityPlayer player : mc.theWorld.playerEntities) {
117
          if (player == null || player.equals(mc.thePlayer)) continue;
118
          String name = player.getGameProfile().getName();
119
120
          if (
121
            name.startsWith("CIT-") ||
122
            name.contains("[NPC]") ||
123
            name.contains("\u00A7") ||
124
            (!tabList(player) && noTab.getValue())
125
          ) bots.add(player.getEntityId());
126
        }
127
      }
128
    }
129
  };
130
131
  @Subscribe
132
  private final Listener<EventPacket.In> packetIn = event -> {
133
    if (mode.getValue() == Mode.WATCHDOG) {
134
      if (event.get() instanceof S13PacketDestroyEntities packet) {
135
        for (int entityId : packet.getEntityIDs()) {
136
          if (entityId == aboveEntityId) {
137
            Printer.print(entityId + " was removed from the world. Staff?");
138
            aboveEntityId = -1;
139
          }
140
        }
141
      } else if (event.get() instanceof S0CPacketSpawnPlayer packet) {
142
        if (!aboveDespawn) return;
143
144
        bots.add(packet.getEntityID());
145
        Printer.print("Suspicious entity spawn: " + packet.getEntityID());
146
      }
147
    }
148
  };
149
150
  private boolean tabList(EntityPlayer player) {
151
    for (NetworkPlayerInfo info : mc.thePlayer.sendQueue.getPlayerInfoMap()) {
152
      if (
153
        info
154
          .getGameProfile()
155
          .getName()
156
          .equals(player.getGameProfile().getName())
157
      ) return true;
158
    }
159
160
    return false;
161
  }
162
163
  public boolean bot(int entityId) {
164
    return bots.contains(entityId);
165
  }
166
167
  private enum Mode {
168
    TAB_TICKS,
169
    NPC,
170
    WATCHDOG,
171
  }
172
}

What this file does

The entire module is this one class. The Mode setting and the tabTicks and noTab settings define the three filter modes, the update listener rebuilds the bots set from mc.theWorld.playerEntities every walking tick after a five-tick grace period, and the packetIn listener handles the WATCHDOG-mode entity lifecycle events. The tabList helper compares game profile names against the send queue's player info map, and the public bot(int) predicate is the single query point that KillAuraModule calls from validTarget.

The dead code is part of the analysis: aboveDespawn is declared, cleared and tested, but never set to true, so the S0CPacketSpawnPlayer branch that would add a spawned entity id to bots can never execute. The WATCHDOG mode therefore only ever flags invisible entities missing from the tab list and reports the one it watches; the S13 branch still works, printing a staff warning when the watched entity is destroyed. The Printer import is used only for those two chat messages.

anticheat Countering Checks

The anticheat code that detects or counters the techniques this module uses. Full source, with the detection mechanism explained below each box.

anticheat Grim PacketEntityReplication (spawn mirroring)

PacketEntityReplication.java627 lines · Java
1
package ac.grim.grimac.events.packets;
2
3
import ac.grim.grimac.GrimAPI;
4
import ac.grim.grimac.api.config.ConfigManager;
5
import ac.grim.grimac.checks.Check;
6
import ac.grim.grimac.checks.type.PacketReceiveListener;
7
import ac.grim.grimac.checks.type.PacketSendListener;
8
import ac.grim.grimac.player.GrimPlayer;
9
import ac.grim.grimac.utils.anticheat.LogUtil;
10
import ac.grim.grimac.utils.data.SprintingState;
11
import ac.grim.grimac.utils.data.TrackerData;
12
import ac.grim.grimac.utils.data.packetentity.DashableEntity;
13
import ac.grim.grimac.utils.data.packetentity.PacketEntity;
14
import ac.grim.grimac.utils.data.packetentity.PacketEntityHook;
15
import ac.grim.grimac.utils.data.packetentity.PacketEntityTrackXRot;
16
import ac.grim.grimac.utils.enums.Pose;
17
import ac.grim.grimac.utils.nmsutil.EntityMetadataPoseUtil;
18
import ac.grim.grimac.utils.viaversion.ViaVersionUtil;
19
import com.github.retrooper.packetevents.PacketEvents;
20
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
21
import com.github.retrooper.packetevents.event.PacketSendEvent;
22
import com.github.retrooper.packetevents.manager.server.ServerVersion;
23
import com.github.retrooper.packetevents.protocol.entity.EntityPositionData;
24
import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
25
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
26
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
27
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
28
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
29
import com.github.retrooper.packetevents.protocol.player.InteractionHand;
30
import com.github.retrooper.packetevents.protocol.player.UserProfile;
31
import com.github.retrooper.packetevents.protocol.potion.PotionType;
32
import com.github.retrooper.packetevents.util.Vector3d;
33
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerAttachEntity;
34
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities;
35
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEffect;
36
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityEquipment;
37
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
38
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityPositionSync;
39
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMove;
40
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRelativeMoveAndRotation;
41
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityRotation;
42
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityStatus;
43
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityTeleport;
44
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo;
45
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoRemove;
46
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoUpdate;
47
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerRemoveEntityEffect;
48
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetPassengers;
49
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetSlot;
50
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity;
51
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnLivingEntity;
52
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPainting;
53
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPlayer;
54
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateAttributes;
55
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowItems;
56
import org.jetbrains.annotations.NotNull;
57
58
import java.util.ArrayList;
59
import java.util.List;
60
import java.util.UUID;
61
import java.util.concurrent.atomic.AtomicBoolean;
62
63
public class PacketEntityReplication extends Check implements PacketReceiveListener, PacketSendListener {
64
65
    private final AtomicBoolean hasSentPreWavePacket = new AtomicBoolean(true);
66
67
    // Let's imagine the player is on a boat.
68
    // The player breaks this boat
69
    // If we were to despawn the boat without an extra transaction, then the boat would disappear before
70
    // it disappeared on the client side, creating a ghost boat to flag checks with
71
    //
72
    // If we were to despawn the tick after, spawning must occur the transaction before to stop the same exact
73
    // problem with ghost boats in reverse.
74
    //
75
    // Therefore, we despawn the transaction after, and spawn the tick before.
76
    //
77
    // If we despawn then spawn an entity in the same transaction, then this solution would despawn the new entity
78
    // instead of the old entity, so we wouldn't see the boat at all
79
    //
80
    // Therefore, if the server sends a despawn and then a spawn in the same transaction for the same entity,
81
    // We should simply add a transaction (which will clear this list!)
82
    //
83
    // Another valid solution is to simply spam more transactions, but let's not waste bandwidth.
84
    private final List<Integer> despawnedEntitiesThisTransaction = new ArrayList<>();
85
86
    // Maximum ping when a firework boost is removed from the player.
87
    private int maxFireworkBoostPing = 1000;
88
89
    public PacketEntityReplication(GrimPlayer player) {
90
        super(player);
91
    }
92
93
    @Override
94
    public void onPacketReceive(PacketReceiveEvent event) {
95
        // Teleports don't interpolate, duplicate 1.17 packets don't interpolate
96
        if (!isTickPacket(event.getPacketType())) return;
97
        player.compensatedEntities.entitiesRemovedThisTick.clear();
98
        boolean isTickingReliably = player.isTickingReliablyFor(3);
99
100
        PacketEntity playerVehicle = player.compensatedEntities.self.getRiding();
101
        for (PacketEntity entity : player.compensatedEntities.entityMap.values()) {
102
            if (entity == playerVehicle && !player.vehicleData.lastDummy) {
103
                // The player has this as their vehicle, so they aren't interpolating it.
104
                // And it isn't a dummy position
105
                entity.setPositionRaw(player, entity.getPossibleLocationBoxes());
106
            } else {
107
                entity.onMovement(isTickingReliably);
108
            }
109
        }
110
111
        if (player.vehicleData.camelSprintingState == SprintingState.STOPPING) {
112
            player.vehicleData.camelSprintingState = SprintingState.STOPPED;
113
        } else if (player.vehicleData.camelSprintingState == SprintingState.STOPPED && player.isSprinting) { // For sprint desyncs
114
            player.vehicleData.camelSprintingState = SprintingState.STARTED;
115
        }
116
    }
117
118
    @Override
119
    public void onPacketSend(PacketSendEvent event) {
120
        // ensure grim is the one that sent the transaction
121
        if ((event.getPacketType() == PacketType.Play.Server.PING || event.getPacketType() == PacketType.Play.Server.WINDOW_CONFIRMATION) && player.packetStateData.lastServerTransWasValid) {
122
            despawnedEntitiesThisTransaction.clear();
123
        } else if (event.getPacketType() == PacketType.Play.Server.SPAWN_LIVING_ENTITY) {
124
            WrapperPlayServerSpawnLivingEntity packetOutEntity = new WrapperPlayServerSpawnLivingEntity(event);
125
            addEntity(packetOutEntity.getEntityId(), packetOutEntity.getEntityUUID(), packetOutEntity.getEntityType(), packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), packetOutEntity.getEntityMetadata(), 0);
126
        } else if (event.getPacketType() == PacketType.Play.Server.SPAWN_ENTITY) {
127
            WrapperPlayServerSpawnEntity packetOutEntity = new WrapperPlayServerSpawnEntity(event);
128
            addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID().orElse(null), packetOutEntity.getEntityType(), packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), null, packetOutEntity.getData());
129
        } else if (event.getPacketType() == PacketType.Play.Server.SPAWN_PLAYER) {
130
            WrapperPlayServerSpawnPlayer packetOutEntity = new WrapperPlayServerSpawnPlayer(event);
131
            addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID(), EntityTypes.PLAYER, packetOutEntity.getPosition(), packetOutEntity.getYaw(), packetOutEntity.getPitch(), packetOutEntity.getEntityMetadata(), 0);
132
        } else if (event.getPacketType() == PacketType.Play.Server.SPAWN_PAINTING) {
133
            WrapperPlayServerSpawnPainting packetOutEntity = new WrapperPlayServerSpawnPainting(event);
134
            addEntity(packetOutEntity.getEntityId(), packetOutEntity.getUUID(), EntityTypes.PAINTING, packetOutEntity.getPosition().toVector3d(), 0, 0f, null, packetOutEntity.getDirection().getHorizontalIndex());
135
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_RELATIVE_MOVE) {
136
            WrapperPlayServerEntityRelativeMove move = new WrapperPlayServerEntityRelativeMove(event);
137
            handleMoveEntity(event, move.getEntityId(), move.getDeltaX(), move.getDeltaY(), move.getDeltaZ(), null, null, true, true);
138
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_RELATIVE_MOVE_AND_ROTATION) {
139
            WrapperPlayServerEntityRelativeMoveAndRotation move = new WrapperPlayServerEntityRelativeMoveAndRotation(event);
140
            handleMoveEntity(event, move.getEntityId(), move.getDeltaX(), move.getDeltaY(), move.getDeltaZ(), move.getYaw() * 0.7111111F, move.getPitch() * 0.7111111F, true, true);
141
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_TELEPORT) {
142
            WrapperPlayServerEntityTeleport move = new WrapperPlayServerEntityTeleport(event);
143
            Vector3d pos = move.getPosition();
144
            handleMoveEntity(event, move.getEntityId(), pos.getX(), pos.getY(), pos.getZ(), move.getYaw(), move.getPitch(), false, true);
145
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_POSITION_SYNC) {
146
            // ENTITY_TELEPORT but without relative flags
147
            WrapperPlayServerEntityPositionSync move = new WrapperPlayServerEntityPositionSync(event);
148
            final EntityPositionData values = move.getValues();
149
            final Vector3d pos = values.getPosition();
150
            // TODO this isn't technically correct
151
            // If the position sync is to a pos > 4096 from the entity pos, client does some special stuff without interpolation
152
            handleMoveEntity(event, move.getId(), pos.getX(), pos.getY(), pos.getZ(), values.getYaw(), values.getPitch(), false, true);
153
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_ROTATION) { // Affects interpolation
154
            WrapperPlayServerEntityRotation move = new WrapperPlayServerEntityRotation(event);
155
            handleMoveEntity(event, move.getEntityId(), 0, 0, 0, move.getYaw() * 0.7111111F, move.getPitch() * 0.7111111F, true, false);
156
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_METADATA) {
157
            WrapperPlayServerEntityMetadata entityMetadata = new WrapperPlayServerEntityMetadata(event);
158
            schedulePoseTransition(entityMetadata, event);
159
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.compensatedEntities.updateEntityMetadata(entityMetadata.getEntityId(), entityMetadata.getEntityMetadata()));
160
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_EQUIPMENT) {
161
            WrapperPlayServerEntityEquipment equipment = new WrapperPlayServerEntityEquipment(event);
162
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.compensatedEntities.updateEntityEquipment(equipment.getEntityId(), equipment.getEquipment()));
163
        }
164
165
        // 1.19.3+
166
        else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO_UPDATE) {
167
            WrapperPlayServerPlayerInfoUpdate info = new WrapperPlayServerPlayerInfoUpdate(event);
168
            if (info.getActions().contains(WrapperPlayServerPlayerInfoUpdate.Action.ADD_PLAYER)) {
169
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
170
                    for (WrapperPlayServerPlayerInfoUpdate.PlayerInfo entry : info.getEntries()) {
171
                        final UserProfile gameProfile = entry.getGameProfile();
172
                        final UUID uuid = gameProfile.getUUID();
173
                        player.compensatedEntities.profiles.put(uuid, gameProfile);
174
                    }
175
                });
176
            }
177
        } else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO_REMOVE) {
178
            WrapperPlayServerPlayerInfoRemove remove = new WrapperPlayServerPlayerInfoRemove(event);
179
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> remove.getProfileIds().forEach(player.compensatedEntities.profiles::remove));
180
        } else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO) {
181
            WrapperPlayServerPlayerInfo info = new WrapperPlayServerPlayerInfo(event);
182
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
183
                if (info.getAction() == WrapperPlayServerPlayerInfo.Action.ADD_PLAYER) {
184
                    for (WrapperPlayServerPlayerInfo.PlayerData entry : info.getPlayerDataList()) {
185
                        final UserProfile gameProfile = entry.getUserProfile();
186
                        final UUID uuid = gameProfile.getUUID();
187
                        player.compensatedEntities.profiles.put(uuid, gameProfile);
188
                    }
189
                } else if (info.getAction() == WrapperPlayServerPlayerInfo.Action.REMOVE_PLAYER) {
190
                    info.getPlayerDataList().forEach(profile -> player.compensatedEntities.profiles.remove(profile.getUserProfile().getUUID()));
191
                }
192
            });
193
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_EFFECT) {
194
            WrapperPlayServerEntityEffect effect = new WrapperPlayServerEntityEffect(event);
195
196
            PotionType type = effect.getPotionType();
197
198
            // ViaVersion tries faking levitation effects and fails badly lol, flagging the anticheat
199
            // Block other effects just in case ViaVersion gets any ideas
200
            //
201
            // Set to 24 so ViaVersion blocks it
202
            // 24 is the levitation effect
203
            if (player.getClientVersion().isOlderThan(ClientVersion.V_1_9) && ViaVersionUtil.isAvailable && type.getId(player.getClientVersion()) > 23) {
204
                event.setCancelled(true);
205
                return;
206
            }
207
208
            // ViaVersion dolphin's grace also messes us up, set it to a potion effect that doesn't exist on 1.12
209
            // Effect 31 is bad omen
210
            if (player.getClientVersion().isOlderThan(ClientVersion.V_1_13) && ViaVersionUtil.isAvailable && type.getId(player.getClientVersion()) == 30) {
211
                event.setCancelled(true);
212
                return;
213
            }
214
215
            if (isDirectlyAffectingPlayer(player, effect.getEntityId())) player.sendTransaction();
216
217
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
218
                PacketEntity entity = player.compensatedEntities.getEntity(effect.getEntityId());
219
                if (entity == null) return;
220
221
                entity.addPotionEffect(type, effect.getEffectAmplifier());
222
            });
223
        } else if (event.getPacketType() == PacketType.Play.Server.REMOVE_ENTITY_EFFECT) {
224
            WrapperPlayServerRemoveEntityEffect effect = new WrapperPlayServerRemoveEntityEffect(event);
225
226
            if (isDirectlyAffectingPlayer(player, effect.getEntityId())) player.sendTransaction();
227
228
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
229
                PacketEntity entity = player.compensatedEntities.getEntity(effect.getEntityId());
230
                if (entity == null) return;
231
232
                entity.removePotionEffect(effect.getPotionType());
233
            });
234
        } else if (event.getPacketType() == PacketType.Play.Server.UPDATE_ATTRIBUTES) {
235
            WrapperPlayServerUpdateAttributes attributes = new WrapperPlayServerUpdateAttributes(event);
236
237
            int entityID = attributes.getEntityId();
238
239
            // The attributes for this entity is active, currently
240
            if (isDirectlyAffectingPlayer(player, entityID)) player.sendTransaction();
241
242
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(),
243
                    () -> player.compensatedEntities.updateAttributes(entityID, attributes.getProperties()));
244
        } else if (event.getPacketType() == PacketType.Play.Server.ENTITY_STATUS) {
245
            WrapperPlayServerEntityStatus status = new WrapperPlayServerEntityStatus(event);
246
            // This hasn't changed from 1.7.2 to 1.17
247
            // Needed to exempt players on dead vehicles, as dead entities have strange physics.
248
            if (status.getStatus() == 3) {
249
                PacketEntity entity = player.compensatedEntities.getEntity(status.getEntityId());
250
251
                if (entity == null) return;
252
                entity.isDead = true;
253
            }
254
255
            if (status.getStatus() == 9) {
256
                if (status.getEntityId() != player.entityID) return;
257
258
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
259
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
260
            }
261
262
            if (status.getStatus() == 31) {
263
                PacketEntity hook = player.compensatedEntities.getEntity(status.getEntityId());
264
                if (!(hook instanceof PacketEntityHook hookEntity)) return;
265
266
                if (hookEntity.attached == player.entityID) {
267
                    player.sendTransaction();
268
                    // We don't transaction sandwich this, it's too rare to be a real problem.
269
                    player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.uncertaintyHandler.fishingRodPulls.add(hookEntity.owner));
270
                }
271
            }
272
273
            if (status.getStatus() >= 24 && status.getStatus() <= 28 && status.getEntityId() == player.entityID) {
274
                player.compensatedEntities.self.opLevel = status.getStatus() - 24;
275
            }
276
        } else if (event.getPacketType() == PacketType.Play.Server.SET_SLOT) {
277
            WrapperPlayServerSetSlot slot = new WrapperPlayServerSetSlot(event);
278
279
            if (slot.getWindowId() == 0) {
280
                Runnable task = () -> {
281
                    if (slot.getSlot() - 36 == player.packetStateData.lastSlotSelected && (
282
                            !player.inventory.getHeldItem().is(slot.getItem().getType()) || player.getClientVersion().isOlderThanOrEquals(ClientVersion.V_1_8)
283
                    ) || slot.getSlot() == 45 && !player.inventory.getOffHand().is(slot.getItem().getType())) {
284
                        InteractionHand hand = slot.getSlot() == 45 ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND;
285
                        if (hand == player.packetStateData.itemInUseHand) {
286
                            player.packetStateData.setSlowedByUsingItem(false);
287
                        }
288
289
                        if (player.isResetItemUsageOnItemUpdate() && hand == GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer)) {
290
                            GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
291
                        }
292
                    }
293
                };
294
295
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), task);
296
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, task);
297
            }
298
        } else if (event.getPacketType() == PacketType.Play.Server.WINDOW_ITEMS) {
299
            WrapperPlayServerWindowItems items = new WrapperPlayServerWindowItems(event);
300
301
            if (items.getWindowId() == 0) { // Player inventory
302
                Runnable task = () -> {
303
                    if (player.getClientVersion().isOlderThanOrEquals(ClientVersion.V_1_8)) {
304
                        player.packetStateData.setSlowedByUsingItem(false);
305
                        if (player.isResetItemUsageOnItemUpdate()) {
306
                            GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
307
                        }
308
                    } else {
309
                        if (items.getItems().size() > 45 && !player.inventory.getOffHand().is(items.getItems().get(45).getType())) {
310
                            if (player.packetStateData.itemInUseHand == InteractionHand.OFF_HAND) {
311
                                player.packetStateData.setSlowedByUsingItem(false);
312
                            }
313
314
                            if (player.isResetItemUsageOnItemUpdate() && GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer) == InteractionHand.OFF_HAND) {
315
                                GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
316
                            }
317
                        }
318
319
                        if (!player.inventory.getHeldItem().is(items.getItems().get(player.packetStateData.lastSlotSelected + 36).getType())) {
320
                            if (player.packetStateData.itemInUseHand == InteractionHand.MAIN_HAND) {
321
                                player.packetStateData.setSlowedByUsingItem(false);
322
                            }
323
324
                            if (player.isResetItemUsageOnItemUpdate() && GrimAPI.INSTANCE.getItemResetHandler().getItemUsageHand(player.platformPlayer) == InteractionHand.MAIN_HAND) {
325
                                GrimAPI.INSTANCE.getItemResetHandler().resetItemUsage(player.platformPlayer);
326
                            }
327
                        }
328
                    }
329
                };
330
331
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), task);
332
                player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, task);
333
            }
334
        }
335
336
        // 1.8 clients fail to send the RELEASE_USE_ITEM packet when a window is opened client sided while using an item
337
        else if (event.getPacketType() == PacketType.Play.Server.OPEN_WINDOW) {
338
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
339
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
340
        } else if (event.getPacketType() == PacketType.Play.Server.OPEN_HORSE_WINDOW) {
341
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> player.packetStateData.setSlowedByUsingItem(false));
342
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.packetStateData.setSlowedByUsingItem(false));
343
        } else if (event.getPacketType() == PacketType.Play.Server.SET_PASSENGERS) {
344
            WrapperPlayServerSetPassengers mount = new WrapperPlayServerSetPassengers(event);
345
346
            int vehicleID = mount.getEntityId();
347
            int[] passengers = mount.getPassengers();
348
349
            handleMountVehicle(event, vehicleID, passengers);
350
        } else if (event.getPacketType() == PacketType.Play.Server.ATTACH_ENTITY) {
351
            WrapperPlayServerAttachEntity attach = new WrapperPlayServerAttachEntity(event);
352
353
            // This packet was replaced by the mount packet on 1.9+ servers - to support multiple passengers on one vehicle
354
            if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9))
355
                return;
356
357
            // If this is mounting rather than leashing
358
            if (!attach.isLeash()) {
359
                // Alright, let's convert this to the 1.9+ format to make it easier for grim
360
                int vehicleID = attach.getHoldingId();
361
                int attachID = attach.getAttachedId();
362
                TrackerData trackerData = player.compensatedEntities.getTrackedEntity(attachID);
363
364
                if (trackerData != null) {
365
                    // 1.8 sends a vehicle ID of -1 to dismount the entity from its vehicle
366
                    // This is opposite of the 1.9+ format, which sends the vehicle ID and then an empty array.
367
                    if (vehicleID == -1) { // Dismounting
368
                        vehicleID = trackerData.getLegacyPointEightMountedUpon();
369
                        handleMountVehicle(event, vehicleID, new int[]{}); // The vehicle is empty
370
                    } else { // Mounting
371
                        trackerData.setLegacyPointEightMountedUpon(vehicleID);
372
                        handleMountVehicle(event, vehicleID, new int[]{attachID});
373
                    }
374
                } else {
375
                    // I don't think we can recover from this... warn and move on as this shouldn't happen.
376
                    LogUtil.warn("Server sent an invalid attach entity packet for entity " + attach.getHoldingId() + " with passenger " + attach.getAttachedId() + "! The client ignores this.");
377
                }
378
            }
379
        } else if (event.getPacketType() == PacketType.Play.Server.DESTROY_ENTITIES) {
380
            WrapperPlayServerDestroyEntities destroy = new WrapperPlayServerDestroyEntities(event);
381
382
            int[] destroyEntityIds = destroy.getEntityIds();
383
384
            for (int entityID : destroyEntityIds) {
385
                despawnedEntitiesThisTransaction.add(entityID);
386
                player.compensatedEntities.serverPositionsMap.remove(entityID);
387
                // Remove the tracked vehicle (handling tracking knockback) if despawned
388
                if (player.compensatedEntities.serverPlayerVehicle != null && player.compensatedEntities.serverPlayerVehicle == entityID) {
389
                    player.compensatedEntities.serverPlayerVehicle = null;
390
                }
391
            }
392
393
            final int destroyTransaction = player.lastTransactionSent.get() + 1;
394
            player.latencyUtils.addRealTimeTask(destroyTransaction, () -> {
395
                for (int entityId : destroyEntityIds) {
396
                    player.compensatedEntities.removeEntity(entityId);
397
                    player.dashableEntities.removeEntity(entityId);
398
                    player.fireworks.removeFirework(entityId);
399
                    player.compensatedEntities.entitiesRemovedThisTick.add(entityId);
400
                }
401
            });
402
403
            // Don't let the player freeze transactions to keep the firework boost velocity + uncertainty
404
            // Also generally prevents people with high ping gaining too high an advantage in firework use
405
            if (maxFireworkBoostPing > 0) {
406
                player.runNettyTaskInMs(() -> {
407
                    if (player.lastTransactionReceived.get() >= destroyTransaction) return;
408
                    for (int entityID : destroyEntityIds) {
409
                        // If the player has a firework boosting them, setback
410
                        if (player.fireworks.hasFirework(entityID)) {
411
                            player.getSetbackTeleportUtil().executeViolationSetback();
412
                            break;
413
                        }
414
                    }
415
                }, maxFireworkBoostPing);
416
            }
417
        }
418
    }
419
420
    private void handleMountVehicle(PacketSendEvent event, int vehicleID, int[] passengers) {
421
        boolean wasInVehicle = player.compensatedEntities.serverPlayerVehicle != null && player.compensatedEntities.serverPlayerVehicle == vehicleID;
422
        boolean inThisVehicle = false;
423
424
        for (int passenger : passengers) {
425
            inThisVehicle = passenger == player.entityID;
426
            if (inThisVehicle) break;
427
        }
428
429
        if (inThisVehicle && !wasInVehicle) {
430
            player.handleMountVehicle(vehicleID);
431
        }
432
433
        if (!inThisVehicle && wasInVehicle) {
434
            player.handleDismountVehicle(event);
435
        }
436
        // Better lag compensation if we were affected by this
437
        if (wasInVehicle || inThisVehicle) {
438
            player.sendTransaction();
439
        }
440
        player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
441
            PacketEntity vehicle = player.compensatedEntities.getEntity(vehicleID);
442
443
            // Vanilla likes sending null vehicles, so we must ignore those like the client ignores them
444
            if (vehicle == null) return;
445
446
            // Eject existing passengers for this vehicle
447
            for (PacketEntity passenger : new ArrayList<>(vehicle.passengers)) {
448
                passenger.eject();
449
            }
450
451
            // Add the entities as vehicles
452
            for (int entityID : passengers) {
453
                PacketEntity passenger = player.compensatedEntities.getEntity(entityID);
454
                if (passenger == null) continue;
455
                passenger.mount(vehicle);
456
            }
457
        });
458
    }
459
460
    private void handleMoveEntity(PacketSendEvent event, int entityId, double deltaX, double deltaY, double deltaZ, Float yaw, Float pitch, boolean isRelative, boolean hasPos) {
461
        TrackerData data = player.compensatedEntities.getTrackedEntity(entityId);
462
463
        final boolean didNotSendPreWave = hasSentPreWavePacket.compareAndSet(false, true);
464
        if (didNotSendPreWave) player.sendTransaction();
465
466
        if (data != null) {
467
            // Update the tracked server's entity position
468
            if (isRelative) {
469
                // There is a bug where vehicles may start flying due to mojang setting packet position on the client
470
                // (Works at 0 ping but causes funny bugs at any higher ping)
471
                // As we don't want vehicles to fly, we need to replace it with a teleport if it is player vehicle
472
                //
473
                // Don't bother with client controlled vehicles though
474
                boolean vanillaVehicleFlight = player.compensatedEntities.serverPlayerVehicle != null
475
                        && player.compensatedEntities.serverPlayerVehicle == entityId
476
                        && player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_9)
477
                        // TODO: https://discord.com/channels/721686193061888071/721686193515003966/1310659538831020123
478
                        // Why does the server now send an entity rel move packet matching the player's vehicle movement every time?
479
                        && PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_21_2)
480
                        && PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9);
481
482
                // ViaVersion sends two relative packets when moving more than 4 blocks
483
                // This is broken and causes the client to interpolate like (0, 4) and (1, 3) instead of (1, 7)
484
                // This causes impossible hits, so grim must replace this with a teleport entity packet
485
                // Not ideal, but neither is 1.8 players on a 1.9+ server.
486
                if (vanillaVehicleFlight ||
487
                        ((Math.abs(deltaX) >= 3.9375 || Math.abs(deltaY) >= 3.9375 || Math.abs(deltaZ) >= 3.9375) && player.getClientVersion().isOlderThan(ClientVersion.V_1_9) && PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_9))) {
488
                    player.user.writePacket(new WrapperPlayServerEntityTeleport(entityId, new Vector3d(data.getX() + deltaX, data.getY() + deltaY, data.getZ() + deltaZ), yaw == null ? data.getXRot() : yaw, pitch == null ? data.getYRot() : pitch, false));
489
                    event.setCancelled(true);
490
                    return;
491
                }
492
493
                data.setX(data.getX() + deltaX);
494
                data.setY(data.getY() + deltaY);
495
                data.setZ(data.getZ() + deltaZ);
496
            } else {
497
                data.setX(deltaX);
498
                data.setY(deltaY);
499
                data.setZ(deltaZ);
500
            }
501
            if (yaw != null) {
502
                data.setXRot(yaw);
503
                data.setYRot(pitch);
504
            }
505
506
            // We can't hang two relative moves on one transaction
507
            if (data.getLastTransactionHung() == player.lastTransactionSent.get()) {
508
                player.sendTransaction();
509
            }
510
            data.setLastTransactionHung(player.lastTransactionSent.get());
511
        }
512
513
        int lastTrans = player.lastTransactionSent.get();
514
515
        player.latencyUtils.addRealTimeTask(lastTrans, () -> {
516
            PacketEntity entity = player.compensatedEntities.getEntity(entityId);
517
            if (entity == null) return;
518
            if (entity instanceof PacketEntityTrackXRot xRotEntity && yaw != null) {
519
                xRotEntity.packetYaw = yaw;
520
                xRotEntity.steps = entity.isBoat ? 10 : 3;
521
            }
522
523
            entity.onFirstTransaction(isRelative, hasPos, deltaX, deltaY, deltaZ, yaw, pitch, player);
524
        });
525
526
        player.latencyUtils.addRealTimeTask(lastTrans + 1, () -> {
527
            PacketEntity entity = player.compensatedEntities.getEntity(entityId);
528
            if (entity == null) return;
529
            entity.onSecondTransaction();
530
        });
531
    }
532
533
    public void addEntity(int entityID, UUID uuid, EntityType type, Vector3d position, float xRot, float yRot, List<EntityData<?>> entityMetadata, int extraData) {
534
        if (despawnedEntitiesThisTransaction.contains(entityID)) {
535
            player.sendTransaction();
536
        }
537
538
        player.compensatedEntities.serverPositionsMap.put(entityID, new TrackerData(position.getX(), position.getY(), position.getZ(), xRot, yRot, type, player.lastTransactionSent.get()));
539
540
        player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
541
            PacketEntity entity = player.compensatedEntities.addEntity(entityID, uuid, type, position, xRot, extraData);
542
            if (entity instanceof DashableEntity dashable) {
543
                player.dashableEntities.addEntity(entityID, dashable);
544
            }
545
546
            if (entityMetadata != null) {
547
                if (EntityMetadataPoseUtil.usesPoseMetadata(entity) && player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_14)) {
548
                    Pose initialPose = EntityMetadataPoseUtil.getPoseFromMetadata(entityMetadata);
549
                    if (initialPose != null) {
550
                        entity.currentPose = initialPose;
551
                    }
552
                }
553
554
                player.compensatedEntities.updateEntityMetadata(entityID, entityMetadata);
555
            }
556
        });
557
    }
558
559
    private void schedulePoseTransition(WrapperPlayServerEntityMetadata entityMetadata, PacketSendEvent event) {
560
        if (player.getClientVersion().isOlderThan(ClientVersion.V_1_14)) return;
561
562
        int entityId = entityMetadata.getEntityId();
563
        if (entityId == player.entityID) return;
564
565
        Pose newPose = EntityMetadataPoseUtil.getPoseFromMetadata(entityMetadata.getEntityMetadata());
566
        if (newPose == null) return;
567
568
        boolean shouldTrackPoseTransition = false;
569
        PacketEntity entity = player.compensatedEntities.getEntity(entityId);
570
        if (entity != null) {
571
            shouldTrackPoseTransition = EntityMetadataPoseUtil.usesPoseMetadata(entity);
572
        } else {
573
            // If the client didn't respond to the spawn packet yet, we need to check if we should track the pose transition based on the entity type
574
            // is there a better way to do this?
575
            TrackerData trackedEntity = player.compensatedEntities.getTrackedEntity(entityId);
576
            if (trackedEntity != null) {
577
                shouldTrackPoseTransition = EntityMetadataPoseUtil.usesPoseMetadata(trackedEntity.getEntityType());
578
            }
579
        }
580
581
        if (!shouldTrackPoseTransition) return;
582
583
        player.sendTransaction();
584
        player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
585
            PacketEntity target = player.compensatedEntities.getEntity(entityId);
586
            if (target == null) {
587
                return;
588
            }
589
590
            target.beginPoseTransition(newPose);
591
        });
592
593
        event.getTasksAfterSend().add(() -> {
594
            player.sendTransaction();
595
            player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
596
                PacketEntity target = player.compensatedEntities.getEntity(entityId);
597
                if (target == null) {
598
                    return;
599
                }
600
601
                target.completePoseTransition(newPose);
602
            });
603
        });
604
    }
605
606
    private boolean isDirectlyAffectingPlayer(GrimPlayer player, int entityID) {
607
        // The attributes for this entity is active, currently
608
        return (player.compensatedEntities.serverPlayerVehicle == null && entityID == player.entityID) ||
609
                (player.compensatedEntities.serverPlayerVehicle != null && entityID == player.compensatedEntities.serverPlayerVehicle);
610
    }
611
612
    public void onEndOfTickEvent(boolean async, boolean flush) {
613
        // Only send a transaction at the end of the tick if we are tracking players
614
        player.sendTransaction(async);
615
        if (flush) player.user.flushPackets();
616
    }
617
618
    public void tickStartTick() {
619
        hasSentPreWavePacket.set(false);
620
    }
621
622
    @Override
623
    public void onReload(@NotNull ConfigManager config) {
624
        maxFireworkBoostPing = config.getIntElse("max-ping-firework-boost", 1000);
625
    }
626
627
}

How it counteracts this module

PacketEntityReplication is Grim's server-side mirror of everything the client knows about entities. Every outgoing spawn packet, including SPAWN_PLAYER for named players, is captured and added to compensatedEntities with its id, uuid, type, position, rotations and metadata, and the follow-up relative moves, teleports and rotations update the replicated boxes each tick. The replication is transaction-aware: despawning is deferred so the client never sees a ghost entity, and the boxes are interpolated through ReachInterpolationData for the reach checks.

This is the structural counter to the module's WATCHDOG heuristic, which guesses which S0CPacketSpawnPlayer spawns are bots by combining invisibility with tab-list absence. Grim does not guess: every spawn is a real entity with a replicated box, and the Reach and Hitboxes checks validate attacks against those boxes regardless of whether the client filtered the entity out of its aura target list. A bot that the client refuses to attack simply generates no C02, while a bot that slips through the filter is judged by geometry, not by the client's opinion of it.

The module's S13 handling also intersects with Grim's despawn tracking: when the watched entity is destroyed, Grim removes its replicated state in the same transaction flow, so there is no window where the client still holds the entity while the server does not.

anticheat NCP Fight NoSwing (arm swing accounting)

NoSwing.java65 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.fight;
16
17
import org.bukkit.entity.Player;
18
19
import fr.neatmonster.nocheatplus.checks.Check;
20
import fr.neatmonster.nocheatplus.checks.CheckType;
21
22
/**
23
 * We require that the player moves their arm between attacks, this is basically what gets checked here.
24
 */
25
public class NoSwing extends Check {
26
27
    /**
28
     * Instantiates a new no swing check.
29
     */
30
    public NoSwing() {
31
        super(CheckType.FIGHT_NOSWING);
32
    }
33
34
    /**
35
     * Checks a player.
36
     * 
37
     * @param player
38
     *            the player
39
     * @return true, if successful
40
     */
41
    public boolean check(final Player player, final FightData data, final FightConfig cc) {
42
        boolean cancel = false;
43
44
        if (data.exemptArmSwing) {
45
            data.exemptArmSwing = false;
46
        }
47
        // Did they swing his arm before?
48
        else if (++data.noSwingCount <= 1) {
49
            // Yes, reward them with reduction of their violation level.
50
            data.noSwingVL *= 0.9D;
51
        } 
52
        else {
53
            data.noSwingCount = 0;
54
            // No, increase their violation level.
55
            data.noSwingVL += 1D;
56
57
            // Execute whatever actions are associated with this check and the violation level and find out if we should
58
            // cancel the event.
59
            cancel = executeActions(player, data.noSwingVL, 1D, cc.noSwingActions).willCancel();
60
        }
61
62
        return cancel;
63
    } 
64
65
}

How it counteracts this module

NoSwing requires an arm swing between attacks. Each attack increments noSwingCount; the first increment is rewarded by shrinking noSwingVL by ten percent, and every subsequent consecutive no-swing attack resets the counter and raises noSwingVL by one, executing noSwingActions when the level crosses the configured threshold. A single swing resets the count, so the check tolerates dropped swing packets as long as they are not consecutive.

November's killaura sends a swingItem call before each attack on the BASIC clicking path, and the ADVANCED and UPDATED clicking modes attack on every walking update tick with no randomization. At a full 20-tick rate the module sustains up to 20 attacks per second, and every attack that is not preceded by a swing packet in the same tick contributes to the no-swing counter. The swing item packet, C0APacketAnimation, is what NCP sees, and the WATCHDOG autoblock mode's C08 and C07 traffic does not substitute for it.

The bot filter does not interact with this check at all: it only removes candidates from the aura, and the attacks that survive still need their swings. An entity that stays filtered simply produces fewer attacks, which reduces the counter rather than feeding it.

anticheat Arc KillAura (attack rate)

KillAura.java114 lines · Java
1
package me.vrekt.arc.check.combat;
2
3
import me.vrekt.arc.Arc;
4
import me.vrekt.arc.check.Check;
5
import me.vrekt.arc.check.CheckType;
6
import me.vrekt.arc.data.combat.FightData;
7
import me.vrekt.arc.utilties.LocationHelper;
8
import org.bukkit.ChatColor;
9
import org.bukkit.entity.Entity;
10
import org.bukkit.entity.Player;
11
import org.bukkit.util.Vector;
12
13
public class KillAura extends Check {
14
15
    private double maxAngle, maxReach;
16
    private int maxSwingTime, maxAttacks, maxAttackPackets;
17
18
    public KillAura() {
19
        super(CheckType.KILLAURA);
20
21
        maxAngle = Arc.getCheckManager().getValueDouble(CheckType.KILLAURA, "max-direction-angle");
22
        maxSwingTime = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-swing-time");
23
        maxReach = Arc.getCheckManager().getValueDouble(CheckType.KILLAURA, "max-reach");
24
        maxAttacks = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-attacks");
25
        maxAttackPackets = Arc.getCheckManager().getValueInt(CheckType.KILLAURA, "max-attack-packets");
26
27
    }
28
29
    public boolean check(FightData data, Player player) {
30
        result.reset();
31
32
        Entity last = data.getLastAttackedEntity();
33
        Entity entity = data.getAttackedEntity();
34
35
        // Calculate angle stuff.
36
        Vector playerLocation = player.getLocation().toVector();
37
        Vector entityLocation = entity.getLocation().toVector();
38
        double angle = entityLocation.subtract(playerLocation).angle(player.getLocation().getDirection());
39
40
        if (last != null && !entity.equals(last)) {
41
            // check the angle between the two entities
42
            Vector lastLocation = last.getLocation().toVector();
43
            double angleToLast = lastLocation.subtract(playerLocation).angle(player.getLocation().getDirection());
44
            double angleDifference = Math.abs(angleToLast - angle);
45
            double distanceDifference = LocationHelper.distance(last.getLocation(), entity.getLocation());
46
            if (angleDifference > maxAngle && distanceDifference <= maxReach) {
47
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Multi)");
48
                result.set(checkViolation(player, "Angle difference greater than allowed. a=" + angleDifference + " e=" + maxAngle));
49
            }
50
        }
51
52
        // check yaw difference.
53
        if (angle > maxAngle) {
54
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Direction)");
55
            result.set(checkViolation(player, "Angle distance greater than allowed. a=" + angle + " e=" + maxAngle));
56
        }
57
58
        // check swing time.
59
        long time = System.currentTimeMillis() - data.getLastArmSwing();
60
        if (time > maxSwingTime) {
61
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(NoSwing)");
62
            result.set(checkViolation(player, "Player did not swing their arm in time."));
63
        }
64
65
        // distance to entity excluding knockback.
66
        double distance = LocationHelper.distance(player.getLocation(), entity.getLocation().subtract(entity.getVelocity()));
67
        // check for reach
68
        if (distance > maxReach) {
69
            getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Reach)");
70
            result.set(checkViolation(player, "Entity is out of players range. d=" + distance + " e=" + maxReach));
71
        }
72
73
        // check max attacks
74
        if (data.getLastAttackCheck() == 0) {
75
            data.setLastAttackCheck(System.currentTimeMillis());
76
        }
77
        long lastAttack = System.currentTimeMillis() - data.getLastAttackCheck();
78
        if (lastAttack >= 1000) {
79
            // check if we exceeded the max attacks in the last second.
80
            int totalAttacks = data.getTotalAttacks();
81
            if (totalAttacks > maxAttacks) {
82
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Speed)");
83
                result.set(checkViolation(player, "Attacking too fast. a=" + totalAttacks + " e=" + maxAttacks));
84
            }
85
            // reset data for next check.
86
            data.setTotalAttacks(0);
87
            data.setLastAttackCheck(System.currentTimeMillis());
88
        }
89
90
        getCheck().setCheckName("KillAura");
91
        return result.failed();
92
    }
93
94
    public boolean checkFrequency(FightData data, Player player) {
95
        if (data.getLastAttackCheck() == 0) {
96
            data.setLastAttackCheck(System.currentTimeMillis());
97
            return false;
98
        }
99
100
        long time = System.currentTimeMillis() - data.getLastAttackCheck();
101
        if (time >= 1000) {
102
            data.setLastAttackCheck(System.currentTimeMillis());
103
            int totalPackets = data.getAttackPackets();
104
            if (totalPackets > maxAttackPackets) {
105
                data.setAttackPackets(0);
106
                getCheck().setCheckName("Kill Aura " + ChatColor.GRAY + "(Speed)");
107
                return checkViolation(player, "Attacking too fast a=" + totalPackets + " e=" + maxAttackPackets);
108
            }
109
        }
110
111
        return false;
112
    }
113
114
}

How it counteracts this module

Arc's Speed sub-check counts attacks and attack packets per second. Every attack adds to totalAttacks, and once a second the check compares the total against max-attacks, resetting the counter; checkFrequency separately compares attackPackets against max-attack-packets. Exceeding either raises 'Kill Aura (Speed)'.

November's ADVANCED and UPDATED clicking modes attack on every walking update, which at a normal tick rate is up to 20 attacks per second, far beyond a typical max-attacks ceiling around 14 to 16. The BASIC mode randomizes the delay from the CPS settings, but the timer still sustains attacks near the configured rate. The autoblock modes add packets around each attack: WATCHDOG and BASIC send C08 placements and C07 releases, so the per-second packet count runs at two to three times the attack count, which is what checkFrequency scores.

Filtering bots reduces the number of valid targets but not the attack rate: with a single real target the module still attacks it on every walking tick in the fast modes. The bot filter therefore cannot tune the module under the rate ceiling; only the CPS settings or the clicking mode change the count.

anticheat Hawk FightHitbox (server-side hit validation)

FightHitbox.java232 lines · Java
1
/*
2
 * This file is part of Hawk Anticheat.
3
 * Copyright (C) 2018 Hawk Development Team
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
package me.islandscout.hawk.check.combat;
20
21
import me.islandscout.hawk.HawkPlayer;
22
import me.islandscout.hawk.check.Cancelless;
23
import me.islandscout.hawk.check.CustomCheck;
24
import me.islandscout.hawk.event.Event;
25
import me.islandscout.hawk.event.InteractEntityEvent;
26
import me.islandscout.hawk.event.MoveEvent;
27
import me.islandscout.hawk.util.*;
28
import me.islandscout.hawk.wrap.block.WrappedBlock;
29
import me.islandscout.hawk.wrap.entity.WrappedEntity;
30
import org.bukkit.GameMode;
31
import org.bukkit.Location;
32
import org.bukkit.Material;
33
import org.bukkit.block.Block;
34
import org.bukkit.entity.Entity;
35
import org.bukkit.entity.Player;
36
import org.bukkit.util.BlockIterator;
37
import org.bukkit.util.Vector;
38
39
import java.util.HashMap;
40
import java.util.Map;
41
import java.util.UUID;
42
43
/**
44
 * The hit detection in Minecraft is mostly determined by the client,
45
 * thus servers are left to trust the client. (There are a few exceptions
46
 * for the unmodified Notchian server such as preventing hits exceeding 6
47
 * blocks from the target entity). This poses a problem for players and
48
 * server owners since players can modify the client to manipulate hit
49
 * detection and allow for cheating when in combat with other players.
50
 *
51
 * Hawk’s hitbox checking aims to detect cheating during player vs.
52
 * player combat by validating hits on the server. When the server
53
 * receives an interaction packet from the client, Hawk gets the client’s
54
 * last known position and next direction, and uses it to perform a ray
55
 * trace test on the victim’s hitbox. Before the ray-trace test begins,
56
 * though, Hawk must factor in latency by rewinding the victim’s hitbox
57
 * to an appropriate time based on the client’s ping latency. To
58
 * accomplish this, Hawk keeps a history of players’ positions and
59
 * timestamps in a table and it retrieves a position that best
60
 * approximates where it appeared to the client when the client attacked
61
 * it. Hawk then performs the ray-trace test to determine whether the
62
 * client landed the hit or not. Although the system may produce false
63
 * positives with clients on unstable connections, it is a fair tradeoff
64
 * between user experience and cheat prevention.
65
 *
66
 * There are other sources of error which will probably not be accounted
67
 * for in Hawk anytime soon. Other sources of error include:
68
 *   - The client receives entity relative moves in 1/32 block precision.
69
 *   - The client holds off one tick to smoothly animate other players
70
 *     on the screen in the case of slight network jitter. It will
71
 *     linearly interpolate from the last position to the latest
72
 *     position up to 3 ticks if it doesn't receive a relative move
73
 *     packet to update the player's position.
74
 *   - The client will predict the motion of some entities, such as
75
 *     arrows. If there is latency and something unexpected happens
76
 *     to the entity, the client may desynchronize from the server.
77
 *
78
 * In most cases, the client uses the current frame's yaw and pitch to
79
 * compute the direction vector for the attack hit-scan. Fortunately,
80
 * ticking and rendering is done in the same thread. Unfortunately, in
81
 * the tick stack, attacking is done before sending yaw/pitch updates
82
 * to the server, which means that we must wait until the next flying
83
 * packet to get the direction of the hit-scan.
84
 *
85
 * For realtime protection, it's best to use the EntityInteractDirection
86
 * check. It actively enforces directions, but it extrapolates the
87
 * yaw/pitch because of how the client hit-scanning works.
88
 */
89
public class FightHitbox extends CustomCheck implements Cancelless {
90
91
    private final double MAX_REACH;
92
    private final int PING_LIMIT;
93
    private final boolean CHECK_OTHER_ENTITIES;
94
    private final boolean LAG_COMPENSATION;
95
    private final boolean DEBUG_HITBOX;
96
    private final boolean DEBUG_RAY;
97
    private final boolean CHECK_OCCLUSION;
98
    private final boolean CHECK_BOX_INTERSECTION;
99
    private final double BOX_EPSILON = 0.005;
100
101
    private Map<UUID, InteractEntityEvent> lastInteractionMap;
102
103
    public FightHitbox() {
104
        super("fighthitbox", false, 5, 10000, 0.95, 5000, "%player% failed combat hitbox. %type% VL: %vl%", null);
105
        CHECK_BOX_INTERSECTION = (boolean) customSetting("checkBoxIntersection", "", true);
106
        CHECK_OCCLUSION = (boolean) customSetting("checkOccluding", "", false);
107
        MAX_REACH = (double) customSetting("maxReach", "", 3.1);
108
        CHECK_OTHER_ENTITIES = (boolean) customSetting("checkOtherEntities", "", false);
109
        LAG_COMPENSATION = (boolean) customSetting("lagCompensation", "", true);
110
        PING_LIMIT = (int) customSetting("pingLimit", "", -1);
111
        DEBUG_HITBOX = (boolean) customSetting("hitbox", "debug", false);
112
        DEBUG_RAY = (boolean) customSetting("ray", "debug", false);
113
        lastInteractionMap = new HashMap<>();
114
    }
115
116
    @Override
117
    protected void check(Event event) {
118
        if(event instanceof InteractEntityEvent)
119
            processHit((InteractEntityEvent)event);
120
        else if(event instanceof MoveEvent) {
121
            InteractEntityEvent interactEntityEvent = lastInteractionMap.get(event.getHawkPlayer().getUuid());
122
            if(interactEntityEvent != null) {
123
                MoveEvent move = (MoveEvent) event;
124
125
                float yaw;
126
                float pitch;
127
                //In 1.8, the yaw of the cursor is behind by one tick.
128
                if(event.getHawkPlayer().getClientVersion() == 8) {
129
                    yaw = event.getHawkPlayer().getYaw();
130
                } else {
131
                    yaw = move.getTo().getYaw();
132
                }
133
                pitch = move.getTo().getPitch();
134
135
                processDirection(interactEntityEvent, yaw, pitch);
136
            }
137
            lastInteractionMap.put(event.getHawkPlayer().getUuid(), null);
138
        }
139
    }
140
141
    private void processHit(InteractEntityEvent e) {
142
        lastInteractionMap.put(e.getHawkPlayer().getUuid(), e);
143
    }
144
145
    private void processDirection(InteractEntityEvent e, float yaw, float pitch) {
146
        Entity entity = e.getEntity();
147
        if (!(entity instanceof Player) && !CHECK_OTHER_ENTITIES)
148
            return;
149
        Player attacker = e.getPlayer();
150
        int ping = ServerUtils.getPing(attacker);
151
        if (ping > PING_LIMIT && PING_LIMIT != -1)
152
            return;
153
154
        HawkPlayer att = e.getHawkPlayer();
155
        Location attackerEyeLocation = att.getPosition().clone().add(new Vector(0, 1.62, 0)).toLocation(att.getWorld());
156
        Vector attackerDirection = MathPlus.getDirection(yaw, pitch);
157
158
        double maxReach = MAX_REACH;
159
        if (attacker.getGameMode() == GameMode.CREATIVE)
160
            maxReach += 1.9;
161
162
        Vector victimLocation;
163
        if (LAG_COMPENSATION)
164
            //No need to add 50ms; the move and attack are already chronologically so close together
165
            victimLocation = hawk.getLagCompensator().getHistoryLocation(ping, e.getEntity()).toVector();
166
        else
167
            victimLocation = e.getEntity().getLocation().toVector();
168
169
        Vector eyePos;
170
        if(e.getHawkPlayer().isInVehicle()) {
171
            eyePos = hawk.getLagCompensator().getHistoryLocation(ping, e.getPlayer()).toVector();
172
            eyePos.setY(eyePos.getY() + e.getPlayer().getEyeHeight());
173
        }
174
        else {
175
            eyePos = new Vector(attackerEyeLocation.getX(), attacker.isSneaking() ? attackerEyeLocation.getY() - 0.08 : attackerEyeLocation.getY(), attackerEyeLocation.getZ());
176
        }
177
        Vector direction = new Vector(attackerDirection.getX(), attackerDirection.getY(), attackerDirection.getZ());
178
        Ray attackerRay = new Ray(eyePos, direction);
179
180
        AABB victimAABB;
181
        victimAABB = WrappedEntity.getWrappedEntity(entity).getHitbox(victimLocation);
182
        victimAABB.expand(BOX_EPSILON, BOX_EPSILON, BOX_EPSILON);
183
184
        Vector intersectVec3d = victimAABB.intersectsRay(attackerRay, 0, Float.MAX_VALUE);
185
186
        if (DEBUG_HITBOX) {
187
            victimAABB.highlight(hawk, attacker.getWorld(), 0.29);
188
        }
189
190
        if (DEBUG_RAY) {
191
            attackerRay.highlight(hawk, attacker.getWorld(), maxReach, 0.1);
192
        }
193
194
        if (intersectVec3d != null) {
195
            Location intersect = new Location(attacker.getWorld(), intersectVec3d.getX(), intersectVec3d.getY(), intersectVec3d.getZ());
196
            double interDistance = intersect.distance(attackerEyeLocation);
197
            if (interDistance > maxReach) {
198
                punish(att, 1, true, e, new Placeholder("type", "Reach: " + MathPlus.round(interDistance, 2) + "m"));
199
                return;
200
            }
201
            if (CHECK_OCCLUSION && interDistance > 1D) {
202
                BlockIterator iter = new BlockIterator(attacker.getWorld(), eyePos, attackerDirection, 0, (int) interDistance + 1);
203
                while (iter.hasNext()) {
204
                    Block bukkitBlock = iter.next();
205
206
                    if (bukkitBlock.getType() == Material.AIR || bukkitBlock.isLiquid())
207
                        continue;
208
209
                    WrappedBlock b = WrappedBlock.getWrappedBlock(bukkitBlock, att.getClientVersion());
210
                    Vector intersection = b.getHitBox().intersectsRay(new Ray(attackerEyeLocation.toVector(), attackerDirection), 0, Float.MAX_VALUE);
211
                    if (intersection != null) {
212
                        if (intersection.distance(eyePos) < interDistance) {
213
                            punish(att, 1, true, e, new Placeholder("type", "Interacted through " + b.getBukkitBlock().getType()));
214
                            return;
215
                        }
216
                    }
217
                }
218
219
            }
220
        } else if (CHECK_BOX_INTERSECTION) {
221
            punish(att, 1, true, e, new Placeholder("type", "Did not hit hitbox."));
222
            return;
223
        }
224
225
        reward(att); //reward player
226
    }
227
228
    @Override
229
    public void removeData(Player p) {
230
        lastInteractionMap.remove(p.getUniqueId());
231
    }
232
}

How it counteracts this module

FightHitbox re-checks each player-versus-player attack by ray tracing from the attacker's eye along the direction carried by the next movement packet. The victim's position is rewound through Hawk's lag compensator to match the ping at attack time, the hitbox is expanded by 0.005, and the ray must intersect it within 3.1 blocks, or 5.0 in creative. A miss with CHECK_BOX_INTERSECTION enabled punishes 'Did not hit hitbox.', an intersection beyond the reach reports the distance in meters, and the optional occlusion pass flags hits whose ray crosses a solid block first.

November's killaura spoofs rotations through the rotation manager at HIGH priority and attacks targets it cannot see at WallRange, so hits can be aimed through walls and at targets outside the visual cone. Hawk derives the direction from the movement packet that follows the C02, and the box is where the victim was when the attacker's view of it was formed, so a wall-hit either misses the box or lands beyond 3.1. The bot filter selects the target client-side, but the server-side ray test applies to every C02 that arrives.

← Back to Analysis Hub