LiquidSense Dev AutoArmor module 2 files, 239 lines

LiquidSense Dev AutoArmor: Full Source Analysis

AutoArmor ranks every armor item in the 36 inventory slots with the static ArmorComparator and shift-clicks the best piece per armor type into place from a Render3DEvent handler.

net/ccbluex/liquidbounce/features/module/modules/combat/AutoArmor.java · GitHub source ↗

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

Analysis

Overview

AutoArmor ranks every armor item in the 36 inventory slots with the static ArmorComparator and shift-clicks the best piece per armor type into place from a Render3DEvent handler. The gate chain blocks the whole routine while flying, while the shared InventoryUtils.CLICK_TIMER has not passed the randomized delay, or while any window other than the player inventory container is open. Equips run newest-first (boots, legs, chest, helmet) and every click is followed by a fresh TimeUtils.randomDelay draw so the click train reads as human-paced. Candidates living in the hotbar skip the window entirely: the module switches the held slot to the armor, sends a C08 use-item packet that equips it server-side, and switches back, a C09-C08-C09 ceremony that never opens a window.

Selection and gating

onRender3D returns while the player flies, while InventoryUtils.CLICK_TIMER.hasTimePassed(delay) is false, or while mc.thePlayer.openContainer.windowId is not 0. The candidate stream is IntStream.range(0, 36): hotbar slots 0-8 are always eligible, inventory slots 9-35 only when the IItemStack getItemDelay watermark (itemDelayValue, default 0) has passed, and each slot must hold an ItemArmor. The pieces are grouped by ArmorPiece.getArmorType and the best of each group is chosen with max(ARMOR_COMPARATOR), the shared comparator instance. The replacement loop walks armorSlot 3 down to 0, so boots are resolved before the helmet, and compares the worn stack against the best piece with ARMOR_COMPARATOR.compare(oldArmor, armorPiece) < 0; a worn piece is moved out of the armor row first (move(8 - armorSlot, true)) and the new piece is equipped second (move(armorPiece.getSlot(), false)), each move returning early so at most one click is sent per render frame.

Two packet ceremonies

move() branches on the candidate slot. For a hotbar candidate (item < 9) with hotbarValue set, it queues C09PacketHeldItemChange(item), then C08PacketPlayerBlockPlacement with the armor stack, then C09PacketHeldItemChange(currentItem): the server processes the use-item as an equip and the client never opens a window, at the cost of two C09 switches per armor. Everything else goes through the window path, guarded against NoMove (MovementUtils.isMoving) and invOpenValue (only GuiInventory screens allowed). With simulateInventory on and no GuiInventory open, the module first queues C16PacketClientStatus(OPEN_INVENTORY_ACHIEVEMENT), then calls playerController.windowClick(windowId 0, slot, 0, 1) which serializes a C0E mode-1 shift-click, then queues C0DPacketCloseWindow when it opened the inventory itself. The container slot mapping is slot + 36 for hotbar indexes and the raw index for the main inventory, and armor-row moves pass the container slots 5-8 directly.

Packet fingerprint

The window path emits one C0E per empty slot and two per replaced slot (move-out then move-in), wrapped in a C16/C0D open-close ceremony only when the GUI was not actually open, so a server that tracks inventory-open state sees window-0 clicks arriving with no prior container-open. Every click is spaced by a fresh uniform delay in [minDelay, maxDelay] milliseconds (defaults 100-200) sampled from TimeUtils.randomDelay, and the module aborts the whole cycle if the shared CLICK_TIMER was reset by any other module's window click or C08 in between. The hotbar path is the one place C09 appears: the switch-to, use, switch-back trio emits two held-slot changes per equipped armor with no C0E at all.

source AutoArmor.java

AutoArmor.java143 lines · JavaOriginal ↗
1
/*
2
 * LiquidBounce Hacked Client
3
 * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
4
 * https://github.com/CCBlueX/LiquidBounce/
5
 */
6
package net.ccbluex.liquidbounce.features.module.modules.combat;
7
8
import net.ccbluex.liquidbounce.event.EventTarget;
9
import net.ccbluex.liquidbounce.event.Render3DEvent;
10
import net.ccbluex.liquidbounce.features.module.Module;
11
import net.ccbluex.liquidbounce.features.module.ModuleCategory;
12
import net.ccbluex.liquidbounce.features.module.ModuleInfo;
13
import net.ccbluex.liquidbounce.injection.implementations.IItemStack;
14
import net.ccbluex.liquidbounce.utils.InventoryUtils;
15
import net.ccbluex.liquidbounce.utils.MovementUtils;
16
import net.ccbluex.liquidbounce.utils.item.ArmorComparator;
17
import net.ccbluex.liquidbounce.utils.item.ArmorPiece;
18
import net.ccbluex.liquidbounce.utils.timer.TimeUtils;
19
import net.ccbluex.liquidbounce.value.BoolValue;
20
import net.ccbluex.liquidbounce.value.IntegerValue;
21
import net.minecraft.client.gui.inventory.GuiInventory;
22
import net.minecraft.item.ItemArmor;
23
import net.minecraft.item.ItemStack;
24
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
25
import net.minecraft.network.play.client.C09PacketHeldItemChange;
26
import net.minecraft.network.play.client.C0DPacketCloseWindow;
27
import net.minecraft.network.play.client.C16PacketClientStatus;
28
29
import java.util.List;
30
import java.util.Map;
31
import java.util.stream.Collectors;
32
import java.util.stream.IntStream;
33
34
@ModuleInfo(name = "AutoArmor", description = "Automatically equips the best armor in your inventory.", category = ModuleCategory.COMBAT)
35
public class AutoArmor extends Module {
36
37
    public static final ArmorComparator ARMOR_COMPARATOR = new ArmorComparator();
38
39
    private final IntegerValue maxDelayValue = new IntegerValue("MaxDelay", 200, 0, 400) {
40
        @Override
41
        protected void onChanged(final Integer oldValue, final Integer newValue) {
42
            final int minDelay = minDelayValue.get();
43
44
            if (minDelay > newValue) set(minDelay);
45
        }
46
    };
47
    private final IntegerValue minDelayValue = new IntegerValue("MinDelay", 100, 0, 400) {
48
49
        @Override
50
        protected void onChanged(final Integer oldValue, final Integer newValue) {
51
            final int maxDelay = maxDelayValue.get();
52
53
            if (maxDelay < newValue) set(maxDelay);
54
        }
55
    };
56
    private final BoolValue invOpenValue = new BoolValue("InvOpen", false);
57
    private final BoolValue simulateInventory = new BoolValue("SimulateInventory", true);
58
    private final BoolValue noMoveValue = new BoolValue("NoMove", false);
59
    private final IntegerValue itemDelayValue = new IntegerValue("ItemDelay", 0, 0, 5000);
60
    private final BoolValue hotbarValue = new BoolValue("Hotbar", true);
61
62
    private long delay;
63
64
    @EventTarget
65
    public void onRender3D(final Render3DEvent event) {
66
        if ((mc.thePlayer.capabilities.allowFlying && mc.thePlayer.capabilities.isFlying) || !InventoryUtils.CLICK_TIMER.hasTimePassed(delay) ||
67
                (mc.thePlayer.openContainer != null && mc.thePlayer.openContainer.windowId != 0))
68
            return;
69
70
        // Find best armor
71
        final Map<Integer, List<ArmorPiece>> armorPieces = IntStream.range(0, 36).filter(i -> {
72
                    final ItemStack itemStack = mc.thePlayer.inventory.getStackInSlot(i);
73
74
                    return itemStack != null && itemStack.getItem() instanceof ItemArmor && (i < 9 || System.currentTimeMillis() - ((IItemStack) (Object) itemStack).getItemDelay() >= itemDelayValue.get());
75
                })
76
                .mapToObj(i -> new ArmorPiece(mc.thePlayer.inventory.getStackInSlot(i), i))
77
                .collect(Collectors.groupingBy(ArmorPiece::getArmorType));
78
79
        final ArmorPiece[] bestArmor = new ArmorPiece[4];
80
81
        for (final Map.Entry<Integer, List<ArmorPiece>> armorEntry : armorPieces.entrySet()) {
82
            bestArmor[armorEntry.getKey()] = armorEntry.getValue().stream()
83
                    .max(ARMOR_COMPARATOR).orElse(null);
84
        }
85
86
        // Swap armor
87
        for (int i = 0; i < 4; i++) {
88
            final ArmorPiece armorPiece = bestArmor[i];
89
90
            if (armorPiece == null)
91
                continue;
92
93
            int armorSlot = 3 - i;
94
95
            final ArmorPiece oldArmor = new ArmorPiece(mc.thePlayer.inventory.armorItemInSlot(armorSlot), -1);
96
97
            if (oldArmor.getItemStack() == null || !(oldArmor.getItemStack().getItem() instanceof ItemArmor) ||
98
                    ARMOR_COMPARATOR.compare(oldArmor, armorPiece) < 0) {
99
                if (oldArmor.getItemStack() != null && move(8 - armorSlot, true))
100
                    return;
101
102
                if (move(armorPiece.getSlot(), false))
103
                    return;
104
            }
105
        }
106
    }
107
108
    /**
109
     * Shift+Left clicks the specified item
110
     *
111
     * @param item        Slot of the item to click
112
     * @param isArmorSlot
113
     * @return True if it is unable to move the item
114
     */
115
    private boolean move(int item, boolean isArmorSlot) {
116
        if (!isArmorSlot && item < 9 && hotbarValue.get()) {
117
            mc.getNetHandler().addToSendQueue(new C09PacketHeldItemChange(item));
118
            mc.getNetHandler().addToSendQueue(new C08PacketPlayerBlockPlacement(mc.thePlayer.inventoryContainer.getSlot(item).getStack()));
119
            mc.getNetHandler().addToSendQueue(new C09PacketHeldItemChange(mc.thePlayer.inventory.currentItem));
120
121
            delay = TimeUtils.randomDelay(minDelayValue.get(), maxDelayValue.get());
122
123
            return true;
124
        } else if (!(noMoveValue.get() && MovementUtils.isMoving()) && (!invOpenValue.get() || mc.currentScreen instanceof GuiInventory) && item != -1) {
125
            final boolean openInventory = simulateInventory.get() && !(mc.currentScreen instanceof GuiInventory);
126
127
            if (openInventory)
128
                mc.getNetHandler().addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.OPEN_INVENTORY_ACHIEVEMENT));
129
130
            mc.playerController.windowClick(mc.thePlayer.inventoryContainer.windowId, isArmorSlot ? item : (item < 9 ? item + 36 : item), 0, 1, mc.thePlayer);
131
132
            delay = TimeUtils.randomDelay(minDelayValue.get(), maxDelayValue.get());
133
134
            if (openInventory)
135
                mc.getNetHandler().addToSendQueue(new C0DPacketCloseWindow());
136
137
            return true;
138
        }
