Tenacity 6.0 KillAura module 4 files, 355 lines

Tenacity 6.0 KillAura: Full Source Analysis

Tenacity 6.0's KillAura is a reach-extending melee aura with randomized CPS, optional auto-block and an optional rotation snap.

dev/tenacity/module/impl/combat/KillAuraModule.java · GitHub source ↗

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

Analysis

Overview

Tenacity 6.0's KillAura is a reach-extending melee aura with randomized CPS, optional auto-block and an optional rotation snap. On every MotionEvent pre-phase it rebuilds a target list of living entities within the Reach setting (default 4, up to 8) that pass canEntityBeSeen, are not invisible and are not friends, sorts it by distance, snaps the client's yaw to the closest target (pitch is left untouched in every rotation mode), and fires swingItem() plus a C02PacketUseEntity ATTACK whenever the per-attack TimerUtil has elapsed 1000 / cps milliseconds. CPS is a configurable 10-100 range (default 10) drawn per attack, optionally multiplied by a random 1-2x interval under 'Extra Randomization'. Auto-block supports Vanilla and Hurt Time modes that send the C08 use-item / C07 release pair around the attacks, and onDisable releases the sword if a block is still active. The 'Fake' auto-block mode and the HvH rotation mode are registered but have no implementing code path.

Architecture

KillAuraModule extends Module and wires all combat logic to a single IEventListener<MotionEvent> (onMotionEvent); a second UpdateEvent listener only updates the HUD suffix with the CPS. Settings are Minimum CPS / Maximum CPS (both default 10, range 1-100), Reach (default 4, range 3-8), Auto Block, Rotate, Enchant/Critical particle toggles, Extra Randomization, Auto Block Mode (Vanilla / Hurt Time / Fake) and Rotation Mode (Vanilla / HvH Mode). The constructor and every tick re-clamp minimumCPS against maximumCPS so the two settings cannot invert. Each motion event calls sortAndAddTargets: the loaded entity list is filtered to EntityLivingBase instances within reach.getCurrentValue() that are not the player, pass mc.thePlayer.canEntityBeSeen(entity) (a world ray trace - no wall hits), are not invisible, and are not on the friend list via FriendCommand.isFriend on the display name, then sorted by distance so the closest legal target is attacked. Packets go through mc.getNetHandler().addToSendQueue, the normal client queue, so they are sent with the tick's batch.

Rotation and auto-block

Rotation is applied only on the pre phase. Vanilla mode calls RotationUtil.getRotationFromTarget and writes only event.setYaw(rotations[0]) - the pitch component is computed by the helper but deliberately not applied, so vertical aim stays at the player's real pitch. The yaw is also quantized in a peculiar way: fixedYaw = rotations[0] - rotations[1] % sensitivityMultiplier is computed but never used, and the plain rotations[0] is what reaches the event, so the snap is a full instant yaw. HvH Mode computes fixedYaw = rotations[1] - rotations[0] % sensitivityMultiplier (a swapped expression) and clamps it with MathUtil.clamp(fixedYaw, 0, 10), pinning the yaw between 0 and 10 degrees - a near-constant bearing that makes the player appear to look in roughly one direction while still attacking, a deliberate anti-aim/HvH gimmick. Auto-block runs independently: Vanilla mode places C08PacketPlayerBlockPlacement(BlockPos(-1,-1,-1), 255, heldItem, 0,0,0) once when !wasBlocked and releases with C07 RELEASE_USE_ITEM when the target disappears or the module disables; Hurt Time mode places the block when mc.thePlayer.hurtTime == 9 (the tick after being hit) and releases when hurtTime == 0, with both releases skipped while isSwingInProgress. The Fake mode has no case in either switch, so it does nothing.

CPS timing and attack dispatch

Attacks are timed by a TimerUtil with hasTimeElapsed(1000 / cps, true), which resets the clock on every fire. With randomization off, cps is Math.round(MathUtil.getRandomInRange(min, max)) drawn per attack, so a 10-10 setting yields a perfectly regular 10 Hz; with Extra Randomization on, the interval becomes 1000 / cps * MathUtil.getRandomInRange(1, 2), so the effective rate alternates between the configured CPS and half of it. At the 100 CPS maximum the interval is 10ms, far shorter than a tick, so the actual rate is capped by the motion-event cadence - at most one attack per tick - but every eligible tick can fire. Each fire calls swingItem() then addToSendQueue(new C02PacketUseEntity(currentTarget, ATTACK)), and the optional particle toggles call mc.thePlayer.onEnchantmentCritical / onCriticalHit directly, which only spawns the client-side particle burst - no server packet - so they are purely cosmetic. The timer clock is shared with the rest of the module and onDisable resets Timer.timerSpeed to 1f, hinting the module normally drives game-speed via the global Timer elsewhere in the client.

