Memeware 7.3 Commands module 2 files, 230 lines

Memeware 7.3 Commands: Full Source Analysis

Memeware 7.3's Commands module is a chat-packet firewall: one LWJEB handler on the outgoing packet bus watches every C01PacketChatMessage, cancels any message whose text starts with the '.' prefix…

me/memewaredevs/client/module/misc/Commands.java · GitHub source ↗

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

Packets This Module Uses

Analysis

Overview

Memeware 7.3's Commands module is a chat-packet firewall: one LWJEB handler on the outgoing packet bus watches every C01PacketChatMessage, cancels any message whose text starts with the '.' prefix before it can reach the wire, and dispatches the stripped command word to a hardcoded switch table. The server never sees the client's command language at all - the cancellation happens on the local event bus, so commands like .vclip, .hclip, .t and .toggle are purely client-side state changes. What the server does see is the residue: .say re-sends its payload as a fresh C01 prefixed with the private-use character U+F705, and the clip commands teleport the player through the normal movement path, both of which are ordinary, legitimate-looking traffic.

Architecture

The whole module is a single public field, eventConsumer0, a Consumer<PacketOutEvent> annotated with LWJEB's @Handler, so it runs synchronously for every outbound packet. The body filters on C01PacketChatMessage, splits the message on one-or-more spaces into args, and derives the command word as args[0] with every '.' removed (String.replace, not replaceFirst, so a first token like '..help' also resolves to 'help'). The 'say' boolean gate is a dead flag: it is declared false, never written anywhere, so the interception branch is always taken. Cancellation is ordered before dispatch - event.cancel() runs first, then the switch - so even a command branch that throws leaves the packet dead and the server none the wiser. The prefix is an instance field defaulting to '.', mutated only by the .prefix command itself.

Command dispatch

The switch covers eleven commands. .bind resolves a module by name, looks up an LWJGL key index, and writes the bind into the module's key field; .help prints a hardcoded command list; .vclip and .hclip parse a double and teleport the player - vclip via setPositionAndUpdate, which immediately enqueues a position packet, hclip via setPosition, whose offset is picked up by the next movement tick; .name copies the player name to the AWT system clipboard; .t and .toggle both resolve a module by (possibly multi-word) name and call toggle(); .clientname and .clientedition rewrite the public static branding strings that other parts of the client display; .prefix changes the instance prefix. Two bugs are worth noting: .bind guards with args[2] != null, but String.split never returns null elements, so a two-token invocation throws ArrayIndexOutOfBoundsException instead of hitting the usage branch (harmless server-side because the packet was already cancelled), and the .say branch rebuilds its payload from args[1..] and re-sends it via sendChatMessage with U+F705 prepended, which is why .say output is not re-intercepted: the re-emitted message starts with the private-use character, not the dot prefix.

Server-visible residue

From the server's point of view the module mostly does not exist: dot-prefixed chat never arrives, so no anticheat check on incoming chat can attribute .bind, .t or .prefix to the user. The leak surface is threefold. .say turns 'hello' into a message that begins with the Unicode private-use code point U+F705, a character no legitimate client produces, visible to any server that inspects chat text. The clip commands move the player through C03/C06 position packets the same way a manual teleport would, so a movement anticheat sees an instantaneous position change of exactly the requested amount. Everything else the user types passes through untouched, which is the module's real value: it taxes the user's outgoing chat stream without adding any distinguishing traffic of its own.

source Commands.java (dot-prefix interceptor)

