LiquidSense Dev HitBox module 2 files, 224 lines

LiquidSense Dev HitBox: Full Source Analysis

LiquidSense Dev's HitBox is a value holder with one job: inflate the client-side collision border of every entity so the mouse-over ray trace treats targets as bigger than they are.

net/ccbluex/liquidbounce/features/module/modules/combat/HitBox.kt · GitHub source ↗

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

Packets This Module Uses

Analysis

Overview

LiquidSense Dev's HitBox is a value holder with one job: inflate the client-side collision border of every entity so the mouse-over ray trace treats targets as bigger than they are. The module itself only registers a Size FloatValue (default 0.4, range 0 to 1); the effect lives in a Forge mixin, MixinEntity.getCollisionBorderSize, which returns 0.1F plus the Size value whenever the module is enabled. Vanilla EntityLivingBase returns a fixed 0.1F border, and the client's EntityRenderer expands each entity's bounding box by that border on all three axes before ray tracing for the mouse-over target. At the default Size the border becomes 0.5 blocks per axis, so the effective box the client aims against grows to roughly 1.6 wide and 2.6 tall, which lets attacks register at larger angular offsets and at eye-to-surface distances the real box cannot support. The module never sends a packet itself: the inflated box only decides which C02 attacks the player's own clicks or a killaura will send, and because a vanilla 1.8 server trusts the client's hit detection entirely, those attacks land.

Module and mixin split

HitBox.kt is two statements: the ModuleInfo header and the sizeValue declaration. All behavior is in MixinEntity, where an injection at the head of getCollisionBorderSize grabs the module instance through LiquidBounce.moduleManager, checks getState(), and returns 0.1F plus sizeValue when enabled. The vanilla method returns 0.1F for EntityLivingBase, so the returned border spans 0.1 (Size 0) to 1.1 (Size 1) and defaults to 0.5. The mixin class also carries unrelated injections (setAngles, moveFlying, a StrafeEvent hook) that do not participate in the hitbox mechanic.

Where the border bites

In 1.8.9 the client's mouse-over scan expands every entity's bounding box by getCollisionBorderSize() on the x, y and z axes before calling calculateIntercept with the look ray, and the ray trace distance is capped by the block-reach distance (4.5 survival). A larger border therefore does two things: it widens the angular envelope the look ray can intersect, and it pushes the intersectable surface outward along the ray, so a target whose real box is beyond vanilla reach becomes hittable up to the 4.5 cap. The attack path needs no further client-side distance validation: PlayerControllerMP.attackEntity trusts the mouse-over result, and the C02 it sends names the victim with no geometry at all.

Server-side asymmetry

None of the expansion transfers to the server. The server tracks the standard 0.6-wide player box, and every anticheat in this corpus rebuilds that box from packets or Bukkit state rather than trusting the client. A hit that only exists because of the inflated border is therefore a hit against geometry the server does not have: ray-trace checks fail against the real box, and distance checks measure eye to the real box center, which the border does not move. The module's practical value is aim forgiveness for killaura rotations that would otherwise miss the real box, at the cost of making every such hit a server-side reach or hitbox violation.

source HitBox.kt (module)

HitBox.kt16 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.features.module.Module
9
import net.ccbluex.liquidbounce.features.module.ModuleCategory
10
import net.ccbluex.liquidbounce.features.module.ModuleInfo
11
import net.ccbluex.liquidbounce.value.FloatValue
12
13
@ModuleInfo(name = "HitBox", description = "Makes hitboxes of targets bigger.", category = ModuleCategory.COMBAT)
14
class HitBox : Module() {
15
    val sizeValue = FloatValue("Size", 0.4F, 0F, 1F)
16
}

What this file does

The whole module is the Size setting. sizeValue is a FloatValue named Size with default 0.4, minimum 0 and maximum 1, and the ModuleInfo header names the category COMBAT. There is no event handler and no packet code: the module only exists to be read by the mixin. The default 0.4 is significant because it is the same expansion a 0.1 border plus the value produces at the default, so a stock install already attacks against a 0.5-per-axis envelope.

source MixinEntity.java (border injection)

