Sigma 4.11 FriendAlert module 2 files, 138 lines

Sigma 4.11 FriendAlert: Full Source Analysis

Sigma 4.11's FriendAlert is a purely passive tab-list watcher: it registers for EventPacket, filters incoming packets to S38PacketPlayerListItem, and when the server broadcasts an ADD_PLAYER action…

info/sigmaclient/module/impl/other/FriendAlert.java · GitHub source ↗

Published 2026-08-13 · Updated 2026-08-13

Packets This Module Uses

Analysis

Overview

Sigma 4.11's FriendAlert is a purely passive tab-list watcher: it registers for EventPacket, filters incoming packets to S38PacketPlayerListItem, and when the server broadcasts an ADD_PLAYER action it walks the AddPlayerData list, matches each name against FriendManager.isFriend, and posts a 2.5-second notification when a friend appears. The module constructs no packets, mutates no packet fields, and never responds to the server - its entire effect is a client-side toast. Because the data it reads is server-initiated broadcast traffic that every client receives anyway, there is no server-observable behavior to distinguish a FriendAlert user from a vanilla client, which makes it the archetype of an undetectable read-only module.

Data source

The trigger is S38PacketPlayerListItem with Action.ADD_PLAYER, the packet the server sends to every player in the tab list when someone joins (and the same packet family used for game-mode and latency updates). FriendAlert ignores every other action and every other packet type, so it fires exactly once per join broadcast. The per-entry match is FriendManager.isFriend(name), which compares case-insensitively after stripping control codes and always returns true for the local player's own profile name - the self-entry in the tab list is the only guaranteed match. The notification text is the friend's name in aqua (§b) with a 2500ms lifetime and Type.INFO, and the unused connect/currentY/targetY/Timer fields are leftovers from an earlier draft that never shipped.

Detection surface

The module's server-visible footprint is zero: it sits on the incoming side of the packet bus (ep.isIncoming()), reads only fields the vanilla client would read to render the tab list, and produces nothing on the outgoing side. No anticheat check in the corpus attaches any behavior to S38PacketPlayerListItem - the packet is presentational state synchronization, not a client-behavior probe. The only way the module could be observed is if a modified variant acted on the harvested names (chat messages, tab-complete probes, friend-targeted attacks), and that would be a different module. FriendAlert itself is a textbook demonstration that information-only modules are undetectable by design, which is why its countering section documents the server-side lifecycle of the S38 data instead of a detection that does not exist.

source FriendAlert.java (module)

FriendAlert.java51 lines · JavaOriginal ↗
1
/**
2
 * Time: 8:22:36 PM
3
 * Date: Jan 5, 2017
4
 * Creator: cool1
5
 */
6
package info.sigmaclient.module.impl.other;
7
8
import info.sigmaclient.event.Event;
9
import info.sigmaclient.event.RegisterEvent;
10
import info.sigmaclient.event.impl.EventPacket;
11
import info.sigmaclient.management.friend.FriendManager;
12
import info.sigmaclient.management.notifications.Notifications;
13
import info.sigmaclient.management.notifications.Notifications.Type;
14
import info.sigmaclient.module.Module;
15
import info.sigmaclient.module.data.ModuleData;
16
import info.sigmaclient.util.Timer;
17
import net.minecraft.network.play.server.S38PacketPlayerListItem;
18
19
/**
20
 * @author cool1
21
 */
22
public class FriendAlert extends Module {
23
24
    private boolean connect;
25
    private String name;
26
    private int currentY, targetY;
27
    Timer timer = new Timer();
28
29
    public FriendAlert(ModuleData data) {
30
        super(data);
31
        // TODO Auto-generated constructor stub
32
    }
33
34
    @Override
35
    @RegisterEvent(events = {EventPacket.class})
36
    public void onEvent(Event event) {
37
        EventPacket ep = (EventPacket) event;
38
        if (ep.isIncoming() && ep.getPacket() instanceof S38PacketPlayerListItem) {
39
            S38PacketPlayerListItem packet = (S38PacketPlayerListItem) ep.getPacket();
40
            if (packet.func_179768_b() == S38PacketPlayerListItem.Action.ADD_PLAYER) {
41
                for (Object o : packet.func_179767_a()) {
42
                    S38PacketPlayerListItem.AddPlayerData data = (S38PacketPlayerListItem.AddPlayerData) o;
43
                    if (FriendManager.isFriend(data.field_179964_d.getName())) {
44
                        Notifications.getManager().post("Friend Alert", "\247b" + data.field_179964_d.getName() + " has joined!", 2500L, Type.INFO);
45
                    }
46
                }
47
            }
48
        }
49
    }
50
}