139
        
140
        return false;
141
    }
142
143
}

What this file does

onRender3D is the whole driver: gate checks, armor ranking via the shared ARMOR_COMPARATOR, and the two move() ceremonies. The early returns after each move mean the module sends at most one inventory action per render frame, which the randomized delay plus the CLICK_TIMER gate turn into a paced click train rather than a burst.

source InventoryUtils.java (CLICK_TIMER pacing)

InventoryUtils.java96 lines · JavaOriginal ↗
1
/*
2
 * LiquidBounce Hacked Client
3
 * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
4
 * https://github.com/CCBlueX/LiquidBounce/
5
 */
6
package net.ccbluex.liquidbounce.utils;
7
8
import net.ccbluex.liquidbounce.event.ClickWindowEvent;
9
import net.ccbluex.liquidbounce.event.EventTarget;
10
import net.ccbluex.liquidbounce.event.Listenable;
11
import net.ccbluex.liquidbounce.event.PacketEvent;
12
import net.ccbluex.liquidbounce.utils.timer.MSTimer;
13
import net.minecraft.block.Block;
14
import net.minecraft.init.Blocks;
15
import net.minecraft.item.Item;
16
import net.minecraft.item.ItemBlock;
17
import net.minecraft.item.ItemStack;
18
import net.minecraft.network.Packet;
19
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
20
21
import java.util.Arrays;
22
import java.util.List;
23
24
public final class InventoryUtils extends MinecraftInstance implements Listenable {
25
26
    public static final MSTimer CLICK_TIMER = new MSTimer();
27
    public static final List<Block> BLOCK_BLACKLIST = Arrays.asList(Blocks.enchanting_table, Blocks.chest, Blocks.ender_chest, Blocks.trapped_chest,
28
            Blocks.anvil, Blocks.sand, Blocks.web, Blocks.torch, Blocks.crafting_table, Blocks.furnace, Blocks.waterlily, Blocks.dispenser,
29
            Blocks.stone_pressure_plate, Blocks.wooden_pressure_plate, Blocks.noteblock, Blocks.dropper);
30
31
    public static int findItem(final int startSlot, final int endSlot, final Item item) {
32
        for(int i = startSlot; i < endSlot; i++) {
33
            final ItemStack stack = mc.thePlayer.inventoryContainer.getSlot(i).getStack();
34
35
            if(stack != null && stack.getItem() == item)
36
                return i;
37
        }
38
        return -1;
39
    }
40
41
    public static boolean hasSpaceHotbar() {
42
        for(int i = 36; i < 45; i++) {
43
            final ItemStack itemStack = mc.thePlayer.inventoryContainer.getSlot(i).getStack();
44
45
            if(itemStack == null)
46
                return true;
47
        }
48
        return false;
49
    }
50
51
    public static int findAutoBlockBlock() {
52
        for(int i = 36; i < 45; i++) {
53
            final ItemStack itemStack = mc.thePlayer.inventoryContainer.getSlot(i).getStack();
54
55
            if(itemStack != null && itemStack.getItem() instanceof ItemBlock) {
56
                final ItemBlock itemBlock = (ItemBlock) itemStack.getItem();
57
                final Block block = itemBlock.getBlock();
58
59
                if (block.isFullCube() && !BLOCK_BLACKLIST.contains(block))
60
                    return i;
61
            }
62
        }
63
64
        for(int i = 36; i < 45; i++) {
65
            final ItemStack itemStack = mc.thePlayer.inventoryContainer.getSlot(i).getStack();
66
67
            if(itemStack != null && itemStack.getItem() instanceof ItemBlock) {
68
                final ItemBlock itemBlock = (ItemBlock) itemStack.getItem();
69
                final Block block = itemBlock.getBlock();
70
71
                if (!BLOCK_BLACKLIST.contains(block))
72
                    return i;
73
            }
74
        }
75
76
        return -1;
77
    }
78
79
    @EventTarget
80
    public void onClick(final ClickWindowEvent event) {
81
        CLICK_TIMER.reset();
82
    }
83
84
    @EventTarget
85
    public void onPacket(final PacketEvent event) {
86
        final Packet packet = event.getPacket();
87
88
        if (packet instanceof C08PacketPlayerBlockPlacement)
89
            CLICK_TIMER.reset();
90
    }
91
92
    @Override
93
    public boolean handleEvents() {
94
        return true;
95
    }
96
}

What this file does

The static CLICK_TIMER is the module's rate limiter and the client-wide inventory cooldown. onClick resets it on every ClickWindowEvent and onPacket resets it on any outgoing C08PacketPlayerBlockPlacement, so AutoArmor's hasTimePassed(delay) gate naturally defers to any other module that clicked a window or sent a use-item packet in the meantime.

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 FastClick (window-click ledger)