MixinEntity.java208 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.injection.forge.mixins.entity;
7
8
import net.ccbluex.liquidbounce.LiquidBounce;
9
import net.ccbluex.liquidbounce.event.StrafeEvent;
10
import net.ccbluex.liquidbounce.features.module.modules.combat.HitBox;
11
import net.minecraft.block.Block;
12
import net.minecraft.block.material.Material;
13
import net.minecraft.client.Minecraft;
14
import net.minecraft.crash.CrashReportCategory;
15
import net.minecraft.entity.Entity;
16
import net.minecraft.util.AxisAlignedBB;
17
import net.minecraft.util.BlockPos;
18
import net.minecraft.util.Vec3;
19
import net.minecraft.world.World;
20
import net.minecraftforge.fml.relauncher.Side;
21
import net.minecraftforge.fml.relauncher.SideOnly;
22
import org.spongepowered.asm.mixin.Mixin;
23
import org.spongepowered.asm.mixin.Shadow;
24
import org.spongepowered.asm.mixin.injection.At;
25
import org.spongepowered.asm.mixin.injection.Inject;
26
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
27
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
28
29
import java.util.Random;
30
import java.util.UUID;
31
32
@Mixin(Entity.class)
33
@SideOnly(Side.CLIENT)
34
public abstract class MixinEntity {
35
36
    @Shadow
37
    public double posX;
38
39
    @Shadow
40
    public double posY;
41
42
    @Shadow
43
    public double posZ;
44
45
    @Shadow
46
    public abstract boolean isSprinting();
47
48
    @Shadow
49
    public float rotationPitch;
50
51
    @Shadow
52
    public float rotationYaw;
53
54
    @Shadow
55
    public abstract AxisAlignedBB getEntityBoundingBox();
56
57
    @Shadow
58
    public Entity ridingEntity;
59
60
    @Shadow
61
    public double motionX;
62
63
    @Shadow
64
    public double motionY;
65
66
    @Shadow
67
    public double motionZ;
68
69
    @Shadow
70
    public boolean onGround;
71
72
    @Shadow
73
    public boolean isAirBorne;
74
75
    @Shadow
76
    public boolean noClip;
77
78
    @Shadow
79
    public World worldObj;
80
81
    @Shadow
82
    public void moveEntity(double x, double y, double z) {
83
    }
84
85
    @Shadow
86
    public boolean isInWeb;
87
88
    @Shadow
89
    public float stepHeight;
90
91
    @Shadow
92
    public boolean isCollidedHorizontally;
93
94
    @Shadow
95
    public boolean isCollidedVertically;
96
97
    @Shadow
98
    public boolean isCollided;
99
100
    @Shadow
101
    public float distanceWalkedModified;
102
103
    @Shadow
104
    public float distanceWalkedOnStepModified;
105
106
    @Shadow
107
    public abstract boolean isInWater();
108
109
    @Shadow
110
    protected Random rand;
111
112
    @Shadow
113
    public int fireResistance;
114
115
    @Shadow
116
    protected boolean inPortal;
117
118
    @Shadow
119
    public int timeUntilPortal;
120
121
    @Shadow
122
    public float width;
123
124
    @Shadow
125
    public abstract boolean isRiding();
126
127
    @Shadow
128
    public abstract void setFire(int seconds);
129
130
    @Shadow
131
    protected abstract void dealFireDamage(int amount);
132
133
    @Shadow
134
    public abstract boolean isWet();
135
136
    @Shadow
137
    public abstract void addEntityCrashInfo(CrashReportCategory category);
138
139
    @Shadow
140
    protected abstract void doBlockCollisions();
141
142
    @Shadow
143
    protected abstract void playStepSound(BlockPos pos, Block blockIn);
144
145
    @Shadow
146
    public abstract void setEntityBoundingBox(AxisAlignedBB bb);
147
148
    @Shadow
149
    private int nextStepDistance;
150
151
    @Shadow
152
    private int fire;
153
154
    @Shadow
155
    public float prevRotationPitch;
156
157
    @Shadow
158
    public float prevRotationYaw;
159
160
    @Shadow
161
    protected abstract Vec3 getVectorForRotation(float pitch, float yaw);
162
163
    @Shadow
164
    public abstract UUID getUniqueID();
165
166
    @Shadow
167
    public abstract boolean isSneaking();
168
169
    @Shadow
170
    public abstract boolean isInsideOfMaterial(Material materialIn);
171
172
    public int getNextStepDistance() {
173
        return nextStepDistance;
174
    }
175
176
    public void setNextStepDistance(int nextStepDistance) {
177
        this.nextStepDistance = nextStepDistance;
178
    }
179
180
    public int getFire() {
181
        return fire;
182
    }
183
184
    @Inject(method = "getCollisionBorderSize", at = @At("HEAD"), cancellable = true)
185
    private void getCollisionBorderSize(final CallbackInfoReturnable<Float> callbackInfoReturnable) {
186
        final HitBox hitBox = (HitBox) LiquidBounce.moduleManager.getModule(HitBox.class);
187
188
        if (hitBox.getState())
189
            callbackInfoReturnable.setReturnValue(0.1F + hitBox.getSizeValue().get());
190
    }
191
192
    @Inject(method = "setAngles", at = @At("HEAD"), cancellable = true)
193
    private void setAngles(final float yaw, final float pitch, final CallbackInfo callbackInfo) {
194
195
    }
196
197
    @Inject(method = "moveFlying", at = @At("HEAD"), cancellable = true)
198
    private void handleRotations(float strafe, float forward, float friction, final CallbackInfo callbackInfo) {
199
        if ((Entity) (Object) this != Minecraft.getMinecraft().thePlayer)
200
            return;
201
202
        final StrafeEvent strafeEvent = new StrafeEvent(strafe, forward, friction);
203
        LiquidBounce.eventManager.callEvent(strafeEvent);
204
205
        if (strafeEvent.isCancelled())
206
            callbackInfo.cancel();
207
    }
208
}

What this file does

The injection at getCollisionBorderSize is where the module takes effect. It resolves the HitBox module by class, and when the module is enabled it overrides the return value with 0.1F plus the Size value, replacing the vanilla 0.1F border. Every consumer of the border, most importantly the EntityRenderer mouse-over expansion, then sees the inflated value. The same file holds the module's rotation hooks, which are unrelated to hitbox sizing.

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 Reach (eye-to-box distance)

Reach.java372 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.fight;
16
17
18
import org.bukkit.GameMode;
19
import org.bukkit.Location;
20
import org.bukkit.entity.EnderDragon;
21
import org.bukkit.entity.Entity;
22
import org.bukkit.entity.Giant;
23
import org.bukkit.entity.LivingEntity;
24
import org.bukkit.entity.Player;
25
import org.bukkit.util.Vector;
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.checks.moving.location.tracking.LocationTrace.ITraceEntry;
33
import fr.neatmonster.nocheatplus.permissions.Permissions;
34
import fr.neatmonster.nocheatplus.players.IPlayerData;
35
import fr.neatmonster.nocheatplus.utilities.StringUtil;
36
import fr.neatmonster.nocheatplus.utilities.TickTask;
37
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
38
39
/**
40
 * The Reach check will find out if a player interacts with something that's too far away.
41
 */