Commands.java208 lines · JavaOriginal ↗
1
package me.memewaredevs.client.module.misc;
2
3
import me.hippo.api.lwjeb.annotation.Handler;
4
import me.memewaredevs.client.Memeware;
5
import me.memewaredevs.client.event.events.PacketOutEvent;
6
import me.memewaredevs.client.module.Module;
7
import me.memewaredevs.client.util.ChatUtil;
8
import net.minecraft.network.Packet;
9
import net.minecraft.network.play.client.C01PacketChatMessage;
10
import org.lwjgl.input.Keyboard;
11
12
import java.awt.*;
13
import java.awt.datatransfer.Clipboard;
14
import java.awt.datatransfer.StringSelection;
15
import java.util.Arrays;
16
import java.util.function.Consumer;
17
18
public class Commands extends Module {
19
20
    private boolean say = false;
21
22
    public static String clientName = "Memeware";
23
    public static String editionName = "Value Patch Edition";
24
    private String prefix = ".";
25
26
    public Commands() {
27
        super("Commands", 0, Module.Category.MISC);
28
    }
29
30
    @Handler
31
    public Consumer<PacketOutEvent> eventConsumer0 = (event) -> {
32
        Packet p = event.getPacket();
33
        if (p instanceof C01PacketChatMessage) {
34
            C01PacketChatMessage packet = (C01PacketChatMessage) p;
35
            String msg = packet.getMessage();
36
            String[] args = msg.split(" +");
37
            String cmd = args[0].replace(this.prefix, "").toLowerCase();
38
            if (!say) {
39
                if (msg.startsWith(this.prefix)) {
40
                    event.cancel();
41
                    switch (cmd) {
42
                        case "bind": {
43
                            if (args[2] != null) {
44
                                Module m = Memeware.INSTANCE.getModuleManager().getModule(args[1]);
45
                                if (m != null) {
46
                                    int key = Keyboard.getKeyIndex(args[2].toUpperCase());
47
                                    if (key != -1) {
48
                                        m.setKeyBind(key);
49
                                        ChatUtil.printChat("Successfully set bind to "
50
                                                + Keyboard.getKeyName(key) + ".");
51
                                    } else {
52
                                        ChatUtil.printChat("Invalid command usage! Correct usage: .bind [module] [key]");
53
                                    }
54
                                } else {
55
                                    ChatUtil.printChat("Invalid command usage! Correct usage: .bind [module] [key]");
56
                                }
57
                            } else {
58
                                ChatUtil.printChat("Invalid command usage! Correct usage: .bind [module] [key]");
59
                            }
60
                            break;
61
                        }
62
                        case "help": {
63
                            String[] cmds = new String[] {".help", ".prefix [key]", ".bind [module] [key]", ".vclip [amount]", ".hclip [amount]", ".name", ".say [message]", ".t [module]", ".toggle [module]", ".clientname [name]", ".clientedition [edition]"};
64
                            for (String s : cmds) {
65
                                ChatUtil.printChat(s);
66
                            }
67
                            break;
68
                        }
69
                        case "vclip": {
70
                            if (args[1] != null) {
71
                                try {
72
                                    mc.thePlayer.setPositionAndUpdate(mc.thePlayer.posX, mc.thePlayer.posY + Double.parseDouble(args[1]), mc.thePlayer.posZ);
73
                                    ChatUtil.printChat("VClip'd " + Double.parseDouble(args[1]) + " blocks.");
74
                                } catch (Exception e) {
75
                                    ChatUtil.printChat("Invalid command usage! Correct usage: .vclip [amount]");
76
                                    e.printStackTrace();
77
                                }
78
                            } else {
79
                                ChatUtil.printChat("Invalid command usage! Correct usage: .vclip [amount]");
80
                            }
81
                            break;
82
                        }
83
                        case "hclip": {
84
                            if (args[1] != null) {
85
                                try {
86
                                    double yaw = Math.toRadians(mc.thePlayer.rotationYaw);
87
                                    double distance = Double.parseDouble(args[1]);
88
                                    mc.thePlayer.setPosition(mc.thePlayer.posX + -Math.sin(yaw) * distance, mc.thePlayer.posY, mc.thePlayer.posZ + Math.cos(yaw) * distance);
89
                                    ChatUtil.printChat("HClip'd " + Double.parseDouble(args[1]) + " blocks.");
90
                                } catch (Exception e) {
91
                                    ChatUtil.printChat("Invalid command usage! Correct usage: .hclip [amount]");
92
                                    e.printStackTrace();
93
                                }
94
                            } else {
95
                                ChatUtil.printChat("Invalid command usage! Correct usage: .hclip [amount]");
96
                            }
97
                            break;
98
                        }
99
                        case "name": {
100
                            String name = mc.thePlayer.getName();
101
                            StringSelection stringSelection = new StringSelection(name);
102
                            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
103
                            clipboard.setContents(stringSelection, null);
104
                            ChatUtil.printChat("Copied your username to the clipboard!");
105
                            break;
106
                        }
107
                        case "say": {
108
                            if (args[1] != null) {
109
                                try {
110
                                    String[] bruh = Arrays.copyOfRange(args, 1, args.length);
111
                                    String msg1 = String.join(" ", bruh);
112
                                    mc.thePlayer.sendChatMessage("\uF705" + msg1);
113
                                    ChatUtil.printChat("Said your chat message!");
114
                                } catch (Exception e) {
115
                                    ChatUtil.printChat("Invalid command usage! Correct usage: .say [message]");
116
                                    e.printStackTrace();
117
                                }
118
                            } else {
119
                                ChatUtil.printChat("Invalid command usage! Correct usage: .say [message]");
120
                            }
121
                            break;
122
                        }
123
                        case "t": {
124
                            if (args[1] != null) {
125
                                try {
126
                                    String[] bruh = Arrays.copyOfRange(args, 1, args.length);
127
                                    String module = String.join(" ", bruh);
128
                                    Memeware.INSTANCE.getModuleManager().getModule(module).toggle();
129
                                    ChatUtil.printChat("Toggled " + module.toUpperCase() + ".");
130
                                } catch (Exception e) {
131
                                    ChatUtil.printChat("Invalid command usage! Correct usage: .t [module]");
132
                                    e.printStackTrace();
133
                                }
134
                            } else {
135
                                ChatUtil.printChat("Invalid command usage! Correct usage: .t [module]");
136
                            }
137
                            break;
138
                        }
139
                        case "toggle": {
140
                            if (args[1] != null) {
141
                                try {
142
                                    String[] bruh = Arrays.copyOfRange(args, 1, args.length);
143
                                    String module = String.join(" ", bruh);
144
                                    Memeware.INSTANCE.getModuleManager().getModule(module).toggle();
145
                                    ChatUtil.printChat("Toggled " + module.toUpperCase() + ".");
146
                                } catch (Exception e) {
147
                                    ChatUtil.printChat("Invalid command usage! Correct usage: .toggle [module]");
148
                                    e.printStackTrace();
149
                                }
150
                            } else {
151
                                ChatUtil.printChat("Invalid command usage! Correct usage: .toggle [module]");
152
                            }
153
                            break;
154
                        }
155
                        case "clientname": {
156
                            if (args[1] != null) {
157
                                try {
158
                                    String[] bruh = Arrays.copyOfRange(args, 1, args.length);
159
                                    String aeiofhneaon = String.join(" ", bruh);
160
                                    this.clientName = aeiofhneaon;
161
                                    ChatUtil.printChat("Client name set to " + aeiofhneaon + ".");
162
                                } catch (Exception e) {
163
                                    ChatUtil.printChat("Invalid command usage! Correct usage: .clientname [name]");
164
                                    e.printStackTrace();
165
                                }
166
                            } else {
167
                                ChatUtil.printChat("Invalid command usage! Correct usage: .clientname [name]");
168
                            }
169
                            break;
170
                        }
171
                        case "clientedition": {
172
                            if (args[1] != null) {
173
                                try {
174
                                    String[] bruh = Arrays.copyOfRange(args, 1, args.length);
175
                                    String aeiofhneaon = String.join(" ", bruh);
176
                                    this.editionName = aeiofhneaon;
177
                                    ChatUtil.printChat("Client Edition set to " + aeiofhneaon + ".");
178
                                } catch (Exception e) {
179
                                    ChatUtil.printChat("Invalid command usage! Correct usage: .clientedition [edition]");
180
                                    e.printStackTrace();
181
                                }
182
                            } else {
183
                                ChatUtil.printChat("Invalid command usage! Correct usage: .clientedition [edition]");
184
                            }
185
                            break;
186
                        }
187
                        case "prefix": {
188
                            if (args[1] != null) {
189
                                try {
190
                                    String[] bruh = Arrays.copyOfRange(args, 1, args.length);
191
                                    String aeiofhneaon = String.join(" ", bruh);
192
                                    this.prefix = aeiofhneaon;
193
                                    ChatUtil.printChat("Prefix set to " + aeiofhneaon);
194
                                } catch (Exception e) {
195
                                    ChatUtil.printChat("Invalid command usage! Correct usage: .prefix [key]");
196
                                    e.printStackTrace();
197
                                }
198
                            } else {
199
                                ChatUtil.printChat("Invalid command usage! Correct usage: .prefix [key]");
200
                            }
201
                            break;
202
                        }
203
                    }
204
                }
205
            }
206
        }
207
    };
208
}