source KillAuraModule.java (module, targeting, attack dispatch)

KillAuraModule.java201 lines · JavaOriginal ↗
1
package dev.tenacity.module.impl.combat;
2
3
import dev.tenacity.command.impl.FriendCommand;
4
import dev.tenacity.event.IEventListener;
5
import dev.tenacity.event.impl.player.MotionEvent;
6
import dev.tenacity.event.impl.player.UpdateEvent;
7
import dev.tenacity.module.Module;
8
import dev.tenacity.module.ModuleCategory;
9
import dev.tenacity.setting.impl.BooleanSetting;
10
import dev.tenacity.setting.impl.ModeSetting;
11
import dev.tenacity.setting.impl.NumberSetting;
12
import dev.tenacity.util.misc.MathUtil;
13
import dev.tenacity.util.misc.TimerUtil;
14
import dev.tenacity.util.player.RotationUtil;
15
import lombok.Getter;
16
import net.minecraft.block.BlockOldLeaf;
17
import net.minecraft.entity.EntityLivingBase;
18
import net.minecraft.entity.player.EntityPlayer;
19
import net.minecraft.item.ItemSword;
20
import net.minecraft.network.play.client.C02PacketUseEntity;
21
import net.minecraft.network.play.client.C07PacketPlayerDigging;
22
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
23
import net.minecraft.util.BlockPos;
24
import net.minecraft.util.EnumFacing;
25
import net.minecraft.util.Timer;
26
27
import java.util.ArrayList;
28
import java.util.Comparator;
29
import java.util.List;
30
31
public final class KillAuraModule extends Module {
32
33
    @Getter
34
    private static EntityLivingBase currentTarget;
35
    private final List<EntityLivingBase> targetList = new ArrayList<>();
36
37
    private final TimerUtil timerUtil = new TimerUtil();
38
39
    private boolean blocking, wasBlocked;
40
41
    private final NumberSetting minimumCPS = new NumberSetting("Minimum CPS", 10, 1, 100, 0.1),
42
            maximumCPS = new NumberSetting("Maximum CPS", 10, 1, 100, 0.1),
43
            reach = new NumberSetting("Reach", 4, 3, 8, 0.1);
44
45
    private final BooleanSetting autoBlock = new BooleanSetting("Auto Block", false),
46
            rotate = new BooleanSetting("Rotate", true),
47
            enchantParticle = new BooleanSetting("Enchant Particle", false),
48
            criticalParticle = new BooleanSetting("Critical Particle", false);
49
    private final BooleanSetting randomizecps = new BooleanSetting("Extra Randomization", false);
50
51
    private final ModeSetting autoBlockMode = new ModeSetting("Auto Block Mode", "Vanilla", "Hurt Time", "Fake"),
52
            rotationMode = new ModeSetting("Rotation Mode", "Vanilla", "HvH Mode");
53
54
    public KillAuraModule() {
55
        super("KillAura", "Automatically attacks people within a set range", ModuleCategory.COMBAT);
56
        initializeSettings(minimumCPS, maximumCPS, reach, autoBlock, autoBlockMode, rotate, rotationMode, enchantParticle, criticalParticle, randomizecps);
57
        if(minimumCPS.getCurrentValue() > maximumCPS.getCurrentValue()) { minimumCPS.setCurrentValue(maximumCPS.getCurrentValue());}
58
        if(maximumCPS.getCurrentValue() < minimumCPS.getCurrentValue()) {maximumCPS.setCurrentValue(minimumCPS.getCurrentValue());}
59
    }
60
61
    private final IEventListener<MotionEvent> onMotionEvent = event -> {
62
        sortAndAddTargets();
63
        if(minimumCPS.getCurrentValue() > maximumCPS.getCurrentValue()) { minimumCPS.setCurrentValue(maximumCPS.getCurrentValue());}
64
        if(maximumCPS.getCurrentValue() < minimumCPS.getCurrentValue()) {maximumCPS.setCurrentValue(minimumCPS.getCurrentValue());}
65
        currentTarget = !targetList.isEmpty() ? targetList.get(0) : null;
66
        blocking = autoBlock.isEnabled() && currentTarget != null && (mc.thePlayer.getHeldItem() != null && mc.thePlayer.getHeldItem().getItem() instanceof ItemSword);
67
        if (currentTarget == null) {
68
            if (event.isPre() && wasBlocked) {
69
                mc.getNetHandler().addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, new BlockPos(0, 0, 0), EnumFacing.DOWN));
70
                wasBlocked = false;
71
            }
72
            return;
73
        }
