Memeware 7.3 Auto Armor module 2 files, 142 lines

Memeware 7.3 Auto Armor: Full Source Analysis

Memeware's Auto Armor is a 110-line inventory-equip module with a structural flaw that shapes everything it does: the protection-value comparison in change() never reads the candidate item, so the module cannot rank armor at all.

me/memewaredevs/client/module/combat/AutoArmor.java · GitHub source ↗

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

Analysis

Overview

Memeware's Auto Armor is a 110-line inventory-equip module with a structural flaw that shapes everything it does: the protection-value comparison in change() never reads the candidate item, so the module cannot rank armor at all. Each pre-update tick it processes one armor slot (helmet, chestplate, leggings, boots in a fixed 5-8 rotation) and shift-clicks the first matching piece it finds into that slot - but only while the slot is empty, because the comparison evaluates the armor slot's own stack against itself. The 500ms Timer gate is a one-shot latch rather than a period (delay() never resets and the module never calls reset()), so after the first half-second the handler fires every tick, cycling all four slots in four ticks. Every equip is a pair of windowClick calls on window 0 - slot 5-8 first to strip a worn piece, then the inventory slot - which becomes a burst of two C0EPacketClickWindow packets in the same 50ms tick, emitted with no GUI screen open and no C09 held-slot sync, because this fork's windowClick dropped the syncCurrentPlayItem call.

The broken ranker