What this file does

The entire module is the eventConsumer0 field: a @Handler consumer over PacketOutEvent that filters C01PacketChatMessage, cancels any message starting with the dot prefix, and dispatches the stripped first token through the switch. The dispatch targets only local state: Module key binds, Module.toggle(), the clipboard, the static clientName and editionName branding strings, and the instance prefix field. The position commands are the only branches with a network effect, and even those go through the vanilla movement path rather than a crafted packet. The 'say' field is never assigned, so the interception branch always runs; the args[2] null guard on .bind is ineffective because split never yields nulls, and the resulting AIOOBE propagates out of the consumer after the packet is already cancelled. The .say branch joins args[1..], prepends U+F705, and calls sendChatMessage, producing a second C01 that escapes re-interception because it no longer starts with '.'. ChatUtil.printChat is the output channel for every branch's feedback line.

source ChatUtil.java (command feedback channel)

ChatUtil.java22 lines · JavaOriginal ↗
1
2
package me.memewaredevs.client.util;
3
4
import me.memewaredevs.client.util.misc.MinecraftUtil;
5
import net.minecraft.network.play.client.C01PacketChatMessage;
6
import net.minecraft.util.ChatComponentText;
7
8
public class ChatUtil implements MinecraftUtil {
9
10
    public static void printChat(final String text) {
11
        mc.thePlayer.addChatComponentMessage(new ChatComponentText("\u00a78[\u00a79Memeware\u00a78]\u00a7f " + text));
12
    }
13
14
    public static void printChatFlag(final String text) {
15
        mc.thePlayer.addChatComponentMessage(new ChatComponentText("\u00a78[\u00a79MAC\u00a78]\u00a7f " + text));
16
    }
17
18
    public static void sendChat(final String text) {
19
        mc.thePlayer.sendQueue.addToSendQueue(new C01PacketChatMessage(text));
20
    }
21
22
}

What this file does

ChatUtil is the local output path every Commands branch uses. printChat appends a '[Memeware]'-prefixed ChatComponentText to the local player's chat via addChatComponentMessage - purely client-side rendering, never a packet. printChatFlag does the same with a '[MAC]' prefix, and is the channel the HackerDetect module reuses for its flag lines. sendChat is the one method with a wire effect: it builds a C01PacketChatMessage and pushes it straight through mc.thePlayer.sendQueue.addToSendQueue, the same queue path vanilla chat uses. The Spammer module calls sendChat once per second, and because those messages never start with '.', they pass the Commands interceptor's startsWith check untouched. The class implements MinecraftUtil, which supplies the mc field, and its three methods are static so any module can call them without a reference.

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 NoCheatPlus Commands (server-side command rate)

Commands.java117 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.chat;
16
17
import org.bukkit.entity.Player;
18
19
import fr.neatmonster.nocheatplus.checks.Check;
20
import fr.neatmonster.nocheatplus.checks.CheckType;
21
import fr.neatmonster.nocheatplus.players.IPlayerData;
22
import fr.neatmonster.nocheatplus.utilities.ColorUtil;
23
import fr.neatmonster.nocheatplus.utilities.TickTask;
24
25
/**
26
 * Check only for commands
27
 * @author asofold
28
 *
29
 */