42
public class Reach extends Check {
43
44
    /** The maximum distance allowed to interact with an entity in creative mode. */
45
    public static final double CREATIVE_DISTANCE = 6D;
46
47
48
    /** Additum for distance, based on entity. */
49
    private static double getDistMod(final Entity damaged) {
50
        // Handle the EnderDragon differently.
51
        if (damaged instanceof EnderDragon)
52
            return 6.5D;
53
        else if (damaged instanceof Giant){
54
            return 1.5D;
55
        }
56
        else return 0;
57
    }
58
59
60
    /**
61
     * Instantiates a new reach check.
62
     */
63
    public Reach() {
64
        super(CheckType.FIGHT_REACH);
65
    }
66
67
68
    /**
69
     * "Classic" check.
70
     * 
71
     * @param player
72
     *            the player
73
     * @param damaged
74
     *            the damaged
75
     * @return true, if successful
76
     */
77
    public boolean check(final Player player, final Location pLoc, 
78
                         final Entity damaged, final boolean damagedIsFake, final Location dRef, 
79
                         final FightData data, final FightConfig cc, final IPlayerData pData) {
80
81
        boolean cancel = false;
82
        // The maximum distance allowed to interact with an entity in survival mode.
83
        final double SURVIVAL_DISTANCE = cc.reachSurvivalDistance; 
84
        // Amount which can be reduced by reach adaption.
85
        final double DYNAMIC_RANGE = cc.reachReduceDistance; 
86
        // Adaption amount for dynamic range.
87
        final double DYNAMIC_STEP = cc.reachReduceStep / SURVIVAL_DISTANCE; 
88
        final double distanceLimit = player.getGameMode() == GameMode.CREATIVE ? CREATIVE_DISTANCE : SURVIVAL_DISTANCE + getDistMod(damaged);
89
        final double distanceMin = (distanceLimit - DYNAMIC_RANGE) / distanceLimit;
90
        final double height = damagedIsFake ? (damaged instanceof LivingEntity ? ((LivingEntity) damaged).getEyeHeight() : 1.75) : mcAccess.getHandle().getHeight(damaged);
91
        final double width = damagedIsFake ? 0.6 : mcAccess.getHandle().getWidth(damaged);
92
        double centertoedge = 0.0;
93
        
94
        if (cc.reachPrecision) {
95
            centertoedge = getinset(pLoc, dRef, width / 2, 0.0);
96
        }
97
98
        // Refine y position.
99
        final double pY = pLoc.getY() + player.getEyeHeight();
100
        final double dY = dRef.getY();
101
        if (pY <= dY) {
102
            // Keep the foot level y.
103
        } 
104
        // Highest ref y
105
        else if (pY >= dY + height) {
106
             dRef.setY(dY + height);
107
        }
108
        // Level with damaged.
109
        else dRef.setY(pY);
110
111
        final Vector pRel = dRef.toVector().subtract(pLoc.toVector().setY(pY)); // TODO: Run calculations on numbers only :p.
112
        // Distance is calculated from eye location to center of targeted. If the player is further away from their target
113
        // than allowed, the difference will be assigned to "distance".
114
        final double lenpRel = pRel.length() - centertoedge;
115
        double violation = lenpRel - distanceLimit;
116
        final double reachMod = data.reachMod; 
117
118
119
        if (violation > 0) {
120
            if (TickTask.getLag(1000, true) < 1.5f){ // Do not increase the vl in case of server lag (1.5 is a magic value)
121
                data.reachVL += violation;
122
                final ViolationData vd = new ViolationData(this, player, data.reachVL, violation, cc.reachActions);
123
                vd.setParameter(ParameterName.REACH_DISTANCE, StringUtil.fdec3.format(lenpRel));
124
                // Execute whatever actions are associated with this check and the violation level and find out if we should
125
                // cancel the event.
126
                cancel = executeActions(vd).willCancel();
127
            }
128
129
            if (Improbable.check(player, (float) violation / 2f, System.currentTimeMillis(), "fight.reach", pData)){
130
                cancel = true;
131
            }
132
133
            if (cancel && cc.reachPenalty > 0){
134
                // Apply an attack penalty time.
135
                data.attackPenalty.applyPenalty(cc.reachPenalty);
136
            }
137
        }
138
        else if (lenpRel - distanceLimit * reachMod > 0){
139
            // Silent cancel.
140
            if (cc.reachPenalty > 0) {
141
                data.attackPenalty.applyPenalty(cc.reachPenalty / 2);
142
            }
143
            cancel = true;
144
            Improbable.feed(player, (float) (lenpRel - distanceLimit * reachMod) / 4f, System.currentTimeMillis());
145
        }
146
        else data.reachVL *= 0.8D; // Player passed the check, reward them.
147
            
148
149
        if (!cc.reachReduce){
150
            data.reachMod = 1d;
151
        }
152
        else if (lenpRel > distanceLimit - DYNAMIC_RANGE){
153
            data.reachMod = Math.max(distanceMin, data.reachMod - DYNAMIC_STEP);
154
        }
155
        else data.reachMod = Math.min(1.0, data.reachMod + DYNAMIC_STEP);
156
157
        if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)){
158
            player.sendMessage("NC+: Attack/reach " + damaged.getType()+ " height="+ StringUtil.fdec3.format(height) + " dist=" + StringUtil.fdec3.format(lenpRel) +" @" + StringUtil.fdec3.format(reachMod));
159
        }
160
161
        return cancel;
162
    }
163
164
    /**
165
     * Data context for iterating over ITraceEntry instances.
166
     * @param player
167
     * @param pLoc
168
     * @param damaged
169
     * @param damagedLoc
170
     * @param data
171
     * @param cc
172
     * @return
173
     */
174
    public ReachContext getContext(final Player player, final Location pLoc, 
175
                                   final Entity damaged, final Location damagedLoc, 
176
                                   final FightData data, final FightConfig cc) {
177
178
        final ReachContext context = new ReachContext();
179
        context.distanceLimit = player.getGameMode() == GameMode.CREATIVE ? CREATIVE_DISTANCE : cc.reachSurvivalDistance + getDistMod(damaged);
180
        context.distanceMin = (context.distanceLimit - cc.reachReduceDistance) / context.distanceLimit;
181
        //context.eyeHeight = player.getEyeHeight();
182
        context.pY = pLoc.getY() + player.getEyeHeight();
183
        return context;
184
    }
185
186
    /**
187
     * Check if the player fails the reach check, no change of FightData.
188
     * @param player
189
     * @param pLoc
190
     * @param damaged
191
     * @param dRef
192
     * @param context
193
     * @param data
194
     * @param cc
195
     * @return
196
     */