What this file does

The handler is a single instanceof filter: ep.isIncoming() && ep.getPacket() instanceof S38PacketPlayerListItem, then a second filter on func_179768_b() == Action.ADD_PLAYER. The per-entry loop iterates packet.func_179767_a() (the AddPlayerData list), extracts data.field_179964_d.getName(), and posts the notification through Notifications.getManager().post when FriendManager.isFriend returns true. Everything the module touches is read-only: the packet, the friend list, and the notification manager. The vestigial fields (connect, name, currentY, targetY, timer) are declared but never used, and there is no onEnable/onDisable, so the module's runtime cost is one packet-type check per incoming packet.

source FriendManager.java (friend list source)

FriendManager.java87 lines · JavaOriginal ↗
1
package info.sigmaclient.management.friend;
2
3
import java.io.File;
4
import java.util.ArrayList;
5
import java.util.List;
6
7
import info.sigmaclient.util.FileUtils;
8
import net.minecraft.client.Minecraft;
9
import net.minecraft.util.StringUtils;
10
11
public class FriendManager {
12
    private static final File FRIEND_DIR;
13
    public static ArrayList<Friend> friendsList;
14
15
    static {
16
        FRIEND_DIR = FileUtils.getConfigFile("Friends");
17
        FriendManager.friendsList = new ArrayList<Friend>();
18
    }
19
20
    public static void start() {
21
        load();
22
        save();
23
    }
24
25
    public static void addFriend(final String name, final String alias) {
26
        FriendManager.friendsList.add(new Friend(name, alias));
27
        save();
28
    }
29
30
    public static String getAlias(final String name) {
31
        String alias = null;
32
        for (final Friend friend : FriendManager.friendsList) {
33
            if (friend.name.equalsIgnoreCase(StringUtils.stripControlCodes(name))) {
34
                alias = friend.alias;
35
                break;
36
            }
37
        }
38
        return alias;
39
    }
40
41
    public static void removeFriend(final String name) {
42
        for (final Friend friend : FriendManager.friendsList) {
43
            if (friend.name.equalsIgnoreCase(name)) {
44
                FriendManager.friendsList.remove(friend);
45
                break;
46
            }
47
        }
48
        save();
49
    }
50
51
    public static boolean isFriend(final String name) {
52
        boolean isFriend = false;
53
        for (final Friend friend : FriendManager.friendsList) {
54
            if (friend.name.equalsIgnoreCase(StringUtils.stripControlCodes(name))) {
55
                isFriend = true;
56
                break;
57
            }
58
        }
59
        if (Minecraft.getMinecraft().thePlayer.getGameProfile().getName() == name) {
60
            isFriend = true;
61
        }
62
        return isFriend;
63
    }
64
65
    public static void load() {
66
        FriendManager.friendsList.clear();
67
        final List<String> fileContent = FileUtils.read(FriendManager.FRIEND_DIR);
68
        for (final String line : fileContent) {
69
            try {
70
                final String[] split = line.split(":");
71
                final String name = split[0];
72
                final String alias = split[1];
73
                addFriend(name, alias);
74
            } catch (Exception ex) {
75
            }
76
        }
77
    }
78
79
    public static void save() {
80
        final List<String> fileContent = new ArrayList<String>();
81
        for (final Friend friend : FriendManager.friendsList) {
82
            fileContent.add(String.format("%s:%s", friend.name, friend.alias));
83
        }
84
        FileUtils.write(FriendManager.FRIEND_DIR, fileContent, true);
85
    }
86
}

What this file does