30
public class Commands extends Check {
31
32
    public Commands() {
33
        super(CheckType.CHAT_COMMANDS);
34
    }
35
    
36
    /**
37
     * Checks a player for command spam
38
     * 
39
     * @param player
40
     * @param message
41
     * @param cc
42
     * @param pData
43
     * @param captcha
44
     * @return true if successful.
45
     */
46
    public boolean check(final Player player, final String message, 
47
                         final ChatConfig cc, final IPlayerData pData, 
48
                         final ICaptcha captcha) {
49
50
        final long now = System.currentTimeMillis();
51
        final int tick = TickTask.getTick();
52
        final ChatData data = pData.getGenericInstance(ChatData.class);
53
        final boolean captchaEnabled = !cc.captchaSkipCommands && pData.isCheckActive(CheckType.CHAT_CAPTCHA, player); 
54
        if (captchaEnabled){
55
            synchronized (data) {
56
                if (captcha.shouldCheckCaptcha(player, cc, data, pData)){
57
                    captcha.checkCaptcha(player, message, cc, data, true);
58
                    return true;
59
                }
60
            }
61
        }
62
63
        // Rest of the check is done without sync, because the data is only used by this check.
64
        // Weight might later be read from some prefix tree (also known / unknown).
65
        final float weight = 1f;
66
        data.commandsWeights.add(now, weight);
67
        if (tick < data.commandsShortTermTick) {
68
            // TickTask got reset.
69
            data.commandsShortTermTick = tick;
70
            data.commandsShortTermWeight = 1.0;
71
        }
72
        else if (tick - data.commandsShortTermTick < cc.commandsShortTermTicks) {
73
            if (!pData.getCurrentWorldData().shouldAdjustToLag(type) 
74
                || TickTask.getLag(50L * (tick - data.commandsShortTermTick), true) < 1.3f) {
75
                // Add up.
76
                data.commandsShortTermWeight += weight;
77
            }
78
            else {
79
                // Reset, too much lag.
80
                data.commandsShortTermTick = tick;
81
                data.commandsShortTermWeight = 1.0;
82
            }
83
        }
84
        else{
85
            // Reset.
86
            data.commandsShortTermTick = tick;
87
            data.commandsShortTermWeight = 1.0;
88
        }
89
90
        final float nw = data.commandsWeights.score(1f);
91
        final double violation = Math.max(nw - cc.commandsLevel, data.commandsShortTermWeight - cc.commandsShortTermLevel);
92
93
        if (violation > 0.0) {
94
            data.commandsVL += violation;
95
            // TODO: Evaluate if sync(data) is necessary or better for executeActions.
96
            if (captchaEnabled) {
97
                synchronized (data) {
98
                    captcha.sendNewCaptcha(player, cc, data);
99
                }
100
                return true;
101
            }
102
            else if (executeActions(player, data.commandsVL, violation, cc.commandsActions).willCancel()) {
103
                return true;
104
            }
105
        }
106
        else if (cc.chatWarningCheck && now - data.chatWarningTime > cc.chatWarningTimeout && (100f * nw / cc.commandsLevel > cc.chatWarningLevel || 100f * data.commandsShortTermWeight / cc.commandsShortTermLevel > cc.chatWarningLevel)){
107
            player.sendMessage(ColorUtil.replaceColors(cc.chatWarningMessage));
108
            data.chatWarningTime = now;
109
        }
110
        else {
111
            // TODO: This might need invalidation with time.
112
            data.commandsVL *= 0.99;
113
        }
114
        return false;
115
    }
116
117
}

How it counteracts this module

NCP's Commands check (CheckType.CHAT_COMMANDS) is the server-side counterpart to this module, and its own comment states the premise: 'We listen to PlayerCommandPreprocess events because commands can be used for spamming too.' It scores every '/'-prefixed input with a weight of 1.0 into data.commandsWeights, an ActionFrequency (line 66), and separately accumulates commandsShortTermWeight over a window of cc.commandsShortTermTicks (lines 67-88), resetting the short-term counter when TickTask lag exceeds 1.3. The violation is max(windowScore - cc.commandsLevel, shortTermWeight - cc.commandsShortTermLevel) (line 91); a positive value adds to commandsVL and either arms a captcha (when CHAT_CAPTCHA is active and captchaSkipCommands is off, lines 53-61) or runs cc.commandsActions (line 102).

The honest limitation is structural: the Memeware module cancels its dot-commands on the client event bus before the C01 is ever enqueued, so no server event, including PlayerCommandPreprocessEvent, can fire for them. This check therefore only governs the command traffic the module does not touch - normal '/' commands the same user types, and any other command the client forwards. What it still does is bound that residue: a user who mixes server commands into the same session is scored like anyone else, and the short-term window catches bursts of '/'-prefixed input the way the module's own switch table never could, because the client has no equivalent rate limit on what it lets through.

anticheat NoCheatPlus Text (message content and frequency)