FastClick.java243 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.inventory;
16
17
import java.util.ArrayList;
18
import java.util.List;
19
20
import org.bukkit.Material;
21
import org.bukkit.entity.Player;
22
import org.bukkit.event.inventory.InventoryClickEvent;
23
import org.bukkit.event.inventory.InventoryType;
24
import org.bukkit.inventory.InventoryView;
25
import org.bukkit.inventory.ItemStack;
26
27
import fr.neatmonster.nocheatplus.actions.ParameterName;
28
import fr.neatmonster.nocheatplus.checks.Check;
29
import fr.neatmonster.nocheatplus.checks.CheckType;
30
import fr.neatmonster.nocheatplus.checks.ViolationData;
31
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
32
import fr.neatmonster.nocheatplus.permissions.Permissions;
33
import fr.neatmonster.nocheatplus.players.IPlayerData;
34
import fr.neatmonster.nocheatplus.utilities.entity.InventoryUtil;
35
import fr.neatmonster.nocheatplus.utilities.StringUtil;
36
import fr.neatmonster.nocheatplus.utilities.TickTask;
37
38
39
/**
40
 * FastClick checks for players clicking in inventories too quickly (nerfs autosteal cheats and the like).
41
 */
42
public class FastClick extends Check {
43
44
45
    final List<String> tags = new ArrayList<String>();
46
47
48
    /**
49
     * Instantiates a new fast click check.
50
     */
51
    public FastClick() {
52
        super(CheckType.INVENTORY_FASTCLICK);
53
    }
54
55
56
   /**
57
    * Checks a player.
58
    * 
59
    * @param player
60
    * @param now Millisec
61
    * @param view
62
    * @param slot
63
    * @param cursor
64
    * @param clicked
65
    * @param isShiftClick
66
    * @param inventoryAction
67
    * @param data
68
    * @param cc 
69
    * @param pData
70
    * @return true, if successful
71
    */
72
    public boolean check(final Player player, final long now, 
73
                         final InventoryClickEvent event, final int slot, final ItemStack cursor, 
74
                         final ItemStack clicked, final boolean isShiftClick, 
75
                         final String inventoryAction, final InventoryData data, final InventoryConfig cc, 
76
                         final IPlayerData pData) {
77
78
        final float amount;
79
        final Material clickedMat = clicked == null ? Material.AIR : clicked.getType();
80
        final Material cursorMat;
81
        final int cursorAmount;
82
        boolean cancel = false;
83
        tags.clear();
84
85
        if (cursor != null) {
86
            cursorMat = cursor.getType();
87
            cursorAmount = Math.max(1, cursor.getAmount());
88
        }
89
        else {
90
            cursorMat = null;
91
            cursorAmount = 0;
92
        }
93
94
        if (inventoryAction != null) {
95
            amount = getAmountWithAction(event, slot, clicked, clickedMat, cursorMat, cursorAmount, isShiftClick, inventoryAction, data, cc);
96
        }
97
        else if (cursor != null) {
98
            // Detect shift-click features indirectly.
99
            amount = detectTweaks1_5(event, slot, clicked, clickedMat, cursorMat, cursorAmount, isShiftClick, data, cc);
100
        }
101
        else amount = 1f;
102
103
        if (isShiftClick && inventoryAction.equals("MOVE_TO_OTHER_INVENTORY") 
104
            && (cursorMat != null && cursorMat != Material.AIR) 
105
            && clickedMat != Material.AIR) {
106
            return false;
107
        }
108
        
109
        // Count clicks
110
        data.fastClickFreq.add(now, amount);
111
        
112
        // Shor-term VL
113
        float shortTerm = data.fastClickFreq.bucketScore(0);
114
        if (shortTerm > cc.fastClickShortTermLimit) {
115
            // Check for lag.
116
            shortTerm /= (float) TickTask.getLag(data.fastClickFreq.bucketDuration(), true);
117
        }
118
        shortTerm -= cc.fastClickShortTermLimit;
119
        
120
        // Normal VL
121
        float normal = data.fastClickFreq.score(1f);
122
        if (normal > cc.fastClickNormalLimit) {
123
            // Check for lag.
124
            normal /= (float) TickTask.getLag(data.fastClickFreq.bucketDuration() * data.fastClickFreq.numberOfBuckets(), true);
125
        }
126
        normal -= cc.fastClickNormalLimit;
127
        
128
        // Process Violations.
129
        final double violation = Math.max(shortTerm, normal);
130
        if (violation > 0.0) {
131
            tags.add("clickspeed");
132
            data.fastClickVL += violation;
133
            final ViolationData vd = new ViolationData(this, player, data.fastClickVL, violation, cc.fastClickActions);
134
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
135
            cancel = executeActions(vd).willCancel();
136
        }
137
        else data.fastClickVL *= 0.99;
138
139
        if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)) {
140
            player.sendMessage("FastClick: " + data.fastClickFreq.bucketScore(0) + " | " + data.fastClickFreq.score(1f) + " | cursor=" + cursor 
141
                                + " | clicked=" + clicked + " | action=" + inventoryAction);
142
        }
143
        
144
        // Adjust data
145
        data.fastClickLastClicked = clickedMat;
146
        data.fastClickLastSlot = slot;
147
        data.fastClickLastCursor = cursorMat;
148
        data.fastClickLastCursorAmount = cursorAmount;
149
150
        // Lastly, always feed the improbable.
151
        if (cc.fastClickImprobableWeight > 0.0f) {
152
            Improbable.feed(player, cc.fastClickImprobableWeight * amount, now);
153
        }
154
        return cancel;
155
    }
156
    
157
158
   /**
159
    * Enforce sane timings for interacting with the container and clicking in it.
160
    * 
161
    * @param player
162
    * @param data
163
    * @param cc
164
    */
165
    public boolean checkContainerInteraction(final Player player, final InventoryData data, final InventoryConfig cc) {
166
        boolean cancel = false;
167
        tags.clear();
168
        if (InventoryUtil.isContainerInteractionRecent(player, cc.chestOpenLimit)) {
169
            // Interaction was too quick, violation.
170
            tags.add("interact_time");
171
            long duration = Math.max(data.lastClickTime - data.containerInteractTime, 20);
172
            double violation = (cc.chestOpenLimit / duration) * 100D; // Normalize.
173
            data.fastClickVL += violation;
174
            final ViolationData vd = new ViolationData(this, player, data.fastClickVL, violation, cc.fastClickActions);
175
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
176
            cancel = executeActions(vd).willCancel();  
177
        }
178
       return cancel;
179
    }
180
    
181
182
   /**
183
    * Detect the inventory tweaks that were introduced in MC 1.5
184
    * 
185
    * @param view
186
    * @param slot
187
    * @param clicked
188
    * @param clickedMat
189
    * @param cursorAmount
190
    * @param isShiftClick
191
    * @param data
192
    * @param cc
193
    */
194
    private float detectTweaks1_5(final InventoryClickEvent event, final int slot, final ItemStack clicked, 
195
                                  final Material clickedMat, final Material cursorMat, 
196
                                  final int cursorAmount, final boolean isShiftClick, 
197
                                  final InventoryData data, final InventoryConfig cc) {
198
199
        if (cursorMat != data.fastClickLastCursor 
200
            && (!isShiftClick || clickedMat == Material.AIR || clickedMat != data.fastClickLastClicked) 
201
            || cursorMat == Material.AIR || cursorAmount != data.fastClickLastCursorAmount) {
202
            return 1f;
203
        }
204
        else if (clickedMat == Material.AIR || clickedMat == cursorMat 
205
                || isShiftClick && clickedMat == data.fastClickLastClicked ) {
206
            return Math.min(cc.fastClickNormalLimit , cc.fastClickShortTermLimit) 
207
                    / (float) (isShiftClick && clickedMat != Material.AIR ? (1.0 + Math.max(cursorAmount, InventoryUtil.getStackCount(event, clicked))) : cursorAmount)  * 0.75f;
208
        }
209
        return 1f;
210
    }