74
75
        if (event.isPre()) {
76
            if(minimumCPS.getCurrentValue() > maximumCPS.getCurrentValue()) { minimumCPS.setCurrentValue(maximumCPS.getCurrentValue());}
77
            if(maximumCPS.getCurrentValue() < minimumCPS.getCurrentValue()) {maximumCPS.setCurrentValue(minimumCPS.getCurrentValue());}
78
79
            if (rotate.isEnabled()) {
80
                switch (rotationMode.getCurrentMode()) {
81
                    case "Vanilla":
82
                        final float[] rotations = RotationUtil.getRotationFromTarget(currentTarget);
83
84
                        final float sensitivityMultiplier = RotationUtil.getSensitivityMultiplier();
85
                        final float fixedYaw = rotations[0] - rotations[1] % sensitivityMultiplier;
86
87
                        event.setYaw(rotations[0]);
88
                        break;
89
                }
90
            }
91
            if (event.isPre()) {
92
                if (rotate.isEnabled()) {
93
                    if(minimumCPS.getCurrentValue() > maximumCPS.getCurrentValue()) { minimumCPS.setCurrentValue(maximumCPS.getCurrentValue());}
94
                    if(maximumCPS.getCurrentValue() < minimumCPS.getCurrentValue()) {maximumCPS.setCurrentValue(minimumCPS.getCurrentValue());}
95
                    switch (rotationMode.getCurrentMode()) {
96
                        case "HvH Mode":
97
                            final float[] rotations = RotationUtil.getRotationFromTarget(currentTarget);
98
99
                            final float sensitivityMultiplier = RotationUtil.getSensitivityMultiplier();
100
                            final float fixedYaw = rotations[1] - rotations[0] % sensitivityMultiplier;
101
102
                            event.setYaw((float) MathUtil.clamp(fixedYaw, 0, 10));
103
                            break;
104
                    }
105
                }
106
                if (!randomizecps.isEnabled()) {
107
                    if(minimumCPS.getCurrentValue() > maximumCPS.getCurrentValue()) { minimumCPS.setCurrentValue(maximumCPS.getCurrentValue());}
108
                    if(maximumCPS.getCurrentValue() < minimumCPS.getCurrentValue()) {maximumCPS.setCurrentValue(minimumCPS.getCurrentValue());}
109
                    final long cps = Math.round(MathUtil.getRandomInRange(minimumCPS.getCurrentValue(), maximumCPS.getCurrentValue()));
110
                    if (timerUtil.hasTimeElapsed(1000 / cps, true)) {
111
112
                        if (enchantParticle.isEnabled())
113
                            mc.thePlayer.onEnchantmentCritical(currentTarget);
114
                        if (criticalParticle.isEnabled())
115
                            mc.thePlayer.onCriticalHit(currentTarget);
116
117
                        mc.thePlayer.swingItem();
118
                        mc.getNetHandler().addToSendQueue(new C02PacketUseEntity(currentTarget, C02PacketUseEntity.Action.ATTACK));
119
                    }
120
                } else {
121
                    if (randomizecps.isEnabled()) {
122
                        if(minimumCPS.getCurrentValue() > maximumCPS.getCurrentValue()) { minimumCPS.setCurrentValue(maximumCPS.getCurrentValue());}
123
                        if(maximumCPS.getCurrentValue() < minimumCPS.getCurrentValue()) {maximumCPS.setCurrentValue(minimumCPS.getCurrentValue());}
124
                        final long cps = Math.round(MathUtil.getRandomInRange(minimumCPS.getCurrentValue(), maximumCPS.getCurrentValue()));
125
                        final long randomcps = (long) MathUtil.getRandomInRange(1, 2);
126
                        if (timerUtil.hasTimeElapsed(1000 / cps * randomcps, true)) {
127
128
                            if (enchantParticle.isEnabled())
129
                                mc.thePlayer.onEnchantmentCritical(currentTarget);
130
                            if (criticalParticle.isEnabled())
131
                                mc.thePlayer.onCriticalHit(currentTarget);
132
133
                            mc.thePlayer.swingItem();
134
                            mc.getNetHandler().addToSendQueue(new C02PacketUseEntity(currentTarget, C02PacketUseEntity.Action.ATTACK));
135
                        }
136
                    }
137
                }
138
            }
139
        }