Text.java331 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.chat;
16
17
import java.util.Collections;
18
import java.util.LinkedList;
19
import java.util.List;
20
import java.util.Map;
21
22
import org.bukkit.entity.Player;
23
24
import fr.neatmonster.nocheatplus.NCPAPIProvider;
25
import fr.neatmonster.nocheatplus.checks.Check;
26
import fr.neatmonster.nocheatplus.checks.CheckType;
27
import fr.neatmonster.nocheatplus.checks.chat.analysis.MessageLetterCount;
28
import fr.neatmonster.nocheatplus.checks.chat.analysis.WordLetterCount;
29
import fr.neatmonster.nocheatplus.checks.chat.analysis.engine.LetterEngine;
30
import fr.neatmonster.nocheatplus.checks.combined.CombinedData;
31
import fr.neatmonster.nocheatplus.components.NoCheatPlusAPI;
32
import fr.neatmonster.nocheatplus.components.registry.feature.INotifyReload;
33
import fr.neatmonster.nocheatplus.config.ConfigFile;
34
import fr.neatmonster.nocheatplus.config.ConfigManager;
35
import fr.neatmonster.nocheatplus.players.IPlayerData;
36
import fr.neatmonster.nocheatplus.utilities.ColorUtil;
37
import fr.neatmonster.nocheatplus.utilities.StringUtil;
38
39
/**
40
 * Some alternative more or less advanced analysis methods.
41
 * @author asofold
42
 *
43
 */