211
212
213
    private float getAmountWithAction(final InventoryClickEvent event, final int slot, final ItemStack clicked, 
214
                                      final Material clickedMat, final Material cursorMat, 
215
                                      final int cursorAmount, final boolean isShiftClick, 
216
                                      final String inventoryAction, 
217
                                      final InventoryData data, final InventoryConfig cc) {
218
219
        // Continuous drop feature with open inventories.
220
        if (inventoryAction.equals("DROP_ONE_SLOT")
221
            && slot == data.fastClickLastSlot 
222
            && clickedMat == data.fastClickLastClicked
223
            && event.getInventory().getType() == InventoryType.CRAFTING
224
            // && InventoryUtil.couldHaveInventoryOpen(player)
225
            // TODO: Distinguish if the inventory is really open.
226
            ) {
227
            return 0.6f;
228
        }
229
230
        // Collect to cursor.
231
        if (inventoryAction.equals("COLLECT_TO_CURSOR")) {
232
            final int stackCount = InventoryUtil.getStackCount(event, clicked);
233
            return stackCount <= 0 ? 1f : Math.min(cc.fastClickNormalLimit , cc.fastClickShortTermLimit) / stackCount * 0.75f;
234
        }
235
236
        // Shift click features.
237
        if ((inventoryAction.equals("MOVE_TO_OTHER_INVENTORY")) && cursorMat != Material.AIR) {
238
            // Let the legacy method do the side condition checks and counting for now.
239
            return detectTweaks1_5(event, slot, clicked, clickedMat, cursorMat, cursorAmount, isShiftClick, data, cc);
240
        }
241
        return 1f;
242
    }
243
}

How it counteracts this module

FastClick scores every C0E into an ActionFrequency(5, 200L) short-term bucket set plus a 15/s normal window, with shift-click MOVE_TO_OTHER_INVENTORY actions discounted through detectTweaks1_5, and feeds Improbable when fastClickImprobableWeight is set. AutoArmor's 100-200ms randomized spacing lands around 5-10 clicks per second, which the short-term buckets forgive, so the real pressure is the container-interaction rule: checkContainerInteraction flags window clicks that arrive without a preceding container-open, exactly the fingerprint of simulateInventory mode on a server that tracks open state.

anticheat InventoryListener (open-state ledger)

InventoryListener.java717 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.inventory;
16
17
import org.bukkit.ChatColor;
18
import org.bukkit.GameMode;
19
import org.bukkit.Location;
20
import org.bukkit.Material;
21
import org.bukkit.entity.Entity;
22
import org.bukkit.entity.HumanEntity;
23
import org.bukkit.entity.LivingEntity;
24
import org.bukkit.entity.Player;
25
import org.bukkit.event.EventHandler;
26
import org.bukkit.event.EventPriority;
27
import org.bukkit.event.block.Action;
28
import org.bukkit.event.block.BlockBreakEvent;
29
import org.bukkit.event.block.BlockPlaceEvent;
30
import org.bukkit.event.entity.EntityDeathEvent;
31
import org.bukkit.event.entity.EntityPortalEnterEvent;
32
import org.bukkit.event.entity.EntityShootBowEvent;
33
import org.bukkit.event.entity.FoodLevelChangeEvent;
34
import org.bukkit.event.inventory.InventoryClickEvent;
35
import org.bukkit.event.inventory.InventoryCloseEvent;
36
import org.bukkit.event.inventory.InventoryEvent;
37
import org.bukkit.event.inventory.InventoryOpenEvent;
38
import org.bukkit.event.inventory.InventoryType;
39
import org.bukkit.event.player.PlayerBedEnterEvent;
40
import org.bukkit.event.player.PlayerBedLeaveEvent;
41
import org.bukkit.event.player.PlayerChangedWorldEvent;
42
import org.bukkit.event.player.PlayerEditBookEvent;
43
import org.bukkit.event.player.PlayerInteractEntityEvent;
44
import org.bukkit.event.player.PlayerInteractEvent;
45
import org.bukkit.event.player.PlayerItemConsumeEvent;
46
import org.bukkit.event.player.PlayerItemHeldEvent;
47
import org.bukkit.event.player.PlayerMoveEvent;
48
import org.bukkit.event.player.PlayerPortalEvent;
49
import org.bukkit.event.player.PlayerRespawnEvent;
50
import org.bukkit.event.player.PlayerTeleportEvent;
51
import org.bukkit.inventory.Inventory;
52
import org.bukkit.inventory.ItemStack;
53
import org.bukkit.inventory.meta.BookMeta;
54
55
import fr.neatmonster.nocheatplus.NCPAPIProvider;
56
import fr.neatmonster.nocheatplus.checks.CheckListener;
57
import fr.neatmonster.nocheatplus.checks.CheckType;
58
import fr.neatmonster.nocheatplus.checks.combined.Combined;
59
import fr.neatmonster.nocheatplus.checks.combined.CombinedData;
60
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
61
import fr.neatmonster.nocheatplus.compat.bukkit.BridgeHealth;
62
import fr.neatmonster.nocheatplus.compat.registry.BukkitAPIAccessFactory;
63
import fr.neatmonster.nocheatplus.compat.BridgeMisc;
64
import fr.neatmonster.nocheatplus.components.NoCheatPlusAPI;
65
import fr.neatmonster.nocheatplus.components.data.ICheckData;
66
import fr.neatmonster.nocheatplus.components.data.IData;
67
import fr.neatmonster.nocheatplus.components.entity.IEntityAccessVehicle;
68
import fr.neatmonster.nocheatplus.components.registry.event.IGenericInstanceHandle;
69
import fr.neatmonster.nocheatplus.components.registry.factory.IFactoryOne;
70
import fr.neatmonster.nocheatplus.components.registry.feature.JoinLeaveListener;
71
import fr.neatmonster.nocheatplus.players.DataManager;
72
import fr.neatmonster.nocheatplus.players.IPlayerData;
73
import fr.neatmonster.nocheatplus.players.PlayerFactoryArgument;
74
import fr.neatmonster.nocheatplus.stats.Counters;
75
import fr.neatmonster.nocheatplus.utilities.entity.InventoryUtil;
76
import fr.neatmonster.nocheatplus.utilities.ReflectionUtil;
77
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
78
import fr.neatmonster.nocheatplus.utilities.math.MathUtil;
79
import fr.neatmonster.nocheatplus.utilities.moving.MovingUtil;
80
import fr.neatmonster.nocheatplus.worlds.WorldFactoryArgument;
81
82
/**
83
 * Central location to listen to events that are relevant for the inventory checks.
84
 * 
85
 * @see InventoryEvent
86
 */