140
141
142
        if (blocking) {
143
            switch (autoBlockMode.getCurrentMode()) {
144
                case "Hurt Time":
145
                    if (event.isPre() && mc.thePlayer.hurtTime == 0 && wasBlocked && !mc.thePlayer.isSwingInProgress) {
146
                        mc.getNetHandler().addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, new BlockPos(0, 0, 0), EnumFacing.DOWN));
147
                        wasBlocked = false;
148
                    }
149
                    break;
150
            }
151
        }
152
153
        if (blocking) {
154
            switch (autoBlockMode.getCurrentMode()) {
155
                case "Vanilla":
156
                    if (!wasBlocked) {
157
                        mc.getNetHandler().addToSendQueue(new C08PacketPlayerBlockPlacement(new BlockPos(-1, -1, -1), 255, mc.thePlayer.getHeldItem(), 0, 0, 0));
158
                        wasBlocked = true;
159
                    }
160
                    break;
161
                case "Hurt Time":
162
                    if (mc.thePlayer.hurtTime == 9 && !wasBlocked) {
163
                        mc.getNetHandler().addToSendQueue(new C08PacketPlayerBlockPlacement(new BlockPos(-1, -1, -1), 255, mc.thePlayer.getHeldItem(), 0, 0, 0));
164
                        wasBlocked = true;
165
                    }
166
                    break;
167
            }
168
        }
169
    };
170
171
    @Override
172
    public void onDisable() {
173
        if (wasBlocked && !mc.thePlayer.isSwingInProgress)
174
            mc.getNetHandler().addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, new BlockPos(0, 0, 0), EnumFacing.DOWN));
175
176
        wasBlocked = blocking = false;
177
178
        currentTarget = null;
179
        targetList.clear();
180
        Timer.timerSpeed = 1f;
181
        super.onDisable();
182
    }
183
    private void sortAndAddTargets() {
184
        targetList.clear();
185
        mc.theWorld.getLoadedEntityList().forEach(entity -> {
186
            if (entity instanceof EntityLivingBase) {
187
                EntityLivingBase entityLivingBase = (EntityLivingBase) entity;
188
                if (mc.thePlayer.getDistanceToEntity(entity) <= reach.getCurrentValue() && entity != mc.thePlayer && mc.thePlayer.canEntityBeSeen(entity) && !entity.isInvisible() && !FriendCommand.isFriend((entity).getDisplayName().getUnformattedText())) {
189
                    targetList.add(entityLivingBase);
190
                }
191
            }
192
        });
193
        targetList.sort(Comparator.comparingDouble(mc.thePlayer::getDistanceToEntity));
194
    }
195
    public boolean isBlocking() {
196
        return blocking;
197
    }
198
199
    private final IEventListener<UpdateEvent> onUpdateEvent = event -> setSuffix(String.valueOf(maximumCPS.getCurrentValue() + " CPS"));
200
201
}

What this file does

The entire module: onMotionEvent filters and sorts the target list each tick, applies the rotation modes (Vanilla sets yaw only; HvH Mode clamps a swapped yaw expression into 0-10 degrees), dispatches attacks on the TimerUtil cadence with optional client-side particle calls, and runs the Vanilla / Hurt Time auto-block state machine with C08 placements at BlockPos(-1,-1,-1) and C07 releases. It also holds the reach (3-8) and CPS (1-100) NumberSettings, the currentTarget getter used by other modules, and an onDisable that releases the sword when wasBlocked and clears target state. Note the asymmetry: getRotationFromTarget computes a pitch that is never applied, and the Fake auto-block mode and the fixedYaw quantization in Vanilla mode are dead code paths.

source RotationUtil.java (aim math and sensitivity)