44
public class Text extends Check implements INotifyReload {
45
46
    private LetterEngine engine = null;
47
48
    /** Not really cancelled but above threshold for actions. */
49
    private String lastCancelledMessage = "";
50
    private long lastCancelledTime = 0;
51
52
    private String lastGlobalMessage = "";
53
    private long lastGlobalTime = 0;
54
55
    public Text() {
56
        super(CheckType.CHAT_TEXT);
57
        init();
58
    }
59
60
    /**
61
     * Start analysis.
62
     * @param player
63
     *          The player who issued the message.
64
     * @param message
65
     *          The message to check.
66
     * @param captcha 
67
     *          Used for starting captcha on failure, if configured so.
68
     * @param alreadyCancelled 
69
     * @return
70
     */
71
    public boolean check(final Player player, final String message, 
72
                         final ChatConfig cc, final IPlayerData pData,
73
                         final ICaptcha captcha, boolean isMainThread, final boolean alreadyCancelled) {
74
        final ChatData data = pData.getGenericInstance(ChatData.class);
75
        synchronized (data) {
76
            return unsafeCheck(player, message, captcha, cc, data, pData, isMainThread, alreadyCancelled);
77
        }
78
    }
79
80
    private void init() {
81
        // Set some things from the global config.
82
        final ConfigFile config = ConfigManager.getConfigFile();
83
        final NoCheatPlusAPI api = NCPAPIProvider.getNoCheatPlusAPI();
84
        if (engine != null) {
85
            engine.clear();
86
            api.removeComponent(engine);
87
        }
88
        engine = new LetterEngine(config);
89
        api.addComponent(engine);
90
    }
91
92
    @Override
93
    public void onReload() {
94
        synchronized(engine) {
95
            engine.clear();
96
        }
97
        init();
98
    }
99
100
    /**
101
     * Check without further synchronization.
102
     * @param player
103
     * @param message
104
     * @param captcha
105
     * @param cc
106
     * @param data
107
     * @param isMainThread 
108
     * @param alreadyCancelled 
109
     * @return
110
     */
111
    private boolean unsafeCheck(final Player player, final String message, final ICaptcha captcha,
112
                                final ChatConfig cc, final ChatData data, final IPlayerData pData,
113
                                boolean isMainThread, final boolean alreadyCancelled) {
114
115
        // Test captcha.
116
        if (captcha.shouldCheckCaptcha(player, cc, data, pData)) {
117
            captcha.checkCaptcha(player, message, cc, data, isMainThread);
118
            return true;
119
        } 
120
        else if (alreadyCancelled) {
121
            // Skip checking.
122
            return true;
123
        }
124
125
        final long time = System.currentTimeMillis();
126
        final String lcMessage = message.trim().toLowerCase();
127
        boolean cancel = false;
128
        final boolean debug = pData.isDebugActive(type);
129
        final List<String> debugParts;
130
        if (debug) {
131
            debugParts = new LinkedList<String>();
132
            debugParts.add("Message (length=" + message.length()+"): ");
133
        }
134
        else debugParts = null;
135
136
        // Update the frequency interval weights.
137
        data.chatFrequency.update(time);
138
139
        // Score for this message (violation score).
140
        float score = 0;
141
        final MessageLetterCount letterCounts = new MessageLetterCount(message);
142
        final int msgLen = message.length();
143
144
145
146
        // (Following: random/made up criteria.)
147
        // TODO: Create tests for all methods with wordlists, fake chat (refactor for that).
148
        // Full message processing. ------------
149
        // Upper case.
150
        if (letterCounts.fullCount.upperCase > msgLen / 3) {
151
            // TODO: Regard chunks of 48 or so letters of the message for this?
152
            final float wUpperCase = 0.6f * letterCounts.fullCount.getUpperCaseRatio();
153
            score += wUpperCase  * cc.textMessageUpperCase;
154
        }
155
156
        // Letters vs. word length.
157
        if (msgLen > 4) {
158
            final float fullRep = letterCounts.fullCount.getLetterCountRatio();
159
            // Long messages: very small and very big are bad !
160
            // 128 is a quick attempt to make one long message possible on 1.11.
161
            final float wRepetition = (float) Math.min(msgLen, 128) / 15.0f * Math.abs(0.5f - fullRep);
162
            score += wRepetition * cc.textMessageLetterCount;
163
164
            // Number of words vs. length of message
165
            final float fnWords = (float) letterCounts.words.length / (float) msgLen;
166
            if (fnWords > 0.75f) { // TODO: balance or configure or remove ?
167
                score += fnWords  * cc.textMessagePartition;
168
            }
169
        }
170
171
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
172
        final long timeout = 8000; // TODO: maybe set dynamically in data.
173
        // Repetition of last message.
174
        if (cc.textMsgRepeatSelf != 0f && time - data.chatLastTime < timeout) {
175
            if (StringUtil.isSimilar(lcMessage, data.chatLastMessage, 0.8f)) {
176
                final float timeWeight = (float) (timeout - (time - data.chatLastTime)) / (float) timeout; 
177
                score += cc.textMsgRepeatSelf * timeWeight;
178
            }
179
        }
180
        // Repetition of last global message.
181
        if (cc.textMsgRepeatGlobal != 0f && time - lastGlobalTime < timeout) {
182
            if (StringUtil.isSimilar(lcMessage, lastGlobalMessage, 0.8f)) {
183
                final float timeWeight = (float) (timeout - (time - lastGlobalTime)) / (float) timeout; 
184
                score += cc.textMsgRepeatGlobal * timeWeight;
185
            }
186
        }
187
        // Repetition of last cancelled message.
188
        if (cc.textMsgRepeatCancel != 0f && time - lastCancelledTime < timeout) {
189
            if (StringUtil.isSimilar(lcMessage, lastCancelledMessage, 0.8f)) {
190
                final float timeWeight = (float) (timeout - (time - lastCancelledTime)) / (float) timeout; 
191
                score += cc.textMsgRepeatCancel * timeWeight;
192
            }
193
        }
194
        // Chat quickly after join.
195
        if (cc.textMsgAfterJoin != 0f && time - cData.lastJoinTime < timeout) {
196
            final float timeWeight = (float) (timeout - (time - cData.lastJoinTime)) / (float) timeout;
197
            score += cc.textMsgAfterJoin * timeWeight; 
198
        }
199
        // Chat without moving.
200
        if (cc.textMsgNoMoving != 0f && time - cData.lastMoveTime > timeout) {
201
            score += cc.textMsgNoMoving;
202
        }
203
204
205
206
        // Per word checks. -------------------
207
        float wWords = 0.0f;
208
        final float avwLen = (float) msgLen / (float) letterCounts.words.length; 
209
        for (final WordLetterCount word : letterCounts.words) {
210
            float wWord = 0.0f;
211
            final int wLen = word.word.length();
212
            // TODO: ? used letters vs. word length.
213
214
            // Length of word vs. av. word length.
215
            final float fLenAv = Math.abs(avwLen - (float) wLen) / avwLen;
216
            wWord += fLenAv * cc.textMessageLengthAv;
217
218
            // Length of word vs. message length;
219
            final float fLenMsg = (float) wLen / (float) msgLen;
220
            wWord += fLenMsg * cc.textMessageLengthMsg;
221
222
            // Not letter:
223
            float notLetter = word.getNotLetterRatio();
224
            notLetter *= notLetter;
225
            wWord += notLetter * cc.textMessageNoLetter;
226
227
            wWord *= wWord; // TODO: quadratic ? (configurable)
228
            wWords += wWord;
229
        }
230
        wWords /= (float) letterCounts.words.length;
231
        score += wWords;
232
233
        if (debug && score > 0f) {
234
            debugParts.add("Simple score: " + StringUtil.fdec3.format(score));
235
        }
236
237
        // Engine:
238
        // TODO: more fine grained sync !
239
        float wEngine = 0f;
240
        final Map<String, Float> engMap;
241
        synchronized (engine) {
242
            engMap = engine.process(letterCounts, player.getName(), cc, data);
243
            // TODO: more fine grained sync !s
244
            // TODO: different methods (add or max or add+max or something else).
245
            for (final Float res : engMap.values()) {
246
                if (cc.textEngineMaximum) {
247
                    wEngine = Math.max(wEngine, res.floatValue());
248
                }
249
                else wEngine += res.floatValue();
250
            }
251
        }
252
        score += wEngine;
253
254
255
        // Wrapping it up. --------------------
256
        // Add weight to frequency counts.
257
        final float normalScore = Math.max(cc.textFreqNormMin, score);
258
        data.chatFrequency.add(time, normalScore);
259
        final float accumulated = cc.textFreqNormWeight * data.chatFrequency.score(cc.textFreqNormFactor);
260
        final boolean normalViolation = accumulated > cc.textFreqNormLevel;
261
        final float shortTermScore = Math.max(cc.textFreqShortTermMin, score);
262
        data.chatShortTermFrequency.add(time, shortTermScore);
263
        // TODO: very short term (1st bucket) or do it indirectly.
264
        final float shortTermAccumulated = cc.textFreqShortTermWeight * data.chatShortTermFrequency.score(cc.textFreqShortTermFactor);
265
        final boolean shortTermViolation = shortTermAccumulated > cc.textFreqShortTermLevel;
266
267
        if (normalViolation || shortTermViolation) {
268
            lastCancelledMessage = lcMessage;
269
            lastCancelledTime = time;
270
271
            final double added;
272
            if (shortTermViolation) {
273
                added = (shortTermAccumulated - cc.textFreqShortTermLevel)/ 3.0;
274
            } 
275
            else added = (accumulated - cc.textFreqNormLevel) / 10.0; 
276
            data.textVL += added;
277
278
            if (captcha.shouldStartCaptcha(player, cc, data, pData)) {
279
                captcha.sendNewCaptcha(player, cc, data);
280
                cancel = true;
281
            }
282
            else {
283
                if (shortTermViolation) {
284
                    if (executeActions(player, data.textVL, added, cc.textFreqShortTermActions).willCancel()) {
285
                        cancel = true;
286
                    }
287
                }
288
                else if (normalViolation) {
289
                    if (executeActions(player, data.textVL, added, cc.textFreqNormActions).willCancel()) {
290
                        cancel = true;
291
                    }
292
                }
293
            }
294
        }
295
        else if (cc.chatWarningCheck && time - data.chatWarningTime > cc.chatWarningTimeout && (100f * accumulated / cc.textFreqNormLevel > cc.chatWarningLevel || 100f * shortTermAccumulated / cc.textFreqShortTermLevel > cc.chatWarningLevel)) {
296
            NCPAPIProvider.getNoCheatPlusAPI().sendMessageOnTick(player.getName(), ColorUtil.replaceColors(cc.chatWarningMessage));
297
            data.chatWarningTime = time;
298
        }
299
        else {
300
            data.textVL *= 0.95;
301
            if (cc.textAllowVLReset && normalScore < 2.0f * cc.textFreqNormWeight && shortTermScore < 2.0f * cc.textFreqShortTermWeight) {
302
                // Reset the VL.
303
                // Maybe elaborate on resetting conditions (after some timeout just divide by two or so?).
304
                data.textVL = 0.0;
305
            }
306
        }
307
308
        if (debug) {
309
            final List<String> keys = new LinkedList<String>(engMap.keySet());
310
            Collections.sort(keys);
311
            for (String key : keys) {
312
                Float s = engMap.get(key);
313
                if (s.floatValue() > 0.0f)
314
                    debugParts.add(key + ":" + StringUtil.fdec3.format(s));
315
            }
316
            if (wEngine > 0.0f)
317
                debugParts.add("Engine score (" + (cc.textEngineMaximum?"max":"sum") + "): " + StringUtil.fdec3.format(wEngine));
318
319
            debugParts.add("Final score: " +  StringUtil.fdec3.format(score));
320
            debugParts.add("Normal: min=" +  StringUtil.fdec3.format(cc.textFreqNormMin) +", weight=" +  StringUtil.fdec3.format(cc.textFreqNormWeight) + " => accumulated=" + StringUtil.fdec3.format(accumulated));
321
            debugParts.add("Short-term: min=" +  StringUtil.fdec3.format(cc.textFreqShortTermMin) +", weight=" +  StringUtil.fdec3.format(cc.textFreqShortTermWeight) + " => accumulated=" + StringUtil.fdec3.format(shortTermAccumulated));
322
            debugParts.add("vl: " + StringUtil.fdec3.format(data.textVL));
323
            debug(player, StringUtil.join(debugParts, " | "));
324
            debugParts.clear();
325
        }
326
327
        lastGlobalMessage = data.chatLastMessage = lcMessage;
328
        lastGlobalTime = data.chatLastTime = time;
329
        return cancel;
330
    }
331
}