87
public class InventoryListener  extends CheckListener implements JoinLeaveListener {
88
    
89
    // Checks
90
    /** More Inventory check */
91
    private final MoreInventory moreInv = addCheck(new MoreInventory());
92
93
    /** The fast click check. */
94
    private final FastClick fastClick  = addCheck(new FastClick());
95
96
    /** The instant bow check. */
97
    private final InstantBow instantBow = addCheck(new InstantBow());
98
99
    /** The fast consume check. */
100
    private final FastConsume fastConsume = addCheck(new FastConsume());
101
    
102
    private final Gutenberg gutenberg = addCheck(new Gutenberg());
103
    
104
    /** The open check */
105
    private final Open open = addCheck(new Open());
106
    
107
    // Other/Auxiliary stuff
108
    private boolean keepCancel = false;
109
110
    private final boolean hasInventoryAction;
111
112
    /** For temporary use: LocUtil.clone before passing deeply, call setWorld(null) after use. */
113
    private final Location useLoc = new Location(null, 0, 0, 0);
114
115
    private final Counters counters = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstance(Counters.class);
116
117
    private final int idCancelDead = counters.registerKey("cancel.dead");
118
119
    private final IGenericInstanceHandle<IEntityAccessVehicle> handleVehicles = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstanceHandle(IEntityAccessVehicle.class);
120
121
    @SuppressWarnings("unchecked")
122
    public InventoryListener() {
123
        super(CheckType.INVENTORY);
124
        final NoCheatPlusAPI api = NCPAPIProvider.getNoCheatPlusAPI();
125
        api.register(api.newRegistrationContext()
126
                // InventoryConfig
127
                .registerConfigWorld(InventoryConfig.class)
128
                .factory(new IFactoryOne<WorldFactoryArgument, InventoryConfig>() {
129
                    @Override
130
                    public InventoryConfig getNewInstance(
131
                            WorldFactoryArgument arg) {
132
                        return new InventoryConfig(arg.worldData);
133
                    }
134
                })
135
                .registerConfigTypesPlayer()
136
                .context() //
137
                // InventoryData
138
                .registerDataPlayer(InventoryData.class)
139
                .factory(new IFactoryOne<PlayerFactoryArgument, InventoryData>() {
140
                    @Override
141
                    public InventoryData getNewInstance(
142
                            PlayerFactoryArgument arg) {
143
                        return new InventoryData();
144
                    }
145
                })
146
                .addToGroups(CheckType.INVENTORY, true, IData.class, ICheckData.class)
147
                .context() //
148
                );
149
        hasInventoryAction = ReflectionUtil.getClass("org.bukkit.event.inventory.InventoryAction") != null;
150
    }
151
152
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
153
    public void onEntityShootBow(final EntityShootBowEvent event) {
154
        // Only if a player shot the arrow.
155
        if (event.getEntity() instanceof Player) {
156
            final Player player = (Player) event.getEntity();
157
            final IPlayerData pData = DataManager.getPlayerData(player);
158
            if (instantBow.isEnabled(player, pData)) {
159
                final long now = System.currentTimeMillis();
160
                final Location loc = player.getLocation(useLoc);
161
                if (Combined.checkYawRate(player, loc.getYaw(), now, loc.getWorld().getName(), pData)) {
162
                    // No else if with this, could be cancelled due to other checks feeding, does not have actions.
163
                    event.setCancelled(true);
164
                }
165
166
                final InventoryConfig cc = pData.getGenericInstance(InventoryConfig.class);
167
                // Still check instantBow, whatever yawrate says.
168
                if (instantBow.check(player, event.getForce(), now)) {
169
                    event.setCancelled(true);
170
                }
171
                else if (cc.instantBowImprobableWeight > 0.0f) {
172
                    if (cc.instantBowImprobableFeedOnly) {
173
                        Improbable.feed(player, cc.instantBowImprobableWeight, now);
174
                    }
175
                    else if (Improbable.check(player, cc.instantBowImprobableWeight, now, "inventory.instantbow", pData)) {
176
                        // Combined fighting speed (Else if: Matter of taste, preventing extreme cascading and actions spam).
177
                        event.setCancelled(true);
178
                    }
179
                }
180
                useLoc.setWorld(null);
181
            }  
182
        }
183
    }
184
185
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
186
    public void onFoodLevelChange(final FoodLevelChangeEvent event) {
187
        // Only if a player ate food.
188
        if (event.getEntity() instanceof Player) {
189
            final Player player = (Player) event.getEntity();
190
            if (player.isDead() && BridgeHealth.getHealth(player) <= 0.0) {
191
                // Eat after death.
192
                event.setCancelled(true);
193
                counters.addPrimaryThread(idCancelDead, 1);
194
            }
195
        }
196
    }
197
198
    @EventHandler(priority = EventPriority.LOWEST)
199
    public void onInventoryClick(final InventoryClickEvent event) {
200
        if (!(event.getWhoClicked() instanceof Player)) {
201
            return;
202
        }
203
        final long now = System.currentTimeMillis();
204
        final HumanEntity entity = event.getWhoClicked();
205
        if (!(entity instanceof Player)) {
206
            return;
207
        }
208
        final Player player = (Player) entity;
209
        final IPlayerData pData = DataManager.getPlayerData(player);
210
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
211
        final int slot = event.getSlot();
212
        final String inventoryAction = hasInventoryAction ? event.getAction().name() : null;
213
        final InventoryConfig cc = pData.getGenericInstance(InventoryConfig.class);
214
        if (pData.isDebugActive(checkType)) {
215
            outputDebugInventoryClick(player, slot, event, inventoryAction);
216
        }
217
        // Set this one as soon as we can and regardless if the click was cancelled or not.
218
        if (data.inventoryOpenTime == 0) {
219
            data.inventoryOpenTime = now;
220
            if (pData.isDebugActive(CheckType.INVENTORY)) {
221
                debug(player, "InventoryClickEvent: inventory wasn't explicitly open previously but an inventory click was sent; register time of the 1st click (assume inventory is open from this moment on)");
222
            }
223
        }
224
        if (event.isCancelled()) {
225
            // Previously: ignoreCancelled = true
226
            // We still want to know if the player clicked in the inventory (even if cancelled) for the inventory-open estimate above.
227
            return;
228
        }
229
        if (slot == -999 || slot < 0) {
230
            // Set and return, not interested in these clicks.
231
            data.lastClickTime = now;
232
            return;
233
        }
234
235
        final ItemStack cursor = event.getCursor();
236
        final ItemStack clicked = event.getCurrentItem();
237
        boolean cancel = false;
238
        // Fast inventory manipulation check.
239
        if (fastClick.isEnabled(player, pData)) {
240
            if (!((event.getInventory().getType().equals(InventoryType.CREATIVE) || player.getGameMode() == GameMode.CREATIVE) && cc.fastClickSpareCreative)) {
241
                boolean check = true;
242
                try {
243
                    // Exempted inventories are not checked.
244
                    check = !cc.inventoryExemptions.contains(ChatColor.stripColor(BukkitAPIAccessFactory.getBukkitAccess().getInventoryTitle(event)));
245
                }
246
                catch (IllegalStateException e) {
247
                    // Uhm... Can this ISE be fixed?
248
                    check = true; 
249
                }
250
                
251
                if (check) {
252
                    // Check for too quick interactions first (we don't need to check for fast clicking if the interaction is inhumanly fast)
253
                    if (InventoryUtil.isContainerInventory(event.getInventory().getType())
254
                        && fastClick.checkContainerInteraction(player, data, cc)) {
255
                        cancel = true;
256
                        keepCancel = true;
257
                    }
258
                    // Then check for too fast inventory clicking
259
                    if (!cancel && fastClick.check(player, now, event, slot, cursor, clicked, event.isShiftClick(), inventoryAction, data, cc, pData)) {  
260
                        cancel = true;
261
                    }
262
                }
263
            }
264
        }
265
        
266
        data.lastClickTime = now;
267
        data.clickedSlotType = event.getSlotType();
268
        // Cancel the event.
269
        if (cancel || keepCancel) {
270
            event.setCancelled(true);
271
        }
272
    }
273
    
274
    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
275
    public void onEditingABook(final PlayerEditBookEvent event) {
276
        final Player player = event.getPlayer();
277
        if (!gutenberg.isEnabled(player)) {
278
            return;
279
        }
280
        final IPlayerData pData = DataManager.getPlayerData(player);
281
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
282
        final BookMeta newMeta = event.getNewBookMeta();
283
        final int pages = newMeta.getPageCount();
284
        if (gutenberg.check(player, data, pData, pages)) {
285
        	event.setCancelled(true);
286
        }
287
    }
288
289
    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
290
    public void onConsumingFoodOrPotions(final PlayerItemConsumeEvent event){
291
        final Player player = event.getPlayer();
292
        if (player.isDead() && BridgeHealth.getHealth(player) <= 0.0) {
293
            // Eat after death.
294
            event.setCancelled(true);
295
            counters.addPrimaryThread(idCancelDead, 1);
296
            return;
297
        }
298
        final IPlayerData pData = DataManager.getPlayerData(player);
299
        if (!fastConsume.isEnabled(player)) {
300
            return;
301
        }
302
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
303
        final long time = System.currentTimeMillis();
304
        if (fastConsume.check(player, event.getItem(), time, data, pData)) {
305
            event.setCancelled(true);
306
            DataManager.getPlayerData(player).requestUpdateInventory();
307
        }
308
    }
309
    
310
    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
311
    public void onClosingAnyInventory(final InventoryCloseEvent event) {
312
        // NOTE: ignoreCancelled is kept to true here. Cancelled events won't reset data.
313
        // NOTE: Priority level -> same as opening time.
314
        final HumanEntity entity = event.getPlayer();
315
        if (entity instanceof Player) {
316
            final Player player = (Player) entity;
317
            final IPlayerData pData = DataManager.getPlayerData(player);
318
            final InventoryData data = pData.getGenericInstance(InventoryData.class);
319
            data.inventoryOpenTime = 0;
320
            data.containerInteractTime = 0;
321
            if (pData.isDebugActive(CheckType.INVENTORY)) {
322
                debug(player, "InventoryCloseEvent: reset timing data.");
323
            }
324
        }
325
        keepCancel = false;
326
    }
327
328
    @EventHandler(priority = EventPriority.LOWEST)
329
    public final void onPlayerInteract(final PlayerInteractEvent event) {
330
        final Player player = event.getPlayer();
331
        final IPlayerData pData = DataManager.getPlayerData(player);
332
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
333
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
334
        // Set the container opening time.
335
        if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null
336
            // Sneaking and right clicking with a block in hand will cause the player to place the block down, not to open the container.
337
            && !(BridgeMisc.isUsingItem(player) || pData.isShiftKeyPressed() && event.isBlockInHand())) {
338
            if (BlockProperties.isContainer(event.getClickedBlock().getType())) {
339
                data.containerInteractTime = System.currentTimeMillis();
340
                if (pData.isDebugActive(CheckType.INVENTORY)) {
341
                    debug(player, "Interacted with a container: register the interaction time.");
342
                }
343
            }
344
        } 
345
        // Only interested in right-clicks while holding an item.
346
        if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) {
347
            return;
348
        }