197
    public boolean loopCheck(final Player player, final Location pLoc, final Entity damaged, 
198
                             final ITraceEntry dRef, final ReachContext context, 
199
                             final FightData data, final FightConfig cc) {
200
201
        boolean cancel = false;
202
203
        // Refine y position.
204
        final double dY = dRef.getY();
205
        double y = dRef.getY();
206
207
        if (context.pY <= dY) {
208
            // Keep the foot level y.
209
        }
210
        else if (context.pY >= dY + dRef.getBoxMarginVertical()) {
211
            y = dY + dRef.getBoxMarginVertical(); // Highest ref y.
212
        }
213
        else {
214
            y = context.pY; // Level with damaged.
215
        }
216
217
        double centertoedge = 0.0;
218
        if (cc.reachPrecision) centertoedge = getinset(pLoc, new Location(null, dRef.getX(), dRef.getY(), dRef.getZ()), dRef.getBoxMarginHorizontal(), y - context.pY);
219
        
220
        // Distance is calculated from eye location to center of targeted. If the player is further away from their target
221
        // than allowed, the difference will be assigned to "distance".
222
        // TODO: Run check on squared distances (quite easy to change to stored boundary-sq values).
223
        final double lenpRel = TrigUtil.distance(dRef.getX(), y, dRef.getZ(), pLoc.getX(), context.pY, pLoc.getZ()) - centertoedge;
224
        double violation = lenpRel - context.distanceLimit;
225
226
        if (violation > 0 || lenpRel - context.distanceLimit * data.reachMod > 0){
227
            // TODO: The silent cancel parts should be sen as "no violation" ?
228
            // Set minimum violation in context
229
            context.minViolation = Math.min(context.minViolation, lenpRel);
230
            cancel = true;
231
        }
232
        context.minResult = Math.min(context.minResult, lenpRel);
233
234
        return cancel;
235
236
    }
237
238
    /**
239
     * Apply changes to FightData according to check results (context), trigger violations.
240
     * @param player
241
     * @param pLoc
242
     * @param damaged
243
     * @param context
244
     * @param forceViolation
245
     * @param data
246
     * @param cc
247
     * @return
248
     */
249
    public boolean loopFinish(final Player player, final Location pLoc, final Entity damaged, 
250
                              final ReachContext context, final ITraceEntry traceEntry, final boolean forceViolation, 
251
                              final FightData data, final FightConfig cc, final IPlayerData pData) {
252
253
        final double lenpRel = forceViolation && context.minViolation != Double.MAX_VALUE ? context.minViolation : context.minResult;
254
255
        if (lenpRel == Double.MAX_VALUE) {
256
            return false;
257
        }
258
259
        double violation = lenpRel - context.distanceLimit;
260
        boolean cancel = false;
261
262
        if (violation > 0) {    
263
            if (TickTask.getLag(1000, true) < 1.5f){
264
                data.reachVL += violation;
265
                final ViolationData vd = new ViolationData(this, player, data.reachVL, violation, cc.reachActions);
266
                vd.setParameter(ParameterName.REACH_DISTANCE, StringUtil.fdec3.format(lenpRel));
267
                // Execute whatever actions are associated with this check and the violation level and find out if we should
268
                // cancel the event.
269
                cancel = executeActions(vd).willCancel();
270
            }
271
            
272
            //if (Improbable.check(player, (float) violation / 2f, System.currentTimeMillis(), 
273
            //        "fight.reach", pData)){
274
            //    cancel = true;
275
            //}
276
            // TODO: New improbable weight calculations so that weight is not inverse to config weight
277
            if (cc.reachImprobableWeight > 0.0f) {
278
                if (!cc.reachImprobableFeedOnly && Improbable.check(player, (float) violation / cc.reachImprobableWeight, System.currentTimeMillis(), "fight.reach", pData)) {
279
                    cancel = true;
280
                }
281
            }
282
283
            if (cancel && cc.reachPenalty > 0){
284
                // Apply an attack penalty time.
285
                data.attackPenalty.applyPenalty(cc.reachPenalty);
286
            }
287
        }
288
        else if (lenpRel - context.distanceLimit * data.reachMod > 0){
289
            // Silent cancel.
290
            if (cc.reachPenalty > 0) {
291
                data.attackPenalty.applyPenalty(cc.reachPenalty / 2);
292
            }
293
294
            cancel = true;
295
296
            if (cc.reachImprobableWeight > 0.0f) {
297
                Improbable.feed(player, (float) (lenpRel - context.distanceLimit * data.reachMod) / cc.reachImprobableWeight, System.currentTimeMillis());
298
            }
299
            // Improbable.feed(player, (float) (lenpRel - context.distanceLimit * data.reachMod) / 4f, System.currentTimeMillis());
300
        }
301
        else {
302
            // Player passed the check, reward them.
303
            data.reachVL *= 0.8D;
304
305
        }
306
307
        // Adaption amount for dynamic range.
308
        final double DYNAMIC_STEP = cc.reachReduceStep / cc.reachSurvivalDistance;
309
310
        if (!cc.reachReduce){
311
            data.reachMod = 1d;
312
        }
313
        else if (lenpRel > context.distanceLimit - cc.reachReduceDistance){
314
            data.reachMod = Math.max(context.distanceMin, data.reachMod - DYNAMIC_STEP);
315
        }
316
        else {
317
            data.reachMod = Math.min(1.0, data.reachMod + DYNAMIC_STEP);
318
        }
319
320
        if (pData.isDebugActive(type) && pData.hasPermission(Permissions.ADMINISTRATION_DEBUG, player)){
321
            // TODO: Height: remember successful ITraceEntry
322
            player.sendMessage("NC+: Attack/reach " + damaged.getType()+ (traceEntry == null ? "" : (" height=" + traceEntry.getBoxMarginVertical())) + " dist=" + StringUtil.fdec3.format(lenpRel) +" @" + StringUtil.fdec3.format(data.reachMod));
323
        }
324
325
        return cancel;
326
    }
327
328
329
    private boolean isSameXZ(final Location loc1, final Location loc2) {
330
        return loc1.getX() == loc2.getX() && loc1.getZ() == loc2.getZ();
331
    }
332
333
334
    /**
335
     *
336
     * @param pLoc
337
     *            the player location
338
     * @param dRef
339
     *            the target location
340
     * @param damagedBoxMarginHorizontal
341
     *            the target Width / 2
342
     * @param diffY the Y different
343
     * @return the double represent for the distance from target location to the edge of target hitbox
344
     */