RotationUtil.java41 lines · JavaOriginal ↗
1
package dev.tenacity.util.player;
2
3
import net.minecraft.client.Minecraft;
4
import net.minecraft.entity.Entity;
5
import net.minecraft.util.MathHelper;
6
7
public final class RotationUtil {
8
9
    private static final Minecraft MC = Minecraft.getMinecraft();
10
11
    private RotationUtil() {
12
    }
13
14
    public static float getSensitivityMultiplier() {
15
        final float sensitivity = MC.gameSettings.mouseSensitivity * 0.6F + 0.2F;
16
        return (sensitivity * sensitivity * sensitivity * 8.0F) * 0.15F;
17
    }
18
19
    public static float[] getRotationFromTarget(final Entity entity) {
20
        if (entity == null) {
21
            return null;
22
        }
23
        Minecraft mc = Minecraft.getMinecraft();
24
        final double xSize = entity.posX - mc.thePlayer.posX;
25
        final double ySize = entity.posY + entity.getEyeHeight() / 2 - (mc.thePlayer.posY + mc.thePlayer.getEyeHeight()/2);
26
        final double zSize = entity.posZ - mc.thePlayer.posZ;
27
        final double theta = MathHelper.sqrt_double(xSize * xSize + zSize * zSize);
28
        final float yaw = (float) (Math.atan2(zSize, xSize) * 180 / Math.PI) - 90;
29
        final float pitch = (float) (-(Math.atan2(ySize, theta) * 180 / Math.PI));
30
        return new float[]{(mc.thePlayer.rotationYaw + MathHelper.wrapAngleTo180_float(yaw - mc.thePlayer.rotationYaw)) % 360, (mc.thePlayer.rotationPitch + MathHelper.wrapAngleTo180_float(pitch - mc.thePlayer.rotationPitch)) % 360.0f};
31
//        final double xSize = entity.posX - MC.thePlayer.posX;
32
//        final double ySize = entity.posY + entity.getEyeHeight() / 2 - (MC.thePlayer.posY + MC.thePlayer.getEyeHeight());
33
//        final double zSize = entity.posZ - MC.thePlayer.posZ;
34
//        final double theta = MathHelper.sqrt_double(xSize * xSize + zSize * zSize);
35
//
36
//        final float yaw = (float) (Math.atan2(zSize, xSize) * 180 / Math.PI) - 90;
37
//        final float pitch = (float) (-(Math.atan2(ySize, theta) * 180 / Math.PI));
38
//        return new float[]{(MC.thePlayer.rotationYaw + MathHelper.wrapAngleTo180_float(yaw - MC.thePlayer.rotationYaw)) % 360, (MC.thePlayer.rotationPitch + MathHelper.wrapAngleTo180_float(pitch - MC.thePlayer.rotationPitch)) % 360.0f};
39
    }
40
41
}

What this file does

getRotationFromTarget aims at the entity's position plus half its eye height against the player's eye level and returns a yaw/pitch pair wrapped into the player's current angles; getSensitivityMultiplier computes the cubic mouse-sensitivity factor (sensitivity^3 * 8 * 0.15) that the module uses to quantize the yaw. The dead commented block shows an earlier variant that aimed at the player's eye height with no /2 adjustment. The key fact for anticheats is that KillAuraModule consumes only the yaw element of this helper's return value, so pitch is never rotated and vertical aim is the player's real look.

source MathUtil.java (random ranges and clamp)