349
        
350
        boolean resetAll = false;
351
        if (event.hasItem()) {
352
            final ItemStack item = event.getItem();
353
            final Material type = item.getType();
354
            // TODO: Get Magic values (800) from the config.
355
            // TODO: Cancelled / deny use item -> reset all?
356
            if (type == Material.BOW) {
357
                final long now = System.currentTimeMillis();
358
                // It was a bow, the player starts to pull the string, remember this time.
359
                data.instantBowInteract = (data.instantBowInteract > 0 && now - data.instantBowInteract < 800) ? Math.min(System.currentTimeMillis(), data.instantBowInteract) : System.currentTimeMillis();
360
            }
361
            else if (InventoryUtil.isConsumable(type)) {
362
                final long now = System.currentTimeMillis();
363
                // It was food, the player starts to eat some food, remember this time and the type of food.
364
                data.fastConsumeFood = type;
365
                data.fastConsumeInteract = (data.fastConsumeInteract > 0 && now - data.fastConsumeInteract < 800) ? Math.min(System.currentTimeMillis(), data.fastConsumeInteract) : System.currentTimeMillis();
366
                data.instantBowInteract = 0; 
367
            } 
368
            else resetAll = true;
369
        }
370
        else resetAll = true;
371
372
        if (resetAll) {
373
            // Nothing that we are interested in, reset data.
374
            data.instantBowInteract = 0;
375
            data.fastConsumeInteract = 0;
376
            data.fastConsumeFood = null;
377
        }
378
    }
379
    
380
    // TODO: Why is this handler inside the INVENTORY listener!?
381
    @EventHandler(priority = EventPriority.LOWEST)
382
    public final void onPlayerInteractEntity(final PlayerInteractEntityEvent event) {
383
        final Player player = event.getPlayer();
384
        if (player.getGameMode() == GameMode.CREATIVE || !DataManager.getPlayerData(player).isCheckActive(CheckType.INVENTORY, player)) {
385
            return;
386
        }
387
        if (player.isDead() && BridgeHealth.getHealth(player) <= 0.0) {
388
            // No zombies.
389
            event.setCancelled(true);
390
            counters.addPrimaryThread(idCancelDead, 1);
391
            return;
392
        }
393
        else if (MovingUtil.hasScheduledPlayerSetBack(player)) {
394
            event.setCancelled(true);
395
            return;
396
        }
397
    }
398
    
399
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
400
    public final void onContainerOpen(final InventoryOpenEvent event) {
401
        // Possibly already prevented by block + entity interaction.
402
        // NOTE: ignoreCancelled is kept true. Denied openings won't register timing data.
403
        final long now = System.currentTimeMillis();
404
        final HumanEntity entity = event.getPlayer();
405
        if (entity instanceof Player) {
406
            final Player player = (Player) entity;
407
            final IPlayerData pData = DataManager.getPlayerData(player);
408
            final InventoryData data = pData.getGenericInstance(InventoryData.class);
409
            if (MovingUtil.hasScheduledPlayerSetBack(player)) {
410
                // Don't allow players to open inventories on set-backs.
411
                event.setCancelled(true);
412
                data.inventoryOpenTime = 0; // Just to be sure
413
                if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
414
                    debug(player, "InventoryOpenEvent: attempted to open a container during set back processing; reset timing data and prevent opening.");
415
                }
416
            }
417
            else if (data.inventoryOpenTime == 0) {
418
                // Only set the inventory opening time, if a setback is not scheduled.
419
                data.inventoryOpenTime = now;
420
                 if (pData.isDebugActive(CheckType.INVENTORY)) {
421
                    debug(player, "Fired an explicit InventoryOpenEvent; inventory is now open (no assumptions): register time.");
422
                }
423
            }
424
        }
425
    }
426
427
    @EventHandler(priority = EventPriority.MONITOR)
428
    public void onItemHeldChange(final PlayerItemHeldEvent event) {
429
        final Player player = event.getPlayer();
430
        final IPlayerData pData = DataManager.getPlayerData(player);
431
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
432
        if (pData.isDebugActive(checkType) && data.fastConsumeFood != null) {
433
            debug(player, "PlayerItemHeldEvent, reset fastconsume.");
434
        }
435
        data.instantBowInteract = 0;
436
        data.fastConsumeInteract = System.currentTimeMillis();
437
        data.fastConsumeFood = null;
438
        if (event.getPreviousSlot() != event.getNewSlot()) {
439
            if (open.check(player)) {
440
                if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
441
                    debug(player, "Force-close inventory on changing slots.");
442
                }
443
            }
444
        }   
445
    }
446
    
447
    @EventHandler(priority = EventPriority.MONITOR)
448
    public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) {
449
        // Data is reset regardless of cancellation state (better safe than sorry)
450
        final Player player = event.getPlayer();
451
        final IPlayerData pData = DataManager.getPlayerData(player);
452
        if (open.check(event.getPlayer())) {
453
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
454
                debug(player, "Force-close inventory on changing worlds.");
455
            }
456
        }
457
    }
458
459
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
460
    public void onBreakingBlocks(final BlockBreakEvent event) {
461
        final Player player = event.getPlayer();
462
        final IPlayerData pData = DataManager.getPlayerData(player);
463
        // Can't break blocks with inventory open.
464
        if (open.check(event.getPlayer())) {
465
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
466
                debug(player, "Force-close inventory on breaking blocks (cheat prevention).");
467
            }
468
        }