345
    private double getinset(final Location pLoc, final Location dRef, final double damagedBoxMarginHorizontal, final double diffY) {
346
347
        if (!isSameXZ(pLoc, dRef)) {
348
            final Location dRefc = dRef.clone();
349
            final Vector vec1 = new Vector(pLoc.getX() - dRef.getX(), diffY , pLoc.getZ() - dRef.getZ());
350
            if (vec1.length() < damagedBoxMarginHorizontal * Math.sqrt(2)) return 0.0;
351
            if (vec1.getZ() > 0.0) {
352
                dRefc.setZ(dRefc.getZ() + damagedBoxMarginHorizontal);
353
            } 
354
            else if (vec1.getZ() < 0.0) {
355
                dRefc.setZ(dRefc.getZ() - damagedBoxMarginHorizontal);
356
            } 
357
            else if (vec1.getX() > 0.0) {
358
                dRefc.setX(dRefc.getX() + damagedBoxMarginHorizontal);
359
            } 
360
            else dRefc.setX(dRefc.getX() - damagedBoxMarginHorizontal);
361
362
            final Vector vec2 = new Vector(dRefc.getX() - dRef.getX(), 0.0 , dRefc.getZ() - dRef.getZ());
363
            double angle = TrigUtil.angle(vec1, vec2);
364
            // Require < 45deg, if not 90deg-angel
365
            if (angle > Math.PI / 4) angle = Math.PI / 2 - angle;
366
            if (angle >= 0.0 && angle <= Math.PI / 4) { // TODO: Dose this one necessary?
367
                return damagedBoxMarginHorizontal / Math.cos(angle);
368
            }
369
        }
370
        return 0.0;
371
    }
372
}

How it counteracts this module

NoCheatPlus measures each attack against the real server-side geometry. The check computes the distance from the attacker's eye to the damaged entity's clamped position, subtracts centertoedge, a getinset half-width derived from the box, and compares the result with the survival distance limit (default 4.02 in DefaultConfig). The reachMod mechanism shrinks the allowed band after repeated hits near the limit, and the silent-cancel branch below distanceLimit times reachMod cancels borderline attacks without raising a public violation. The client's inflated border does not move the server-side box: a hit that only exists because the border pushed the intersectable surface outward still measures eye to the real center, so the 4.02 ceiling applies unchanged, and the module's corner-shot attacks at the 4.5 mouse-over cap flag directly.

anticheat FightHitbox (lag-compensated ray trace)

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

How it counteracts this module

Hawk re-validates the hit on the server using the victim's real hitbox. On an InteractEntityEvent it stores the interaction, then on the next MoveEvent it builds the attacker's ray from the eye position and the yaw and pitch carried by that move (1.8 sends the attack before the yaw update, so the trace waits for the follow-up move), rewinds the victim to the lag-compensated position, and intersects the ray against WrappedEntity.getHitbox, the standard 0.6-wide box expanded only by a 0.005 epsilon. The inflated client border is irrelevant to this geometry: attacks that only register because the client box extends past the real one miss the intersection and earn the Did not hit hitbox. punishment, and hits that do intersect measure beyond the 3.1 maxReach (4.2 with the 1.9 creative bonus) earn a reach punish. The occluding check adds a BlockIterator when enabled, so through-wall hits from the expanded box also fail.

anticheat Reach (packet-entity ray trace)