How it counteracts this module

NCP's Text check (CheckType.CHAT_TEXT) runs on every AsyncPlayerChatEvent at LOWEST priority (ChatListener.onPlayerChat) and scores the message content itself. A per-message score is built from letter statistics: upperCase ratio beyond a third of the message (line 150), letter-count ratio and word-partition ratio for messages longer than 4 characters (lines 157-169), and per-word length and notLetter scores, the latter squared (lines 209-231). Every message then feeds two ActionFrequency accumulators, chatFrequency and chatShortTermFrequency, each with a minimum score floor and a weighted window score compared against cc.textFreqNormLevel / cc.textFreqShortTermLevel (lines 257-265); a violation adds to textVL and triggers a captcha or the configured actions (lines 267-294). The same message text is also compared for similarity against the player's previous message within 8000ms via StringUtil.isSimilar(..., 0.8f) (lines 174-179), and flat penalties apply for chatting within 8 seconds of joining and after 8 seconds without moving (lines 194-202).

For this module the check sees exactly the residue the interceptor lets through. The .say output starts with U+F705, a private-use code point that is not a letter, so the first word carries a non-letter ratio that is squared into the per-word score, and repeated .say invocations re-emit identical text that trips the 8-second repeat-similarity comparison. The frequency accumulators score every chat message the user sends between commands at the module's normal chat rate. The dot-commands themselves stay invisible: cancellation happens client-side, so NCP's Bukkit event never sees them.

anticheat NoCheatPlus Captcha (chat gate)