469
    }
470
471
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
472
    public void onPlacingBlocks(final BlockPlaceEvent event) {
473
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
474
        // Can't place blocks with inventory open.
475
        if (open.check(event.getPlayer())) {
476
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
477
                debug(event.getPlayer(), "Force-close inventory on placing blocks (cheat prevention).");
478
            }
479
        }
480
    }
481
    
482
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
483
    public void onPlayerPortal(final PlayerPortalEvent event) {
484
        // Note: ignore cancelother setting.
485
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
486
        if (open.check(event.getPlayer())) {
487
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
488
                debug(event.getPlayer(), "Force-close inventory on using a portal.");
489
            }
490
        }
491
    }
492
    
493
    @EventHandler(priority = EventPriority.MONITOR)
494
    public void onPlayerRespawn(final PlayerRespawnEvent event) {
495
        // NOTE: Data is reset regardless of cancellation state (better safe than sorry)
496
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
497
        if (open.check(event.getPlayer())) {
498
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
499
                debug(event.getPlayer(), "Force-close inventory on respawning.");
500
            }
501
        }
502
    }
503
    
504
    @EventHandler(priority = EventPriority.MONITOR)
505
    public void onPlayerDeath(final EntityDeathEvent event) {
506
        // NOTE: Data is reset regardless of cancellation state (better safe than sorry)
507
        final LivingEntity entity = event.getEntity();
508
        if (entity instanceof Player) {
509
            final Player player = (Player) entity;
510
            final IPlayerData pData = DataManager.getPlayerData(player);
511
            if (open.check(player)) {
512
                if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
513
                    debug(player, "Force-close inventory on death.");
514
                }
515
            }
516
        }
517
    }
518
    
519
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
520
    public void onPlayerSleep(final PlayerBedEnterEvent event) {
521
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
522
        if (open.check(event.getPlayer())) {
523
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
524
                debug(event.getPlayer(), "Force-close inventory on sleeping.");
525
            }
526
        }
527
    }
528
529
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
530
    public void onPlayerWake(final PlayerBedLeaveEvent event) {
531
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
532
        if (open.check(event.getPlayer())) {
533
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
534
                debug(event.getPlayer(), "Force-close inventory on waking up.");
535
            }
536
        }
537
    }
538
    
539
    // Check even if cancelled
540
    // (Players swing their arm when dropping items.)
541
    // @EventHandler(priority = EventPriority.MONITOR)
542
    // public void onSwingingArm(final PlayerAnimationEvent event) {
543
    //     final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
544
    //     if (open.check(event.getPlayer())) {
545
    //         if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
546
    //             debug(event.getPlayer(), "Force-close inventory on swinging arm (cheat prevention).");
547
    //         }
548
    //     }
549
    // }
550
551
    @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
552
    public void onEntityPortal(final EntityPortalEnterEvent event) {
553
        // Check passengers flat for now.
554
        final Entity entity = event.getEntity();
555
        if (entity instanceof Player) {
556
            final IPlayerData pData = DataManager.getPlayerData((Player) entity);
557
            if (open.check((Player) entity)) {
558
                if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
559
                    debug((Player) entity, "Force-close inventory on using a portal (entity).");
560
                }
561
            }
562
        }
563
        else {
564
            for (final Entity passenger : handleVehicles.getHandle().getEntityPassengers(entity)) {
565
                if (passenger instanceof Player) {
566
                	final IPlayerData pData = DataManager.getPlayerData((Player) entity);
567
                    if (open.check((Player) passenger)) {
568
                        if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
569
                            debug((Player) passenger, "Force-close inventory of passenger on using a portal, passenger: " + passenger.toString());
570
                        }
571
                    }
572
                }
573
            }
574
        }
575
    }
576
    
577
    /** Event priority must be set to priority used for moving checks due using moving data from there */
578
    @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
579
    public void onPlayerMove(final PlayerMoveEvent event) {
580
        final Location from = event.getFrom();
581
        final Location to = event.getTo();
582
        final boolean PoYdiff = from.getPitch() != to.getPitch() || from.getYaw() != to.getYaw();
583
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
584
        if (MovingUtil.hasScheduledPlayerSetBack(event.getPlayer())) {
585
            // On 1.8 set back technique is different, as we do not cancel the event.
586
            return;
587
        }
588
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
589
        final InventoryConfig cc = pData.getGenericInstance(InventoryConfig.class);
590
        final Inventory inv = BukkitAPIAccessFactory.getBukkitAccess().getTopInventory(event.getPlayer());
591
        boolean moreInvCheck = false;
592
        if (moreInv.isEnabled(event.getPlayer(), pData) 
593
            && moreInv.check(event.getPlayer(), cData, pData, inv.getType(), inv, PoYdiff)) {
594
            for (int i = 1; i <= 4; i++) {
595
                final ItemStack item = inv.getItem(i);
596
                // Ensure air-clicking is not detected... :)
597
                if (item != null && !BlockProperties.isAir(item.getType())) {
598
                    // NOTE: dropItemsNaturally does not fire InvDrop events, so don't use it here. Simply close the inventory,
599
                    event.getPlayer().closeInventory(); // Do not call Open.checkClose() here, as it checks for if the inventory is open again, and we're not interested in that.
600
                    if (pData.isDebugActive(CheckType.INVENTORY_MOREINVENTORY)) {
601
                        debug(event.getPlayer(), "On PlayerMoveEvent: force-close inventory on MoreInv detection.");
602
                    }
603
                    moreInvCheck = true;
604
                    break;
605
                }
606
            }
607
        }
608
        if (moreInvCheck) {
609
            // Already closed inventory; no need to also check for open-on-move.
610
            return;
611
        }
612
        // Determine if the inventory should be closed.
613
        if (cc.openCancelOnMove && !pData.hasBypass(CheckType.INVENTORY_OPEN, event.getPlayer())) {
614
            if (InventoryUtil.hasInventoryOpen(event.getPlayer()) && open.checkOnMove(event.getPlayer(), pData)) {
615
                event.getPlayer().closeInventory(); // Do not call open.check() here. <- Uhm... Why did I write this note?
616
                if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
617
                    debug(event.getPlayer(), "Player is actively moving: force-close open inventory.");
618
                }
619
            }
620
        }
621
    }
622
    
623
    @EventHandler(priority = EventPriority.MONITOR)
624
    public void onPlayerTeleport(final PlayerTeleportEvent event) {
625
        // NOTE: Data is reset regardless of cancellation state (better safe than sorry)
626
        final IPlayerData pData = DataManager.getPlayerData(event.getPlayer());
627
        if (open.check(event.getPlayer())) {
628
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
629
                debug(event.getPlayer(), "Force-close inventory on teleporting.");
630
            }
631
        }
632
    }
633
634
    @Override
635
    public void playerJoins(Player player) {
636
        // Just to be sure...
637
        final IPlayerData pData = DataManager.getPlayerData(player);
638
        final InventoryData data = pData.getGenericInstance(InventoryData.class);
639
        data.inventoryOpenTime = 0;
640
        if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
641
            debug(player, "Reset inventory timings data on join.");
642
        }
643
    }
644
645
    @Override
646
    public void playerLeaves(Player player) {
647
        final IPlayerData pData = DataManager.getPlayerData(player);
648
        if (open.check(player)) {
649
            if (pData.isDebugActive(CheckType.INVENTORY_OPEN)) {
650
                debug(player, "Force-close inventory on leaving the server.");
651
            }
652
        }
653
    }
654
655
    /**
656
     * Debug inventory classes. Contains information about classes, to indicate
657
     * if cross-plugin compatibility issues can be dealt with easily.
658
     * 
659
     * @param player
660
     * @param slot
661
     * @param event
662
     */