MathUtil.java86 lines · JavaOriginal ↗
1
package dev.tenacity.util.misc;
2
3
import net.minecraft.client.Minecraft;
4
import net.minecraft.util.MathHelper;
5
6
import java.math.BigDecimal;
7
import java.security.SecureRandom;
8
import java.text.DecimalFormat;
9
10
public final class MathUtil {
11
12
    public static final DecimalFormat DF_0 = new DecimalFormat("0");
13
    public static final DecimalFormat DF_1 = new DecimalFormat("0.0");
14
    public static final DecimalFormat DF_2 = new DecimalFormat("0.00");
15
16
    public static final SecureRandom SECURE_RANDOM = new SecureRandom();
17
18
    private MathUtil() {
19
    }
20
21
    public static int getRandomInRange(final int min, final int max) {
22
        return (int) ((Math.random() * (max - min)) + min);
23
    }
24
25
    public static double[] yawPos(final double value) {
26
        return yawPos(Minecraft.getMinecraft().thePlayer.rotationYaw * MathHelper.deg2Rad, value);
27
    }
28
29
    public static double[] yawPos(final float yaw, final double value) {
30
        return new double[]{-MathHelper.sin(yaw) * value, MathHelper.cos(yaw) * value};
31
    }
32
33
    public static float getRandomInRange(final float min, final float max) {
34
        return SECURE_RANDOM.nextFloat() * (max - min) + min;
35
    }
36
37
    public static double getRandomInRange(final double min, final double max) {
38
        return min == max ? min : SECURE_RANDOM.nextDouble() * (max - min) + min;
39
    }
40
41
    public static double lerp(final double old, final double newVal, final double amount) {
42
        return (1.0 - amount) * old + amount * newVal;
43
    }
44
45
    public static Double interpolate(final double oldValue, final double newValue, final double interpolationValue){
46
        return (oldValue + (newValue - oldValue) * interpolationValue);
47
    }
48
49
    public static float interpolateFloat(final float oldValue, final float newValue, final double interpolationValue){
50
        return interpolate(oldValue, newValue, (float) interpolationValue).floatValue();
51
    }
52
53
    public static int interpolateInt(final int oldValue, final int newValue, final double interpolationValue){
54
        return interpolate(oldValue, newValue, (float) interpolationValue).intValue();
55
    }
56
57
    public static float calculateGaussianValue(final float x, final float sigma) {
58
        final double output = 1.0 / Math.sqrt(2.0 * Math.PI * (sigma * sigma));
59
        return (float) (output * Math.exp(-(x * x) / (2.0 * (sigma * sigma))));
60
    }
61
62
    public static float getRandomFloat(final float max, final float min) {
63
        return SECURE_RANDOM.nextFloat() * (max - min) + min;
64
    }
65
66
    public static int getNumberOfDecimalPlace(final double value) {
67
        final BigDecimal bigDecimal = new BigDecimal(value);
68
        return Math.max(0, bigDecimal.stripTrailingZeros().scale());
69
    }
70
71
    public static double clamp(double value, final double min, final double max) {
72
        value = Math.max(min, value);
73
        value = Math.min(max, value);
74
        return value;
75
    }
76
77
    public static double roundToHalf(double d) {
78
        return Math.round(d * 2) / 2.0;
79
    }
80
81
    public static int nextInt(int min, int max) {
82
        return (int) ((Math.random() * (max - min)) + min);
83
    }
84
85
86
}

What this file does

getRandomInRange(double, double) draws from a SecureRandom and is the per-attack CPS source, getRandomInRange(int, int) feeds the 1-2x Extra Randomization multiplier, and clamp is what pins the HvH Mode yaw into the 0-10 degree band. The fixed-interval behavior when randomization is off follows from min == max: the double overload returns the constant directly, so a 10-10 CPS setting produces a perfectly regular 100ms attack interval - the signature that rate checks rely on.

source TimerUtil.java (attack clock)

TimerUtil.java27 lines · JavaOriginal ↗
1
package dev.tenacity.util.misc;
2
3
public final class TimerUtil {
4
5
    private long lastMS = System.currentTimeMillis();
6
7
    public void reset() {
8
        lastMS = System.currentTimeMillis();
9
    }
10
11
    public boolean hasTimeElapsed(final long time, final boolean reset) {
12
        if(System.currentTimeMillis() - lastMS > time) {
13
            if(reset) reset();
14
            return true;
15
        }
16
        return false;
17
    }
18
19
    public long getTime() {
20
        return System.currentTimeMillis() - lastMS;
21
    }
22
23
    public void setTime(final long time) {
24
        lastMS = time;
25
    }
26
27
}

What this file does