Reach.java404 lines · Java
1
// This file was designed and is an original check for GrimAC
2
// Copyright (C) 2021 DefineOutside
3
//
4
// This program is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// This program is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
package ac.grim.grimac.checks.impl.combat;
17
18
import ac.grim.grimac.api.config.ConfigManager;
19
import ac.grim.grimac.api.storage.verbose.Verbose;
20
import ac.grim.grimac.checks.Check;
21
import ac.grim.grimac.checks.CheckData;
22
import ac.grim.grimac.checks.type.PacketReceiveListener;
23
import ac.grim.grimac.player.GrimPlayer;
24
import ac.grim.grimac.utils.collisions.datatypes.SimpleCollisionBox;
25
import ac.grim.grimac.utils.data.packetentity.PacketEntity;
26
import ac.grim.grimac.utils.data.packetentity.PacketEntitySizeable;
27
import ac.grim.grimac.utils.data.packetentity.dragon.PacketEntityEnderDragonPart;
28
import ac.grim.grimac.utils.math.Vector3dm;
29
import ac.grim.grimac.utils.nmsutil.ReachUtils;
30
import ac.grim.grimac.utils.viaversion.ViaVersionUtil;
31
import com.github.retrooper.packetevents.PacketEvents;
32
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
33
import com.github.retrooper.packetevents.manager.server.ServerVersion;
34
import com.github.retrooper.packetevents.protocol.attribute.Attributes;
35
import com.github.retrooper.packetevents.protocol.component.ComponentTypes;
36
import com.github.retrooper.packetevents.protocol.component.builtin.item.ItemAttackRange;
37
import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
38
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
39
import com.github.retrooper.packetevents.protocol.item.ItemStack;
40
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
41
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
42
import com.github.retrooper.packetevents.protocol.player.GameMode;
43
import com.github.retrooper.packetevents.protocol.player.InteractionHand;
44
import com.github.retrooper.packetevents.util.Vector3d;
45
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientAttack;
46
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientInteractEntity;
47
import com.viaversion.viaversion.api.Via;
48
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
49
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
50
import org.jetbrains.annotations.NotNull;
51
52
import java.util.ArrayList;
53
import java.util.Arrays;
54
import java.util.Collections;
55
import java.util.List;
56
57
// You may not copy the check unless you are licensed under GPL
58
@CheckData(name = "Reach", stableKey = "grim.combat.reach", description = "Attacked an entity from too far away")
59
public class Reach extends Check implements PacketReceiveListener {
60
    private static final Verbose V = Verbose.of("{f64:%.5f} blocks, type={entity}");
61
62
    private static final List<EntityType> blacklisted = Arrays.asList(
63
            EntityTypes.BOAT,
64
            EntityTypes.CHEST_BOAT,
65
            EntityTypes.SHULKER);
66
    private static final CheckResult NONE = new CheckResult(ResultType.NONE, 0, 0, false);
67
    // Only one flag per reach attack, per entity, per tick.
68
    // We store position because lastX isn't reliable on teleports.
69
    private final Int2ObjectMap<InteractionData> playerAttackQueue = new Int2ObjectOpenHashMap<>();
70
    private boolean cancelImpossibleHits;
71
    private double threshold;
72
    private double cancelBuffer; // For the next 4 hits after using reach, we aggressively cancel reach
73
74
    public Reach(GrimPlayer player) {
75
        super(player);
76
    }
77
78
    @Override
79
    public void onPacketReceive(final PacketReceiveEvent event) {
80
        if (!player.disableGrim && event.getPacketType() == PacketType.Play.Client.ATTACK) {
81
            WrapperPlayClientAttack packet = new WrapperPlayClientAttack(event);
82
            onInteract(event, packet.getEntityId(), InteractionHand.MAIN_HAND);
83
        }
84
85
        if (!player.disableGrim && event.getPacketType() == PacketType.Play.Client.INTERACT_ENTITY) {
86
            WrapperPlayClientInteractEntity packet = new WrapperPlayClientInteractEntity(event);
87
            onInteract(event, packet.getEntityId(), packet.getAction() == WrapperPlayClientInteractEntity.InteractAction.ATTACK ? InteractionHand.MAIN_HAND : packet.getHand());
88
        }
89
90
        // If the player set their look, or we know they have a new tick
91
        if (isUpdate(event.getPacketType())) {
92
            tickBetterReachCheckWithAngle();
93
        }
94
    }
95
96
    private void onInteract(PacketReceiveEvent event, int entityId, InteractionHand hand) {
97
        // Don't let the player teleport to bypass reach
98
        if (player.getSetbackTeleportUtil().shouldBlockMovement()) {
99
            event.setCancelled(true);
100
            player.onPacketCancel();
101
            return;
102
        }
103
104
        PacketEntity entity = player.compensatedEntities.entityMap.get(entityId);
105
        // Stop people from freezing transactions before an entity spawns to bypass reach
106
        // TODO: implement dragon parts?
107
        if (entity == null || entity instanceof PacketEntityEnderDragonPart) {
108
            // Only cancel if and only if we are tracking this entity
109
            // This is because we don't track paintings.
110
            if (shouldModifyPackets() && player.compensatedEntities.serverPositionsMap.containsKey(entityId)) {
111
                event.setCancelled(true);
112
                player.onPacketCancel();
113
            }
114
            return;
115
        }
116
117
        // Dead entities cause false flags (https://github.com/GrimAnticheat/Grim/issues/546)
118
        if (entity.isDead) return;
119
120
        // TODO: Remove when in front of via
121
        if (entity.getType() == EntityTypes.ARMOR_STAND && player.getClientVersion().isOlderThan(ClientVersion.V_1_8))
122
            return;
123
        // Prevents Happy Ghast Reach false on 1.21.6+ servers with ViaBackwards set up
124
        if (entity.getType() == EntityTypes.HAPPY_GHAST && player.getClientVersion().isOlderThan(ClientVersion.V_1_21_6))
125
            return;
126
        if (player.gamemode == GameMode.CREATIVE || player.gamemode == GameMode.SPECTATOR)
127
            return;
128
        if (player.inVehicle()) return;
129
        if (entity.riding != null) return;
130
131
        ItemStack currentStack = player.inventory.getItemInHand(hand);
132
        ItemStack startStack = player.inventory.getStartOfTickStack();
133
134
        boolean hasRange = false;
135
        float maxReach = 0f;
136
        float hitboxMargin = 0f;
137
        Vector3dm attackRangeMovement = null;
138
139
        boolean clientAttackRangeExists = player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_21_11);
140
        boolean clientAndServerAgrees = clientAttackRangeExists && ATTACK_RANGE_COMPONENT_EXISTS;
141
142
        boolean viaVersionAvailable = false;
143
        if (USE_1_8_HITBOX_MARGIN && ViaVersionUtil.isAvailable) {
144
            viaVersionAvailable = Via.getConfig().getValues().containsKey("use-1_8-hitbox-margin") && Via.getConfig().use1_8HitboxMargin();
145
        }
146
147
        boolean clientAndViaVersion = clientAttackRangeExists && viaVersionAvailable;
148
        if (clientAndServerAgrees || clientAndViaVersion) {
149
            ItemAttackRange startRange = startStack.getComponentOr(ComponentTypes.ATTACK_RANGE, null);
150
            ItemAttackRange currentRange = currentStack.getComponentOr(ComponentTypes.ATTACK_RANGE, null);
151
152
            if (clientAndViaVersion) {
153
                if (startStack != ItemStack.EMPTY) {
154
                    startRange = new ItemAttackRange(0F, 3F, 0F, 4F, 0.1F, 1F);
155
                }
156
157
                if (currentStack != ItemStack.EMPTY) {
158
                    currentRange = new ItemAttackRange(0F, 3F, 0F, 4F, 0.1F, 1F);
159
                }
160
            }
161
162
            // If the start stack has no range component, the client defaults to vanilla reach behavior,
163
            // regardless of what the current stack is (No Range -> X = No Range used).
164
            if (startRange != null) {
165
                hasRange = true;
166
                if (currentRange == null) {
167
                    // Range (Start) -> No Range (Current)
168
                    // Client logic uses Start Range, including the attack_range movement projection.
169
                    if (!clientAndViaVersion) {
170
                        attackRangeMovement = player.clientVelocity.clone();
171
                    }
172
                    maxReach = startRange.getMaxRange();
173
                    hitboxMargin = startRange.getHitboxMargin();
174
                } else {
175
                    // Range (Start) -> Range (Current)
176
                    // Client logic requires satisfying BOTH constraints
177
                    maxReach = Math.min(startRange.getMaxRange(), currentRange.getMaxRange());
178
                    hitboxMargin = Math.min(startRange.getHitboxMargin(), currentRange.getHitboxMargin());
179
                }
180
            }
181
        }
182
183
        boolean tooManyAttacks = playerAttackQueue.size() > 10;
184
        if (!tooManyAttacks) {
185
            playerAttackQueue.put(entityId, new InteractionData(
186
                    player.x, player.y, player.z,
187
                    hasRange, maxReach, hitboxMargin, attackRangeMovement
188
            )); // Queue for next tick for very precise check
189
        }
190
191
        boolean knownInvalid = attackRangeMovement == null && isKnownInvalid(entity, hasRange, maxReach, hitboxMargin);
192
193
        if ((shouldModifyPackets() && cancelImpossibleHits && knownInvalid) || tooManyAttacks) {
194
            event.setCancelled(true);
195
            player.onPacketCancel();
196
        }
197
    }