Captcha.java115 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.chat;
16
17
import java.util.concurrent.ThreadLocalRandom;
18
19
import org.bukkit.entity.Player;
20
21
import fr.neatmonster.nocheatplus.checks.Check;
22
import fr.neatmonster.nocheatplus.checks.CheckType;
23
import fr.neatmonster.nocheatplus.players.DataManager;
24
import fr.neatmonster.nocheatplus.players.IPlayerData;
25
import fr.neatmonster.nocheatplus.utilities.ColorUtil;
26
27
/**
28
 * NOTE: EARLY REFACTORING STATE, MOST METHODS NEED SYNC OVER DATA !
29
 * @author mc_dev
30
 *
31
 */
32
public class Captcha extends Check implements ICaptcha{
33
34
    public Captcha() {
35
        super(CheckType.CHAT_CAPTCHA);
36
    }
37
38
    @Override
39
    public void checkCaptcha(Player player, String message, ChatConfig cc, ChatData data, boolean isMainThread) {
40
        // Correct answer to the captcha?
41
        if (message.equals(data.captchaGenerated)) {
42
            // Yes, clear their data and do not worry anymore about them.
43
            data.reset();
44
            data.captchaStarted = false;
45
            player.sendMessage(ColorUtil.replaceColors(cc.captchaSuccess));
46
        } 
47
        else {
48
            // Increment their tries number counter.
49
            data.captchTries++;
50
            data.captchaVL ++;
51
            // Have they failed too man times?
52
            if (data.captchTries > cc.captchaTries) {
53
                // Find out if we need to kick the player or not.
54
                executeActions(player, data.captchaVL, 1, cc.captchaActions);
55
                // (Resetting captcha tries is done on quit/kick).
56
            }
57
            // Display the question again (if not kicked).
58
            if (player.isOnline()) {
59
                sendCaptcha(player, cc, data);
60
            }
61
        }
62
    }
63
64
    @Override
65
    public void sendNewCaptcha(Player player, ChatConfig cc, ChatData data) {
66
        // Display a captcha to the player.
67
        generateCaptcha(cc, data, true);
68
        sendCaptcha(player, cc, data);
69
        data.captchaStarted = true;
70
    }
71
72
    @Override
73
    public void generateCaptcha(ChatConfig cc, ChatData data, boolean reset) {
74
        if (reset) data.captchTries = 0;
75
        final char[] chars = new char[cc.captchaLength];
76
        for (int i = 0; i < cc.captchaLength; i++) {
77
            chars[i] = cc.captchaCharacters.charAt(ThreadLocalRandom.current().nextInt(cc.captchaCharacters.length()));
78
        }
79
        data.captchaGenerated = new String(chars);
80
    }
81
82
    @Override
83
    public void resetCaptcha(Player player){
84
        final IPlayerData pData = DataManager.getPlayerData(player);
85
        ChatData data = pData.getGenericInstance(ChatData.class);
86
        synchronized (data) {
87
            resetCaptcha(player, pData.getGenericInstance(ChatConfig.class), data, pData);
88
        }
89
    }
90
91
    @Override
92
    public void resetCaptcha(Player player, ChatConfig cc, ChatData data, IPlayerData pData) {
93
        data.captchTries = 0;
94
        if (shouldCheckCaptcha(player, cc, data, pData) || shouldStartCaptcha(player, cc, data, pData)){
95
            generateCaptcha(cc, data, true);
96
        }
97
    }
98
99
    @Override
100
    public void sendCaptcha(Player player, ChatConfig cc, ChatData data) {
101
        player.sendMessage(ColorUtil.replaceColors(cc.captchaQuestion.replace("[captcha]", data.captchaGenerated)));
102
    }
103
104
    @Override
105
    public boolean shouldStartCaptcha(Player player, ChatConfig cc, ChatData data, IPlayerData pData) {
106
        // TODO: Only call if IWorldData.isCheckActive(CHAT_CAPTCHA) has returned true?
107
        return !data.captchaStarted && pData.isCheckActive(CheckType.CHAT_CAPTCHA, player);
108
    }
109
110
    @Override
111
    public boolean shouldCheckCaptcha(Player player, ChatConfig cc, ChatData data, IPlayerData pData) {
112
        // TODO: Only call if IWorldData.isCheckActive(CHAT_CAPTCHA) has returned true?
113
        return data.captchaStarted  && pData.isCheckActive(CheckType.CHAT_CAPTCHA, player);
114
    }
115
}

How it counteracts this module

Captcha is the enforcement arm both chat checks share. shouldStartCaptcha (lines 105-108) returns true while CHAT_CAPTCHA is active and no captcha has been started, and Text calls it on every violation (Text line 278), while the Commands check arms it directly when captchaSkipCommands is disabled (Commands lines 53-61). sendNewCaptcha generates a random string of cc.captchaLength characters from cc.captchaCharacters, stores it in data.captchaGenerated, and sends the question to the player (lines 65-70). checkCaptcha then accepts exactly one answer: message.equals(data.captchaGenerated) (line 41). Anything else increments captchTries and captchaVL, re-displays the question, and once captchTries exceeds cc.captchaTries executes cc.captchaActions (lines 47-61) - the configured kick/ban ladder.

The module has no captcha-answer path: it is a switch table over local commands, and a user in the middle of a command session who trips either chat check must type the exact generated string to clear the flag. There is no command in the switch that can echo the captcha text, so the gate stays armed until the user manually types the answer - which is precisely the interaction a chat-automation client is built to avoid.

← Back to Analysis Hub