A millisecond stopwatch: hasTimeElapsed(time, reset) returns true once System.currentTimeMillis() - lastMS exceeds the interval and then resets the clock, which is exactly how the module implements its 1000 / cps attack cadence. The reset-on-fire semantics mean a single long frame (lag spike, render stall) only delays the next attack - the clock re-arms from the moment it fires, so the module cannot burst-attack after a stall, but it also means the attack stream is strictly periodic at the configured CPS, which is what makes the rate deterministic for server-side frequency checks.

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 (queued attack ray trace with angle)

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's Reach check runs on every ATTACK packet and never trusts the client's claim. onPacketReceive stores the player's exact position in playerAttackQueue, and on the next look update tickBetterReachCheckWithAngle casts rays from every possible eye height along the current yaw/pitch plus the previous yaw (1.8 clients are allowed both, since the attack and the look update arrive in the same tick) against the entity's tracked collision box expanded by the threshold (0.0005) plus a 0.1 hitbox margin for pre-1.9 clients. A ray that never intercepts the box produces the HITBOX result and flags the Hitboxes check; an intercept farther than maxReach (3.0) produces the REACH result. Independently, the real-time path (block-impossible-hits, on by default) uses getMinReachToBox - the distance from the eyes to the closest point of the box - and cancels any attack whose minimum reach exceeds the limit, arming a 4-hit cancel buffer.\n\nTenacity's default Reach of 4 blocks is nearly a full block over the 3.1005 effective ceiling, so every attack REACH-flags and the real-time cancel path kills the hit before damage. Raising Reach toward 8 makes the flagged distance larger. Because the module never sets pitch, a target standing above or below the player's eye level can also make the ray miss the box entirely, producing a Hitboxes flag on top of the reach violation. The only configuration that passes is Reach at 3.0 with targets at eye level, which removes the module's entire point.