198
199
    // This method finds the most optimal point at which the user should be aiming at
200
    // and then measures the distance between the player's eyes and this target point
201
    //
202
    // It will not cancel every invalid attack but should cancel 3.05+ or so in real-time
203
    // Let the post look check measure the distance, as it will always return equal or higher
204
    // than this method.  If this method flags, the other method WILL flag.
205
    //
206
    // Meaning that the other check should be the only one that flags.
207
    private boolean isKnownInvalid(PacketEntity reachEntity, boolean hasAttackRange, float itemMaxReach, float itemHitboxMargin) {
208
        // If the entity doesn't exist, or if it is exempt, or if it is dead
209
        if ((blacklisted.contains(reachEntity.getType()) || !reachEntity.isLivingEntity) && reachEntity.getType() != EntityTypes.END_CRYSTAL)
210
            return false; // exempt
211
212
        if (player.gamemode == GameMode.CREATIVE || player.gamemode == GameMode.SPECTATOR)
213
            return false;
214
        if (player.inVehicle()) return false;
215
216
        // Filter out what we assume to be cheats
217
        if (cancelBuffer != 0) {
218
            CheckResult result = checkReach(reachEntity, player.x, player.y, player.z, hasAttackRange, itemMaxReach, itemHitboxMargin, null, true);
219
            return result.isFlag();
220
        } else {
221
            SimpleCollisionBox targetBox = getTargetBox(reachEntity);
222
223
            double maxReach = applyReachModifiers(targetBox, hasAttackRange, itemMaxReach, itemHitboxMargin, !player.packetStateData.didLastMovementIncludePosition);
224
            return ReachUtils.getMinReachToBox(player, targetBox) > maxReach;
225
        }
226
    }
227
228
    private void tickBetterReachCheckWithAngle() {
229
        for (Int2ObjectMap.Entry<InteractionData> attack : playerAttackQueue.int2ObjectEntrySet()) {
230
            PacketEntity reachEntity = player.compensatedEntities.entityMap.get(attack.getIntKey());
231
            if (reachEntity == null) continue;
232
233
            InteractionData interactionData = attack.getValue();
234
            CheckResult result = checkReach(reachEntity, interactionData.x, interactionData.y, interactionData.z, interactionData.hasAttackRange, interactionData.maxReach, interactionData.hitboxMargin, interactionData.attackRangeMovement, false);
235
            switch (result.type()) {
236
                case REACH -> flag(
237
                        V.write(verbose()).f64(result.minDistance()).uint(reachEntity.getType().getId(player.getClientVersion())),
238
                        () -> {
239
                            String added = ", type=" + reachEntity.getType().getName().getKey();
240
                            if (reachEntity instanceof PacketEntitySizeable sizeable) {
241
                                added += ", size=" + sizeable.size;
242
                            }
243
                            return result.verbose() + added;
244
                        });
245
                case HITBOX -> {
246
                    String added = "type=" + reachEntity.getType().getName().getKey();
247
                    if (reachEntity instanceof PacketEntitySizeable sizeable) {
248
                        added += ", size=" + sizeable.size;
249
                    }
250
                    player.checkManager.getCheck(Hitboxes.class).flag(result.verbose() + added);
251
                }
252
            }
253
        }
254
255
        playerAttackQueue.clear();
256
    }
257
258
    @NotNull
259
    private CheckResult checkReach(PacketEntity reachEntity, double x, double y, double z, boolean hasAttackRange, float itemMaxReach, float itemHitboxMargin, Vector3dm attackRangeMovement, boolean isPrediction) {
260
        SimpleCollisionBox targetBox = getTargetBox(reachEntity);
261
262
        double movementAllowance = attackRangeMovement == null ? 0 : getAttackRangeMovementAllowance(attackRangeMovement);
263
        double maxReach = applyReachModifiers(targetBox, hasAttackRange, itemMaxReach, itemHitboxMargin, !player.packetStateData.didLastLastMovementIncludePosition) + movementAllowance;
264
        double minDistance = Double.MAX_VALUE;
265
266
        // https://bugs.mojang.com/browse/MC-67665
267
        List<Vector3dm> possibleLookDirs = new ArrayList<>(Collections.singletonList(ReachUtils.getLook(player, player.yaw, player.pitch)));
268
269
        // If we are a tick behind, we don't know their next look so don't bother doing this
270
        if (!isPrediction) {
271
            // 1.7 players do not have any of these issues! They are always on the latest look vector
272
            if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_8)) {
273
                possibleLookDirs.add(ReachUtils.getLook(player, player.lastYaw, player.pitch));
274
275
                // 1.9+ players could be a tick behind because we don't get skipped ticks
276
                if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_9)) {
277
                    possibleLookDirs.add(ReachUtils.getLook(player, player.lastYaw, player.lastPitch));
278
                }
279
            }
280
        }
281
282
        // +3 would be 3 + 3 = 6, which is the pre-1.20.5 behaviour, preventing "Missed Hitbox"
283
        final double distance = maxReach + 3;
284
285
        final double[] possibleEyeHeights = player.getPossibleEyeHeights();
286
        for (Vector3dm lookVec : possibleLookDirs) {
287
            lookVec.multiply(distance);
288
289
            for (double eye : possibleEyeHeights) {
290
                final Vector3d eyePos = new Vector3d(x, y + eye, z);
291
                Vector3d endReachPos = eyePos.add(lookVec.getX(), lookVec.getY(), lookVec.getZ());
292
293
                Vector3d intercept = ReachUtils.calculateIntercept(targetBox, eyePos, endReachPos).first();
294
295
                if (ReachUtils.isVecInside(targetBox, eyePos)) {
296
                    minDistance = 0;
297
                    break;
298
                }
299
300
                if (intercept != null) {
301
                    minDistance = Math.min(eyePos.distance(intercept), minDistance);
302
                }
303
            }
304
        }