change(armorSlot, slot) fetches the stack currently in the armor slot and computes protVal from that stack only; the candidate in the inventory slot is never passed to getProtValue. The guard protVal <= getProtValue(stack) && protVal != getProtValue(stack) therefore compares the running max (or the armor slot's own value) against the armor slot's own value. When the armor slot is empty, protVal starts at -1.0 and the guard passes for the first candidate, pinning item to that slot and maxValue to 0.0; every later candidate fails because 0.0 <= 0.0 is false. When the armor slot holds a piece, protVal equals its value and the guard is false for every candidate. Net effect: the enchantment-weighted getProtValue formula (damageReduceAmount plus a 0.0075-scaled Protection bonus) is dead code, and the module fills an empty armor slot with whatever matching piece happens to be scanned first - lowest-scan-order wins, iron before diamond if the iron is in an earlier slot.

Timer latch and per-tick cadence

The Timer field is constructed once when the module instance is created (client startup) and Auto Armor never calls reset(). Timer.delay(500) is a pure comparison of now against the constructor-stamped prevMS with no side effect, so it returns true for every update after the first 500ms of client uptime. The handler therefore runs on every pre-update tick: it walks slots 9-44, finds the first piece whose canEquip() result equals the current num, shift-clicks it into place, and advances num (5 -> 8 -> 5). With all four armor slots empty, the module equips a full set in four consecutive ticks rather than the two seconds the 500ms constant suggests. The isPost() early return keeps the swap in the pre phase, so the two windowClick calls - and the two C0E packets they emit - land back-to-back inside one tick.

Wire signature

windowClick(0, num, 0, 1, player) sends C0EPacketClickWindow with windowId 0, slotId 5-8, button 0, mode 1 (SHIFT_CLICK); windowClick(0, item, 0, 1, player) sends a second C0E with the inventory slot. The first click only fires when the armor slot is occupied, so a bare equip is one C0E and a replace is two - but because the ranker never replaces, the two-click pair appears only when the module briefly strips and re-equips, which its own logic prevents. The fork's PlayerControllerMP.windowClick no longer calls syncCurrentPlayItem, so no C09PacketHeldItemChange accompanies the clicks; the whole operation is pure C0E traffic on window 0, issued while mc.currentScreen is null and openContainer.windowId is 0. The open-window guard (windowId != 0) means the module never clicks a real chest, so every C0E it emits carries the closed-inventory signature that anticheats key on.

source AutoArmor.java (module)

AutoArmor.java111 lines · JavaOriginal ↗
1
2
package me.memewaredevs.client.module.combat;
3
4
import me.hippo.api.lwjeb.annotation.Handler;
5
import me.memewaredevs.client.event.events.UpdateEvent;
6
import me.memewaredevs.client.module.Module;
7
import me.memewaredevs.client.util.misc.Timer;
8
import net.minecraft.enchantment.Enchantment;
9
import net.minecraft.enchantment.EnchantmentHelper;
10
import net.minecraft.item.Item;
11
import net.minecraft.item.ItemArmor;
12
import net.minecraft.item.ItemStack;
13
14
import java.util.function.Consumer;
15
16
public class AutoArmor extends Module {
17
    private static final int[] HELMET = new int[]{310, 306, 314, 302, 298};
18
    private static final int[] CHESTPLATE = new int[]{311, 307, 315, 303, 299};
19
    private static final int[] LEGGINGS = new int[]{312, 308, 316, 304, 300};
20
    private static final int[] BOOTS = new int[]{313, 309, 317, 305, 301};
21
22
    private Timer timer = new Timer();
23
    private int num = 5;
24
    private double maxValue = -1.0;
25
    private double protVal;
26
    private int item = -1;
27
28
    public AutoArmor() {
29
        super("Auto Armor", 0, Module.Category.COMBAT);
30
    }
31
32
33
    @Handler
34
    public Consumer<UpdateEvent> update = e -> {
35
        if (e.isPost())
36
            return;
37
        if (mc.thePlayer.capabilities.isCreativeMode
38
                || mc.thePlayer.openContainer != null && mc.thePlayer.openContainer.windowId != 0) {
39
            return;
40
        }
41
        if (timer.delay(500L)) {
42
            maxValue = -1.0;
43
            item = -1;
44
            for (int i = 9; i < 45; ++i) {
45
                if (mc.thePlayer.inventoryContainer.getSlot(i).getStack() == null
46
                        || canEquip(mc.thePlayer.inventoryContainer.getSlot(i).getStack()) == -1
47
                        || canEquip(mc.thePlayer.inventoryContainer.getSlot(i).getStack()) != num) {
48
                    continue;
49
                }
50
                change(num, i);
51
            }
52
            if (item != -1) {
53
                if (mc.thePlayer.inventoryContainer.getSlot(item).getStack() != null) {
54
                    mc.playerController.windowClick(0, num, 0, 1, mc.thePlayer);
55
                }
56
                mc.playerController.windowClick(0, item, 0, 1, mc.thePlayer);
57
            }
58
            num = num == 8 ? 5 : ++num;
59
        }
60
    };
61
62
    private int canEquip(ItemStack stack) {
63
        for (int id : BOOTS) {
64
            if (Item.getIdFromItem(stack.getItem()) != id) {
65
                continue;
66
            }
67
            return 8;
68
        }
69
        for (int id : LEGGINGS) {
70
            if (Item.getIdFromItem(stack.getItem()) != id) {
71
                continue;
72
            }
73
            return 7;
74
        }
75
        for (int id : CHESTPLATE) {
76
            if (Item.getIdFromItem(stack.getItem()) != id) {
77
                continue;
78
            }
79
            return 6;
80
        }
81
        for (int id : HELMET) {
82
            if (Item.getIdFromItem(stack.getItem()) != id) {
83
                continue;
84
            }
85
            return 5;
86
        }
87
        return -1;
88
    }
89
90
    private void change(int armorSlot, int slot) {
91
        ItemStack stack = mc.thePlayer.inventoryContainer.getSlot(armorSlot).getStack();
92
        protVal = maxValue == -1.0 ? stack != null
93
                ? getProtValue(stack)
94
                : maxValue : maxValue;
95
        if (protVal <= getProtValue(stack)
96
                && protVal != getProtValue(stack)) {
97
            item = slot;
98
            maxValue = getProtValue(stack);
99
        }
100
    }
101
102
    private double getProtValue(ItemStack stack) {
103
        if (stack != null) {
104
            return ((ItemArmor) stack.getItem()).damageReduceAmount
105
                    + (100 - ((ItemArmor) stack.getItem()).damageReduceAmount * 4)
106
                    * EnchantmentHelper.getEnchantmentLevel(Enchantment.field_180310_c.effectId, stack) * 4
107
                    * 0.0075;
108
        }
109
        return 0.0;
110
    }
111
}

What this file does

The module is one @Handler Consumer on UpdateEvent (lines 33-60). The gate at line 37 bails in creative mode or when openContainer.windowId differs from 0, so window clicks only ever target the player container. The timer check at line 41 is the one-shot latch described above - delay(500) with no reset anywhere in the class. The scan loop (lines 44-51) iterates container slots 9-44, skips empty stacks, items whose canEquip() returns -1, and items whose armor slot does not match the current num, then calls change(num, i). Lines 52-57 perform the equip: the first windowClick(0, num, 0, 1) strips the occupied armor slot, the second windowClick(0, item, 0, 1) shift-clicks the found piece in. Line 58 advances the rotation. canEquip (lines 62-88) maps item IDs to armor slots via the four tier-ordered arrays (BOOTS 8, LEGGINGS 7, CHESTPLATE 6, HELMET 5) - the array order (diamond, gold, iron, chain, leather) is irrelevant because only the slot is returned. change() (lines 90-100) contains the self-comparison bug: it evaluates the armor slot's own stack, so only the first candidate is ever selected and occupied slots are never upgraded. getProtValue (lines 102-110) computes the damage-reduction-plus-Protection rating that the buggy comparison never actually applies to a candidate.

source Timer.java (cadence gate)

Timer.java31 lines · JavaOriginal ↗
1
2
package me.memewaredevs.client.util.misc;
3
4
public class Timer {
5
    private long prevMS = 0L;
6
7
    public Timer() {
8
        this.reset();
9
    }
10
11
    public boolean delay(final float milliSec) {
12
        return this.getTime() - this.prevMS >= milliSec;
13
    }
14
15
    public void reset() {
16
        this.prevMS = this.getTime();
17
    }
18
19
    public long getTime() {
20
        return System.nanoTime() / 1000000L;
21
    }
22
23
    public boolean sleep(long time) {
24
	    if (getTime() >= time) {
25
	      reset();
26
	      return true;
27
	    } 
28
	    return false;
29
	  }
30
31
}

What this file does

The Timer is a plain wall-clock comparator. The constructor resets prevMS to the current millis (nanoTime / 1e6), and delay(milliSec) returns true once getTime() - prevMS passes the threshold - with no reset side effect. Auto Armor relies on this as a 500ms period but never calls reset(), so the gate fires once 500ms after module construction and stays open; only AutoPotion, which calls reset() before arming its throw, gets a real period out of this class. The same Timer backs Memeware's other combat modules, which is why their cadences differ despite sharing the class. The sleep() helper is unused by Auto Armor.

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 (C0E click-rate 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

NoCheatPlus scores every inventory click into a frequency ledger instead of trusting the client's timing. InventoryListener.onInventoryClick routes each Bukkit InventoryClickEvent into FastClick.check, which stamps data.fastClickFreq with an amount-weighted sample: plain clicks count 1f, shift-clicks and COLLECT_TO_CURSOR actions are discounted through detectTweaks1_5/getAmountWithAction, and the same bucket feeds Improbable when fastClickImprobableWeight is configured. Two windows are scored - the newest short-term bucket against fastClickShortTermLimit and the full window against fastClickNormalLimit - with lag division and a VL that decays by 0.99 on clean buckets. Auto Armor's traffic is exactly the shape this ledger was built to absorb: each equip is one or two SHIFT_CLICK C0Es (action MOVE_TO_OTHER_INVENTORY) emitted in the same tick, and the per-tick rotation means consecutive clicks land in adjacent 50ms windows. The raw rate - up to eight C0Es per second across a full four-slot equip - stays under most short-term limits, so the click-speed branch alone is lenient; what the module cannot shed is the ledger's side effects: every click extends the interaction history and feeds Improbable, and checkContainerInteraction ties click timing to container-open timing, which the module's window-0 clicks never legitimately satisfy because no container open event precedes them.

anticheat InventoryActions (clicks with inventory closed)

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's InventoryActions enforces the window state contract around clicks. The check punishes any ClickInventoryEvent while HawkPlayer.hasInventoryOpen() reports 0 - the player clicked a window the server never saw opened - and conversely punishes world interactions (InteractEntity, BlockDig, ArmSwing, InteractWorld) while a window is open. The first branch is a direct hit on Auto Armor: the module clicks window 0 from the pre-update handler with mc.currentScreen null, so hasInventoryOpen() is 0 for every one of its C0Es. A single punish(pp, true, e) (VL +1, cancellable) plus e.resync() follows; resync forces the client back into the server's inventory state, undoing the local armor swap the module just performed and desynchronizing its own scan on the next tick - the client re-reads slots from the sync it was just forced to accept. The check's 5-second reward decay (0.999 per tick) means the module's sustained every-tick click stream accumulates VL steadily while a legit player who only clicks an actually-open inventory stays clean.

anticheat InventoryListener (inventory-open estimation)

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 inventory listener maintains the open/closed state that its checks trust. onInventoryClick (line 199) treats the first click as authoritative: when data.inventoryOpenTime is 0 it stamps the current time with the explicit debug comment 'assume inventory is open from this moment on' - a heuristic designed for exactly the situation Auto Armor creates, where C0Es arrive with no InventoryOpenEvent before them. onContainerOpen only sets inventoryOpenTime for real opens, onInventoryClose resets it, and the Open check force-closes the window when the player breaks blocks, places blocks or interacts while the ledger says it is open. The module's window-0 clicks therefore fabricate the open state the Open check then polices: the listener's first-click assumption marks the inventory as open, and every subsequent world interaction - attacking, mining, placing - while the module keeps clicking feeds the forced-close path, which cancels the interaction and requests an inventory resync. The C0E pair in a single tick also means lastClickTime is stamped twice within 50ms, tightening the container-interaction timing check checkContainerInteraction feeds from.

anticheat InventoryEvent (click dispatch into check runners)

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's inventory click surface is a Bukkit listener that funnels every InventoryClickEvent into the check framework: InventoryClick() runs p.executeRunners(false, e) on the check thread for any click carrying a material, which is the entry point for the INVENTORY_CLICKS and IMPOSSIBLE_INVENTORY detections registered in CheckEnums (the same runner pipeline the click-pattern checks consume). The second half of the handler intercepts clicks on Spartan's own menu items (InventoryMenu.handle) - the anti-management-UI path that any click stream, including Auto Armor's, must traverse before Spartan's per-click checks see it. For the module, the relevant property is that every window-0 C0E is delivered to executeRunners as a genuine click with its slot, cursor and click-type intact; the module's back-to-back SHIFT_CLICK pair arrives as two consecutive runner invocations in the same tick, which is the input pattern the inventory-click detections are structured to examine, and the closed-window origin of those clicks is visible to the protocol layer even though this listener alone does not classify it.

← Back to Analysis Hub