anticheat FightHitbox (lag-compensated hitbox 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 validates each hit with its own ray trace after the fact: the interaction is deferred to the next MoveEvent, the victim's hitbox is rewound by the attacker's ping through the lag compensator and expanded by 0.005, and a ray from the attacker's eye (position + 1.62, minus 0.08 while sneaking) along the attacking direction must intersect it within maxReach (3.1 survival, 5.0 creative). A hit beyond 3.1 punishes 'Reach: Xm'; a ray that never touches the expanded box punishes 'Did not hit hitbox.' when checkBoxIntersection is on (default); optional occlusion checking exposes wall hits.\n\nTenacity's default 4-block reach exceeds the 3.1 cap by a clear margin, so FightHitbox flags every attack with the measured distance. The yaw snap does not help because Hawk uses the actual attacking direction and the module's pitch is never rotated: for a target above or below eye level the ray passes over or under the box and the check reports a missed hitbox instead of a reach violation. The lag compensator and the 0.005 epsilon forgive the small position interpolation error on legit 3.0-3.1 hits, but a 4+ block attack is far outside that envelope.

anticheat AttackFrequency (per-second attack caps)

AttackFrequency.java114 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.net;
16
17
import org.bukkit.entity.Player;
18
19
import fr.neatmonster.nocheatplus.actions.ParameterName;
20
import fr.neatmonster.nocheatplus.checks.Check;
21
import fr.neatmonster.nocheatplus.checks.CheckType;
22
import fr.neatmonster.nocheatplus.checks.ViolationData;
23
import fr.neatmonster.nocheatplus.players.IPlayerData;
24
import fr.neatmonster.nocheatplus.utilities.TickTask;
25
26
public class AttackFrequency extends Check {
27
28
    public AttackFrequency() {
29
        super(CheckType.NET_ATTACKFREQUENCY);
30
    }
31
32
    /**
33
     * Checks a player
34
     * (Checks hasBypass on violation only)
35
     * 
36
     * @param player
37
     * @param time milliseconds
38
     * @param data
39
     * @param cc
40
     * @param pData
41
     * @return true if successful
42
     */
43
    public boolean check(final Player player, final long time, final NetData data, final NetConfig cc, final IPlayerData pData) {
44
        // Update frequency.
45
        data.attackFrequencySeconds.add(time, 1f);
46
        double maxVL = 0.0;
47
        float maxLimit = 0f;
48
        String tags = null;
49
        // TODO: option to normalize the vl / stats to per second? 
50
        // HALF
51
        float sum = data.attackFrequencySeconds.bucketScore(0); // HALF
52
        float limit = cc.attackFrequencyLimitSecondsHalf;
53
        if (sum - limit > maxVL) {
54
            maxVL = sum - limit;
55
            maxLimit = limit;
56
            tags = "sec_half";
57
        }
58
        // ONE (update sum).
59
        sum += data.attackFrequencySeconds.bucketScore(1);
60
        limit = cc.attackFrequencyLimitSecondsOne;
61
        if (sum - limit > maxVL) {
62
            maxVL = sum - limit;
63
            maxLimit = limit;
64
            tags = "sec_one";
65
        }
66
        // TWO (update sum).
67
        sum += data.attackFrequencySeconds.sliceScore(2, 4, 1f);
68
        limit = cc.attackFrequencyLimitSecondsTwo;
69
        if (sum - limit > maxVL) {
70
            maxVL = sum - limit;
71
            maxLimit = limit;
72
            tags = "sec_two";
73
        }
74
        // FOUR (update sum).
75
        sum += data.attackFrequencySeconds.sliceScore(4, 8, 1f);
76
        limit = cc.attackFrequencyLimitSecondsFour;
77
        if (sum - limit > maxVL) {
78
            maxVL = sum - limit;
79
            maxLimit = limit;
80
            tags = "sec_four";
81
        }
82
        // EIGHT (update sum).
83
        sum += data.attackFrequencySeconds.sliceScore(8, 16, 1f);
84
        limit = cc.attackFrequencyLimitSecondsEight;
85
        if (sum - limit > maxVL) {
86
            maxVL = sum - limit;
87
            maxLimit = limit;
88
            tags = "sec_eight";
89
        }
90
91
        if (pData.isDebugActive(CheckType.NET_ATTACKFREQUENCY)) {
92
            player.sendMessage("AttackFrequency: " + data.attackFrequencySeconds.toLine());
93
        }
94
95
        boolean cancel = false;
96
        if (maxVL > 0.0) {
97
            // Trigger a violation.
98
            final ViolationData vd = new ViolationData(this, player, maxVL, 1.0, cc.attackFrequencyActions);
99
            if (pData.isDebugActive(type) || vd.needsParameters()) {
100
                vd.setParameter(ParameterName.PACKETS, Integer.toString((int) sum));
101
                vd.setParameter(ParameterName.LIMIT, Integer.toString((int) maxLimit));
102
                vd.setParameter(ParameterName.TAGS, tags);
103
            }
104
            cancel = executeActions(vd).willCancel();
105
            // Feed Improbable.
106
            if (cc.attackFrequencyImprobableWeight > 0.0f) {
107
            	TickTask.requestImprobableUpdate(player.getUniqueId(), cc.attackFrequencyImprobableWeight);
108
            }
109
        }
110
111
        return cancel;
112
    }
113
114
}

How it counteracts this module

The ProtocolLib UseEntityAdapter feeds every USE_ENTITY packet through action interpretation (legacy reflection for 1.7, enum wrappers for newer) and counts only ATTACK actions into attackFrequencySeconds, an ActionFrequency of 16 buckets x 500ms spanning 8 seconds. Each packet checks five windows - 500ms (limit 8), 1s (15), 2s (30), 4s (60), 8s (95) - and raises a violation the moment any sum exceeds its limit, feeding Improbable with weight 3.0 and defaulting to cancel at vl>10.\n\nTenacity's attack stream is a strict 1000/cps periodic series (the TimerUtil resets on every fire), which makes it easy to score: at the default 10 CPS all five windows stay under their caps, but the module's range goes to 100. A sustained 16 CPS trips the 1s and 2s caps, 17+ trips the 500ms cap, and anything above 30 trips the 2s window immediately; at 100 CPS every window overflows on the first second. Extra Randomization's 1-2x interval multiplier halves the effective rate on multiplier-2 draws, which delays but does not eliminate the violation at high CPS, and because the stream is perfectly periodic when randomization is off, the 8s window accumulates the excess without any bursty averaging-out.

anticheat KillAura (direction / noswing / reach / speed)

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 composite KillAura check runs from FightListener.onFight on the damage event at HIGHEST priority and applies five sub-checks with config defaults max-direction-angle 1.2 radians, max-swing-time 80ms, max-reach 4.2, max-attacks 16/s and max-attack-packets 20/s. Direction measures the angle between the player's look vector and the attacked entity, Multi compares the angles to two consecutive targets, NoSwing demands an arm swing within 80ms of the attack, Reach measures the distance to the entity position minus its velocity, and Speed counts attacks and attack packets per second with a per-second reset.\n\nAgainst Tenacity the reach sub-check bites as soon as the Reach setting exceeds 4.2 (the module allows up to 8), so the default 4 passes but any extension flags every hit with the measured distance. The speed sub-checks counter the CPS range: more than 16 attacks in a second (CPS 17+) trips max-attacks, and more than 20 attack packets in a second (CPS 21+) trips max-attack-packets, so the default 10 CPS passes but the upper half of the 1-100 range is exposed. Direction passes because the yaw is snapped onto the target, and NoSwing passes because swingItem() precedes every C02 - the same two components that let Memeware's blockhit aura pass those branches.

← Back to Analysis Hub