305
306
        // if the entity is not exempt and the entity is alive
307
        if ((!blacklisted.contains(reachEntity.getType()) && reachEntity.isLivingEntity) || reachEntity.getType() == EntityTypes.END_CRYSTAL) {
308
            if (minDistance == Double.MAX_VALUE) {
309
                cancelBuffer = 1;
310
                return new CheckResult(ResultType.HITBOX, 0, 0, false);
311
            } else if (minDistance > maxReach) {
312
                cancelBuffer = 1;
313
                return new CheckResult(ResultType.REACH, minDistance, movementAllowance, attackRangeMovement != null);
314
            } else {
315
                cancelBuffer = Math.max(0, cancelBuffer - 0.25);
316
            }
317
        }
318
319
        return NONE;
320
    }
321
322
    private SimpleCollisionBox getTargetBox(PacketEntity reachEntity) {
323
        if (reachEntity.getType() == EntityTypes.END_CRYSTAL) { // Hardcode end crystal box
324
            return new SimpleCollisionBox(reachEntity.trackedServerPosition.getPos().subtract(1, 0, 1), reachEntity.trackedServerPosition.getPos().add(1, 2, 1));
325
        }
326
        return reachEntity.getPossibleCollisionBoxes();
327
    }
328
329
    private double getAttackRangeMovementAllowance(Vector3dm attackRangeMovement) {
330
        if (attackRangeMovement.lengthSquared() == 0) {
331
            return 0;
332
        }
333
334
        return getForwardMovement(attackRangeMovement, player.yaw, player.pitch);
335
    }
336
337
    private double getForwardMovement(Vector3dm movement, float yaw, float pitch) {
338
        return Math.max(0, movement.dot(ReachUtils.getLook(player, yaw, pitch)));
339
    }
340
341
    private static final boolean ATTACK_RANGE_COMPONENT_EXISTS = PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_21_11);
342
    private static final boolean USE_1_8_HITBOX_MARGIN = PacketEvents.getAPI().getServerManager().getVersion().isOlderThanOrEquals(ServerVersion.V_1_8_8);
343
344
    private double applyReachModifiers(SimpleCollisionBox targetBox, boolean hasAttackRange, float itemMaxReach, float itemHitboxMargin, boolean giveMovementThreshold) {
345
        double maxReach;
346
        double hitboxMargin = threshold;
347
348
        if (hasAttackRange) {
349
            maxReach = itemMaxReach;
350
            hitboxMargin += itemHitboxMargin;
351
        } else {
352
            maxReach = player.compensatedEntities.self.getAttributeValue(Attributes.ENTITY_INTERACTION_RANGE);
353
            // 1.7 and 1.8 players get a bit of extra hitbox (this is why you should use 1.8 on cross version servers)
354
            // Yes, this is vanilla and not uncertainty.  All reach checks have this or they are wrong.
355
            if (player.getClientVersion().isOlderThan(ClientVersion.V_1_9)) {
356
                hitboxMargin += 0.1f;
357
            }
358
        }
359
360
        // This is better than adding to the reach, as 0.03 can cause a player to miss their target
361
        // Adds some more than 0.03 uncertainty in some cases, but a good trade off for simplicity
362
        //
363
        // Just give the uncertainty on 1.9+ clients as we have no way of knowing whether they had 0.03 movement
364
        // However, on 1.21.2+ we do know if they had 0.03 movement
365
        if (giveMovementThreshold || player.canSkipTicks()) {
366
            hitboxMargin += player.getMovementThreshold();
367
        }
368
369
        targetBox.expand(hitboxMargin);
370
371
        return maxReach;
372
    }
373
374
    @Override
375
    public void onReload(@NotNull ConfigManager config) {
376
        this.cancelImpossibleHits = config.getBooleanElse("Reach.block-impossible-hits", true);
377
        this.threshold = config.getDoubleElse("Reach.threshold", 0.0005);
378
    }
379
380
    private enum ResultType {
381
        REACH, HITBOX, NONE
382
    }
383
384
    private record CheckResult(ResultType type, double minDistance, double extraMovement, boolean hasExtraMovement) {
385
        public boolean isFlag() {
386
            return type != ResultType.NONE;
387
        }
388
389
        public String verbose() {
390
            if (type != ResultType.REACH) {
391
                return "";
392
            }
393
394
            String verbose = String.format("%.5f", minDistance) + " blocks";
395
            if (hasExtraMovement) {
396
                verbose += String.format(", extraMovement=%.5f", extraMovement);
397
            }
398
            return verbose;
399
        }
400
    }
401
402
    private record InteractionData(double x, double y, double z, boolean hasAttackRange,
403
                                   float maxReach, float hitboxMargin, Vector3dm attackRangeMovement) {}
404
}

How it counteracts this module

Grim queues the attack position on ATTACK and INTERACT_ENTITY and performs the precise ray trace on the following look update, against the packet-entity box rebuilt from server-side teleport and rel-move data. Because 1.8 can lag the look by one tick, the trace checks all possible look directions from both the current and last yaw and pitch and all possible eye heights, and pre-1.9 clients get a 0.1 hitbox margin on the box. The client-side border never reaches the server, so the trace sees the unexpanded box: a hit that only the inflated border made possible fails the intersection, and hits that do intersect beyond the real box surface flag on distance with the default threshold 0.0005. The cancelBuffer then suppresses the next several attacks, which directly counters a killaura that keeps firing into the expanded box.

anticheat KillAura (reach and direction sub-checks)

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

How it counteracts this module

Arc v2's KillAura check runs from the EntityDamageByEntityEvent path with five sub-checks. The reach sub-check measures the distance from the player to the victim's location minus the victim's current velocity, compared with max-reach 4.2 from config.yml, so knockback does not false-flag and the measurement is against the real center. The direction sub-check compares the look angle to the victim with max-direction-angle 1.2, which exposes the off-axis aim that the expanded border encourages. The inflated client box changes neither the center distance nor the look angle the server sees, so every hit that relied on the border trips one of the two. The speed sub-check (max-attacks 16 and max-attack-packets 20 per second) additionally caps how fast a killaura can exploit the wider envelope.

← Back to Analysis Hub