663
    private void outputDebugInventoryClick(final Player player, final int slot, final InventoryClickEvent event, 
664
                                           final String action) {
665
        // TODO: Consider only logging where different from expected (CraftXY, more/other viewer than player). 
666
667
        final StringBuilder builder = new StringBuilder(512);
668
        final InventoryData data = DataManager.getPlayerData(player).getGenericInstance(InventoryData.class);
669
        builder.append("Inventory click: slot: " + slot);
670
        builder.append(" , Inventory has been opened for: " + MathUtil.toSeconds(System.currentTimeMillis() - data.inventoryOpenTime) + " secs");
671
        builder.append(" , Time between inventory click and last interaction time: " + MathUtil.toSeconds(data.lastClickTime - data.containerInteractTime) + " secs");
672
673
        // Viewers.
674
        builder.append(" , Viewers: ");
675
        for (final HumanEntity entity : event.getViewers()) {
676
            builder.append(entity.getName());
677
            builder.append("(");
678
            builder.append(entity.getClass().getName());
679
            builder.append(")");
680
        }
681
682
        // Inventory view.
683
        builder.append(" , View: ");
684
        //final InventoryView view = BridgeBukkitAPI.getInventoryView(event);
685
        //builder.append(view.getClass().getName());
686
687
        // Bottom inventory.
688
        addInventory(BukkitAPIAccessFactory.getBukkitAccess().getBottomInventory(event), BukkitAPIAccessFactory.getBukkitAccess().getInventoryTitle(event), " , Bottom: ", builder);
689
690
        // Top inventory.
691
        addInventory(BukkitAPIAccessFactory.getBukkitAccess().getTopInventory(event), BukkitAPIAccessFactory.getBukkitAccess().getInventoryTitle(event), " , Top: ", builder);
692
        
693
        if (action != null) {
694
            builder.append(" , Action: ");
695
            builder.append(action);
696
        }
697
698
        // Event class.
699
        builder.append(" , Event: ");
700
        builder.append(event.getClass().getName());
701
702
        // Log debug.
703
        debug(player, builder.toString());
704
    }
705
706
    private void addInventory(final Inventory inventory, final String name, final String prefix, final StringBuilder builder) {
707
        builder.append(prefix);
708
        if (inventory == null) {
709
            builder.append("(none)");
710
        }
711
        else {
712
            builder.append(name);
713
            builder.append("/");
714
            builder.append(inventory.getClass().getName());
715
        }
716
    }
717
}

How it counteracts this module

NCP's first-click heuristic stamps inventoryOpenTime on the first click and assumes the window is open from that moment, which is precisely the fiction simulateInventory mode fabricates with its C16/C0D pair. The Open check force-closes on any break, place or interact while the ledger believes a window is open, so the C0D close packet races the ledger: a close NCP never saw leaves the open state behind, and the next window-0 click is scored against an unopened window.

anticheat InventoryActions (window-0 click punishment)

InventoryActions.java60 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.interaction.inventory;
20
21
/*
22
 * InventoryActions check originally written by Havesta; modified, split apart, and implemented into Hawk by Islandscout
23
 *
24
 * InventoryActions checks if a player is
25
 * - interacting with entities/blocks while inventory is opened
26
 */
27
28
import me.islandscout.hawk.HawkPlayer;
29
import me.islandscout.hawk.check.CustomCheck;
30
import me.islandscout.hawk.event.*;
31
32
public class InventoryActions extends CustomCheck {
33
34
    public InventoryActions() {
35
        super("inventoryactions", true, 3, 5, 0.999, 5000, "%player% failed inventory-actions, VL: %vl%", null);
36
    }
37
38
    @Override
39
    protected void check(Event e) {
40
        HawkPlayer pp = e.getHawkPlayer();
41
42
        //player tried to interact with entities/world while an inventory window is open
43
        if(pp.hasInventoryOpen() != 0 && (e instanceof InteractEntityEvent || e instanceof BlockDigEvent ||
44
                e instanceof ArmSwingEvent || e instanceof InteractWorldEvent)) {
45
            punish(pp, true, e);
46
            e.resync();
47
            //TODO After failing several times, there's a chance that they could be legit, but the inventory state is glitched. Close the player's inventory.
48
        }
49
50
        //player tried to interact with inventory while it is closed
51
        else if(pp.hasInventoryOpen() == 0 && e instanceof ClickInventoryEvent) {
52
            //TODO also check that window ID makes sense with the window type (eg. ID 0 must mean hasInventoryOpen() == 0)
53
            punish(pp, true, e);
54
            e.resync();
55
        }
56
        else {
57
            reward(pp);
58
        }
59
    }
60
}

How it counteracts this module

Hawk punishes a ClickInventoryEvent whenever hasInventoryOpen() is 0, so the C0E shift-clicks of the window path are a direct hit when no GUI is open: the check raises VL and calls e.resync(), which undoes the local armor swap by re-syncing the inventory and defeats the equip in the same tick. The hotbar path evades it completely because it never opens a window, which is the honest bypass surface to note.

anticheat InventoryEvent (click runner feed)

InventoryEvent.java55 lines · Java
1
package ai.idealistic.spartan.listeners.bukkit.standalone;
2
3
import ai.idealistic.spartan.abstraction.inventory.InventoryMenu;
4
import ai.idealistic.spartan.abstraction.protocol.PlayerProtocol;
5
import ai.idealistic.spartan.functionality.concurrent.CheckThread;
6
import ai.idealistic.spartan.functionality.server.MultiVersion;
7
import ai.idealistic.spartan.functionality.server.PluginBase;
8
import ai.idealistic.spartan.utils.java.StringUtils;
9
import ai.idealistic.spartan.utils.minecraft.world.BlockUtils;
10
import org.bukkit.entity.Player;
11
import org.bukkit.event.EventHandler;
12
import org.bukkit.event.EventPriority;
13
import org.bukkit.event.Listener;
14
import org.bukkit.event.inventory.ClickType;
15
import org.bukkit.event.inventory.InventoryClickEvent;
16
import org.bukkit.event.player.PlayerDropItemEvent;
17
import org.bukkit.inventory.ItemStack;
18
19
public class InventoryEvent implements Listener {
20
21
    @EventHandler(priority = EventPriority.HIGHEST)
22
    private void ItemDrop(PlayerDropItemEvent e) {
23
        PlayerProtocol p = PluginBase.getProtocol(e.getPlayer(), true);
24
        CheckThread.run(null, () -> p.executeRunners(e.isCancelled(), e));
25
    }
26
27
    @EventHandler(priority = EventPriority.HIGHEST)
28
    private void InventoryClick(InventoryClickEvent e) {
29
        ItemStack item = e.getCurrentItem();
30
31
        if (BlockUtils.hasMaterial(item)) {
32
            Player n = (Player) e.getWhoClicked();
33
            PlayerProtocol p = PluginBase.getProtocol(n, true);
34
            CheckThread.run(null, () -> p.executeRunners(false, e));
35
36
            if (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) {
37
                ClickType click = e.getClick();
38
                String title = p.getOpenInventoryTitle("");
39
40
                if (MultiVersion.isOrGreater(MultiVersion.MCVersion.V1_13)) {
41
                    title = StringUtils.getClearColorString(title);
42
                }
43
                int slot = e.getSlot();
44
45
                for (InventoryMenu menu : PluginBase.menus) {
46
                    if (menu.handle(p, title, item, click, slot)) {
47
                        e.setCancelled(true);
48
                        break;
49
                    }
50
                }
51
            }
52
        }
53
    }
54
55
}

How it counteracts this module

Spartan routes every InventoryClickEvent into p.executeRunners, feeding the INVENTORY_CLICKS and IMPOSSIBLE_INVENTORY checks registered in CheckEnums. The per-check executor classes are absent from the clone, so thresholds are not quotable, but the listener is the feed that would classify the window-0 shift-clicks, and the C16-achievement open is the anomaly it sees first.

← Back to Analysis Hub