FriendManager is the lookup table behind the alert. It keeps a static ArrayList<Friend> persisted to a 'Friends' config file as name:alias lines (load() splits on ':' and save() rewrites the file), and isFriend(name) is the matcher FriendAlert calls: it iterates the list comparing friend.name against StringUtils.stripControlCodes(name) with equalsIgnoreCase, and hard-codes the local player's own game profile name as always-friend. That last rule is why the tab-list self-entry can produce an alert even with an empty friend list. Because the comparison strips color codes and ignores case, the module matches names regardless of how the server formats them in the S38 payload.

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 PacketEntityReplication (the AC's only S38 consumption)

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

Grim's PacketEntityReplication is the representative example of what a modern anticheat actually does with S38PacketPlayerListItem: it parses ADD_PLAYER entries (WrapperPlayServerPlayerInfo / PlayerInfoUpdate) to register UUIDs and positions into its compensatedEntities bookkeeping, and REMOVE_PLAYER to unregister them - the same data FriendAlert reads, consumed for entity-replication state rather than for client-behavior detection. The handler treats the packet as authoritative server state about other entities, never as evidence about the receiving client. That is the entire point of the comparison: FriendAlert performs an identical parse on the client side and then does nothing observable with it. There is no counter to measure, because the AC's ledger is keyed to the packet's content, not to who read it or when - a read leaves no trace in any server-side data structure.

anticheat SpectateManager (S38 filtering predicate)

SpectateManager.java102 lines · Java
1
package ac.grim.grimac.manager;
2
3
import ac.grim.grimac.GrimAPI;
4
import ac.grim.grimac.manager.init.ReloadableInitable;
5
import ac.grim.grimac.manager.init.start.StartableInitable;
6
import ac.grim.grimac.platform.api.player.PlatformPlayer;
7
import ac.grim.grimac.player.GrimPlayer;
8
import ac.grim.grimac.utils.math.Location;
9
import com.github.retrooper.packetevents.protocol.player.GameMode;
10
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo;
11
import net.kyori.adventure.text.Component;
12
import net.kyori.adventure.text.format.NamedTextColor;
13
import org.jetbrains.annotations.NotNull;
14
15
import java.util.ArrayList;
16
import java.util.Map;
17
import java.util.Objects;
18
import java.util.Set;
19
import java.util.UUID;
20
import java.util.concurrent.ConcurrentHashMap;
21
22
public class SpectateManager implements StartableInitable, ReloadableInitable {
23
24
    private final Map<UUID, PreviousState> spectatingPlayers = new ConcurrentHashMap<>();
25
    private final Set<UUID> hiddenPlayers = ConcurrentHashMap.newKeySet();
26
    private final Set<String> allowedWorlds = ConcurrentHashMap.newKeySet();
27
28
    private boolean checkWorld = false;
29
30
    @Override
31
    public void start() {
32
        reload();
33
    }
34
35
    @Override
36
    public void reload() {
37
        allowedWorlds.clear();
38
        allowedWorlds.addAll(GrimAPI.INSTANCE.getConfigManager().getConfig().getStringListElse("spectators.allowed-worlds", new ArrayList<>()));
39
        checkWorld = !(allowedWorlds.isEmpty() || new ArrayList<>(allowedWorlds).get(0).isEmpty());
40
    }
41
42
    public boolean isSpectating(UUID uuid) {
43
        return spectatingPlayers.containsKey(uuid);
44
    }
45
46
    public boolean shouldHidePlayer(GrimPlayer receiver, WrapperPlayServerPlayerInfo.PlayerData playerData) {
47
        return playerData.getUserProfile() != null
48
                && playerData.getUserProfile().getUUID() != null
49
                && shouldHidePlayer(receiver, playerData.getUserProfile().getUUID());
50
    }
51
52
    public boolean shouldHidePlayer(GrimPlayer receiver, UUID uuid) {
53
        return !Objects.equals(uuid, receiver.uuid) // don't hide to yourself
54
                && (spectatingPlayers.containsKey(uuid) || hiddenPlayers.contains(uuid)) //hide if you are a spectator
55
                && !(receiver.uuid != null && (spectatingPlayers.containsKey(receiver.uuid) || hiddenPlayers.contains(receiver.uuid))) // don't hide to other spectators
56
                && (!checkWorld || (receiver.platformPlayer != null && allowedWorlds.contains(receiver.platformPlayer.getWorld().getName()))); // hide if you are in a specific world
57
    }
58
59
    public boolean enable(PlatformPlayer platformPlayer) {
60
        if (spectatingPlayers.containsKey(platformPlayer.getUniqueId())) return false;
61
        spectatingPlayers.put(platformPlayer.getUniqueId(), new PreviousState(platformPlayer.getGameMode(), platformPlayer.getLocation()));
62
        return true;
63
    }
64
65
    public void onLogin(UUID uuid) {
66
        hiddenPlayers.add(uuid);
67
    }
68
69
    public void onQuit(UUID uuid) {
70
        hiddenPlayers.remove(uuid);
71
        handlePlayerStopSpectating(uuid);
72
    }
73
74
    // only call this synchronously
75
    public void disable(@NotNull PlatformPlayer platformPlayer, boolean teleportBack) {
76
        PreviousState previousState = spectatingPlayers.get(platformPlayer.getUniqueId());
77
        if (previousState != null) {
78
            if (teleportBack && previousState.location.isWorldLoaded()) {
79
                platformPlayer.teleportAsync(previousState.location).thenAccept(bool -> {
80
                    if (bool) {
81
                        onDisable(previousState, platformPlayer);
82
                    } else {
83
                        platformPlayer.sendMessage(Component.text("Teleport failed, please try again.", NamedTextColor.RED));
84
                    }
85
                });
86
            } else {
87
                onDisable(previousState, platformPlayer);
88
            }
89
        }
90
    }
91
92
    private void onDisable(PreviousState previousState, PlatformPlayer platformPlayer) {
93
        platformPlayer.setGameMode(previousState.gameMode);
94
        handlePlayerStopSpectating(platformPlayer.getUniqueId());
95
    }
96
97
    public void handlePlayerStopSpectating(UUID uuid) {
98
        spectatingPlayers.remove(uuid);
99
    }
100
101
    private record PreviousState(GameMode gameMode, Location location) {}
102
}

How it counteracts this module

SpectateManager holds the predicate that decides which tab-list entries get hidden from which viewers: shouldHidePlayer(receiver, uuid) returns true when the entry is a spectator (or on the hidden list), the receiver is not themselves a spectator, and the world filter passes. This is presentation logic over the same S38 stream FriendAlert watches - the AC decides what the client should see, but it cannot and does not infer anything about what the client does with what it sees. The function's inputs are receiver identity, entry UUID and world configuration; a client that renders the entry and pops a notification is indistinguishable from a client that renders nothing. The check documents the boundary of the packet's trust model: servers filter S38 content on the way out because it is display data, and display data carries no return channel for detection.

anticheat PacketHidePlayerInfo (S38 rewriting)

PacketHidePlayerInfo.java110 lines · Java
1
package ac.grim.grimac.events.packets;
2
3
import ac.grim.grimac.GrimAPI;
4
import ac.grim.grimac.player.GrimPlayer;
5
import com.github.retrooper.packetevents.PacketEvents;
6
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
7
import com.github.retrooper.packetevents.event.PacketListenerPriority;
8
import com.github.retrooper.packetevents.event.PacketSendEvent;
9
import com.github.retrooper.packetevents.manager.server.ServerVersion;
10
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
11
import com.github.retrooper.packetevents.protocol.player.GameMode;
12
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfo;
13
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerInfoUpdate;
14
15
import java.util.ArrayList;
16
import java.util.EnumSet;
17
import java.util.List;
18
19
public class PacketHidePlayerInfo extends PacketListenerAbstract {
20
21
    public PacketHidePlayerInfo() {
22
        super(PacketListenerPriority.HIGHEST);
23
    }
24
25
    @Override
26
    public boolean isPreVia() {
27
        return true;
28
    }
29
30
    @Override
31
    public void onPacketSend(PacketSendEvent event) {
32
        if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO) {
33
            // iterate through players and fake their game mode if they are spectating via grim spectate
34
            if (PacketEvents.getAPI().getServerManager().getVersion().isOlderThanOrEquals(ServerVersion.V_1_12_2))
35
                return;
36
37
            GrimPlayer receiver = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getUser());
38
39
            if (receiver == null) { // Exempt
40
                return;
41
            }
42
43
            WrapperPlayServerPlayerInfo info = new WrapperPlayServerPlayerInfo(event);
44
45
            if (info.getAction() == WrapperPlayServerPlayerInfo.Action.UPDATE_GAME_MODE || info.getAction() == WrapperPlayServerPlayerInfo.Action.ADD_PLAYER) {
46
                List<WrapperPlayServerPlayerInfo.PlayerData> nmsPlayerInfoDataList = info.getPlayerDataList();
47
48
                int hideCount = 0;
49
                for (WrapperPlayServerPlayerInfo.PlayerData playerData : nmsPlayerInfoDataList) {
50
                    if (GrimAPI.INSTANCE.getSpectateManager().shouldHidePlayer(receiver, playerData)) {
51
                        hideCount++;
52
                        if (playerData.getGameMode() == GameMode.SPECTATOR)
53
                            playerData.setGameMode(GameMode.SURVIVAL);
54
                    }
55
                }
56
57
                // if amount of hidden players is the amount of players updated & is an update game mode action just cancel it
58
                if (hideCount == nmsPlayerInfoDataList.size() && info.getAction() == WrapperPlayServerPlayerInfo.Action.UPDATE_GAME_MODE) {
59
                    event.setCancelled(true);
60
                } else if (hideCount > 0) {
61
                    event.markForReEncode(true);
62
                }
63
            }
64
        } else if (event.getPacketType() == PacketType.Play.Server.PLAYER_INFO_UPDATE) {
65
            GrimPlayer receiver = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getUser());
66
            if (receiver == null) return;
67
68
            WrapperPlayServerPlayerInfoUpdate wrapper = new WrapperPlayServerPlayerInfoUpdate(event);
69
            EnumSet<WrapperPlayServerPlayerInfoUpdate.Action> actions = wrapper.getActions();
70
            if (!actions.contains(WrapperPlayServerPlayerInfoUpdate.Action.UPDATE_GAME_MODE)) return;
71
72
            boolean onlyGameMode = actions.size() == 1; // packet is being sent to only update game modes
73
            int hideCount = 0;
74
            List<WrapperPlayServerPlayerInfoUpdate.PlayerInfo> modified = new ArrayList<>(wrapper.getEntries().size());
75
            // iterate through the player entries
76
            for (WrapperPlayServerPlayerInfoUpdate.PlayerInfo entry : wrapper.getEntries()) {
77
                // check if the player should be hidden
78
                WrapperPlayServerPlayerInfoUpdate.PlayerInfo modifiedPacket = null;
79
                if (GrimAPI.INSTANCE.getSpectateManager().shouldHidePlayer(receiver, entry.getGameProfile().getUUID())) {
80
                    hideCount++;
81
                    // modify & create a new packet from pre-existing one if they are a spectator
82
                    if (entry.getGameMode() == GameMode.SPECTATOR) {
83
                        modifiedPacket = new WrapperPlayServerPlayerInfoUpdate.PlayerInfo(entry);
84
                        modifiedPacket.setGameMode(GameMode.SURVIVAL);
85
                        modified.add(modifiedPacket);
86
                    }
87
                }
88
89
                if (modifiedPacket == null) {  // if the packet wasn't modified, send original
90
                    modified.add(entry);
91
                } else if (!onlyGameMode) { // if more than just the game mode updated, modify the packet
92
                    modified.add(modifiedPacket);
93
                } // if only the game mode was updated and the packet was modified, don't send anything
94
            }
95
96
            // if the amount of hidden players & modified entries are the same
97
            if (hideCount == modified.size()) {
98
                if (onlyGameMode) { // if only the game mode changed, cancel
99
                    event.setCancelled(true);
100
                } else { // if more than the game mode changed, remove the action
101
                    wrapper.getActions().remove(WrapperPlayServerPlayerInfoUpdate.Action.UPDATE_GAME_MODE);
102
                    event.markForReEncode(true);
103
                }
104
            } else { // modify entries
105
                wrapper.setEntries(modified);
106
                event.markForReEncode(true);
107
            }
108
        }
109
    }
110
}

How it counteracts this module

PacketHidePlayerInfo is the outbound half of the same machinery: on PLAYER_INFO (S38) sends it rewrites ADD_PLAYER and UPDATE_GAME_MODE entries for spectated targets - faking spectator game modes back to survival, re-encoding the packet, or cancelling it outright when every entry was hidden. The key fact for FriendAlert is that the AC itself modifies and cancels S38 packets before delivery, which means the packet is treated as untrusted presentation state whose only server-side counterpart is the broadcast itself. A client-side reader of that stream generates no traffic the server could correlate: the ADD_PLAYER broadcast is already happening, the read is passive, and the notification never leaves the process. The one theoretical counter - detecting clients that acknowledge or re-request tab-list data - would require the client to send something, and FriendAlert never does.

← Back to Analysis Hub