Rise 5.99 NameProtect module 2 files, 558 lines

Rise 5.99 NameProtect: Full Source Analysis

NameProtect is a render-only module whose entire implementation is a static enabled flag.

dev/rise/module/impl/other/NameProtect.java · GitHub source ↗

Published 2026-08-13 · Updated 2026-08-13

Packets This Module Uses

Analysis

Overview

NameProtect is a render-only module whose entire implementation is a static enabled flag. The real behavior lives in the client's custom TTF font renderer: TTFFontRenderer.drawString replaces every occurrence of the player's own name in any string it renders with 'Rise User' while the flag is set, which covers nametags, chat lines and HUD text that route through the renderer. The module sends no packets and rewrites no incoming packets; the server already knows the name because it authored the messages. The C17 chip is the identity-carrying payload family the module is often grouped with, but the module never touches it.

Static flag surface

The module body is a boolean: onEnable sets the public static enabled flag, onDisable clears it, and nothing else exists. Rise's font pipeline reads the flag directly: TTFFontRenderer.drawString checks NameProtect.enabled at three call sites and substitutes the player name before the glyph pass. The sibling Streamer module follows the same pattern with a player list, replacing each listed name with 'Player'. The module is registered in ProtectedLaunch's module array like every other Rise module.

Replacement mechanics

The substitution is a regex replace: text.replaceAll(mc.thePlayer.getName(), "Rise User"). Because the name is treated as a regular expression pattern, a player name containing metacharacters such as a dot or a dollar sign makes the pattern malformed and the render call throws PatternSyntaxException, breaking the draw path for that frame; the module is only safe for plain alphanumeric names. The replacement applies anywhere the name appears in rendered strings, so nametags, the chat feed and scoreboard-style HUD lines all show the alias.

Wire silence

Nothing leaves the client and no inbound packet is modified: the S02 chat messages, S0C spawns and S3F team updates that carry the name pass through untouched, and the server-side identity, used by staff commands, chat formatting and scoreboards, is unaffected. The hiding is purely a local display transformation, which is why every server-side check below is an honest gap.

source NameProtect.java

NameProtect.java28 lines · JavaOriginal ↗
1
/*
2
 Copyright Alan Wood 2021
3
 None of this code to be reused without my written permission
4
 Intellectual Rights owned by Alan Wood
5
 */
6
package dev.rise.module.impl.other;
7
8
import dev.rise.module.Module;
9
import dev.rise.module.api.ModuleInfo;
10
import dev.rise.module.enums.Category;
11
12
@ModuleInfo(name = "NameProtect", description = "Hides your name", category = Category.RENDER)
13
public final class NameProtect extends Module {
14
    public static boolean enabled;
15
    // FontRenderer class
16
17
18
    @Override
19
    protected void onEnable() {
20
        enabled = true;
21
    }
22
23
    @Override
24
    protected void onDisable() {
25
        enabled = false;
26
    }
27
28
}

What this file does

The module file: the static enabled flag with its enable and disable lifecycle and nothing else. The absence of handlers is the finding; the module is a state switch for the font renderer.

source TTFFontRenderer.java (name substitution)

TTFFontRenderer.java530 lines · JavaOriginal ↗
1
package dev.rise.font.fontrenderer;
2
3
import dev.rise.module.impl.other.NameProtect;
4
import dev.rise.module.impl.render.Streamer;
5
import net.minecraft.client.Minecraft;
6
import net.minecraft.client.renderer.GlStateManager;
7
import net.minecraft.util.MathHelper;
8
import org.lwjgl.BufferUtils;
9
import org.lwjgl.opengl.GL11;
10
import org.lwjgl.util.vector.Vector2f;
11
import store.intent.intentguard.annotation.Exclude;
12
import store.intent.intentguard.annotation.Strategy;
13
14
import java.awt.*;
15
import java.awt.geom.Rectangle2D;
16
import java.awt.image.BufferedImage;
17
import java.nio.ByteBuffer;
18
import java.util.Locale;
19
import java.util.concurrent.ConcurrentLinkedQueue;
20
import java.util.concurrent.ExecutorService;
21
22
@Exclude({Strategy.NUMBER_OBFUSCATION, Strategy.FLOW_OBFUSCATION})
23
public class TTFFontRenderer {
24
25
    private final boolean antiAlias;
26
    private final Font font;
27
    private boolean fractionalMetrics;
28
    private CharacterData[] regularData;
29
    private CharacterData[] boldData;
30
    private CharacterData[] italicsData;
31
    private final int[] colorCodes;
32
    private static int RANDOM_OFFSET;
33
34
    public TTFFontRenderer(final ExecutorService executorService, final ConcurrentLinkedQueue<TextureData> textureQueue, final Font font) {
35
        this(executorService, textureQueue, font, 256);
36
    }
37
38
    public TTFFontRenderer(final ExecutorService executorService, final ConcurrentLinkedQueue<TextureData> textureQueue, final Font font, final int characterCount) {
39
        this(executorService, textureQueue, font, characterCount, true);
40
    }
41
42
    public TTFFontRenderer(final ExecutorService executorService, final ConcurrentLinkedQueue<TextureData> textureQueue, final Font font, final boolean antiAlias) {
43
        this(executorService, textureQueue, font, 256, antiAlias);
44
    }
45
46
    public TTFFontRenderer(final ExecutorService executorService, final ConcurrentLinkedQueue<TextureData> textureQueue, final Font font, final int characterCount, final boolean antiAlias) {
47
        this.fractionalMetrics = false;
48
        this.colorCodes = new int[32];
49
        this.font = font;
50
        this.fractionalMetrics = true;
51
        this.antiAlias = antiAlias;
52
        final int[] regularTexturesIds = new int[characterCount];
53
        final int[] boldTexturesIds = new int[characterCount];
54
        final int[] italicTexturesIds = new int[characterCount];
55
        for (int i = 0; i < characterCount; ++i) {
56
            regularTexturesIds[i] = GL11.glGenTextures();
57
            boldTexturesIds[i] = GL11.glGenTextures();
58
            italicTexturesIds[i] = GL11.glGenTextures();
59
        }
60
        executorService.execute(() -> this.regularData = this.setup(new CharacterData[characterCount], regularTexturesIds, textureQueue, 0));
61
        executorService.execute(() -> this.boldData = this.setup(new CharacterData[characterCount], boldTexturesIds, textureQueue, 1));
62
        executorService.execute(() -> this.italicsData = this.setup(new CharacterData[characterCount], italicTexturesIds, textureQueue, 2));
63
    }
64
65
    private CharacterData[] setup(final CharacterData[] characterData, final int[] texturesIds, final ConcurrentLinkedQueue<TextureData> textureQueue, final int type) {
66
        this.generateColors();
67
        final Font font = this.font.deriveFont(type);
68
        final BufferedImage utilityImage = new BufferedImage(1, 1, 2);
69
        final Graphics2D utilityGraphics = (Graphics2D) utilityImage.getGraphics();
70
        utilityGraphics.setFont(font);
71
        final FontMetrics fontMetrics = utilityGraphics.getFontMetrics();
72
73
74
        for (int index = 0; index < characterData.length; ++index) {
75
            final char character = (char) index;
76
            final Rectangle2D characterBounds = fontMetrics.getStringBounds(character + "", utilityGraphics);
77
            final float width = (float) characterBounds.getWidth() + 8.0f;
78
            final float height = (float) characterBounds.getHeight();
79
            final BufferedImage characterImage = new BufferedImage(MathHelper.ceiling_double_int(width), MathHelper.ceiling_double_int(height), 2);
80
            final Graphics2D graphics = (Graphics2D) characterImage.getGraphics();
81
            graphics.setFont(font);
82
            graphics.setColor(new Color(255, 255, 255, 0));
83
            graphics.fillRect(0, 0, characterImage.getWidth(), characterImage.getHeight());
84
            graphics.setColor(Color.WHITE);
85
            if (this.antiAlias) {
86
                graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
87
                graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
88
                graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
89
                graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, this.fractionalMetrics ? RenderingHints.VALUE_FRACTIONALMETRICS_ON : RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
90
            }
91
            graphics.drawString(character + "", 4, fontMetrics.getAscent());
92
            final int textureId = texturesIds[index];
93
            this.createTexture(textureId, characterImage, textureQueue);
94
            characterData[index] = new CharacterData(character, (float) characterImage.getWidth(), (float) characterImage.getHeight(), textureId);
95
        }
96
        return characterData;
97
    }
98
99
    private void createTexture(final int textureId, final BufferedImage image, final ConcurrentLinkedQueue<TextureData> textureQueue) {
100
        final int[] pixels = new int[image.getWidth() * image.getHeight()];
101
        image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
102
        final ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);
103
        for (int y = 0; y < image.getHeight(); ++y) {
104
            for (int x = 0; x < image.getWidth(); ++x) {
105
                final int pixel = pixels[y * image.getWidth() + x];
106
                buffer.put((byte) (pixel >> 16 & 0xFF));
107
                buffer.put((byte) (pixel >> 8 & 0xFF));
108
                buffer.put((byte) (pixel & 0xFF));
109
                buffer.put((byte) (pixel >> 24 & 0xFF));
110
            }
111
        }
112
        buffer.flip();
113
        textureQueue.add(new TextureData(textureId, image.getWidth(), image.getHeight(), buffer));
114
    }
115
116
    public void drawString(final String text, final float x, final float y, final int color) {
117
        GlStateManager.enableAlpha();
118
        GlStateManager.disableBlend();
119
        this.renderString(text, x, y, color, false);
120
    }
121
122
    public void drawStringWithColorCode(final String text, final float x, final float y, final int color) {
123
        GlStateManager.disableAlpha();
124
        GlStateManager.disableBlend();
125
        this.renderString(text, x, y, color, false, true);
126
    }
127
128
    public void drawCenteredString(final String text, final float x, final float y, final int color) {
129
        final float width = this.getWidth(text) / 2.0f;
130
        this.renderString(text, x - width, y, color, false);
131
    }
132
133
    public void drawStringWithShadow(final String text, final float x, final float y, final int color) {
134
        GL11.glTranslated(0.5, 0.5, 0.0);
135
        this.renderString(text, x, y, color, true);
136
        GL11.glTranslated(-0.5, -0.5, 0.0);
137
        this.renderString(text, x, y, color, false);
138
    }
139
140
    public void drawCenteredStringWithShadow(final String text, final float x, final float y, final int color) {
141
        final float width = this.getWidth(text) / 2.0f;
142
143
        GL11.glTranslated(0.5, 0.5, 0.0);
144
        this.renderString(text, x - width, y, color, true);
145
        GL11.glTranslated(-0.5, -0.5, 0.0);
146
        this.renderString(text, x - width, y, color, false);
147
    }
148
149
    private int renderString(String text, float x, float y, final int color, final boolean shadow) {
150
        if (text.equals("") || text.length() == 0) {
151
            return 0;
152
        }
153
154
        x = Math.round(x * 10.0F) / 10.0F;
155
        y = Math.round(y * 10.0F) / 10.0F;
156
157
        final Minecraft mc = Minecraft.getMinecraft();
158
159
        if (mc != null && mc.thePlayer != null && mc.theWorld != null && mc.thePlayer.getName() != null && text.length() > 1) {
160
            if (NameProtect.enabled) {
161
                text = text.replaceAll(mc.thePlayer.getName(), "Rise User");
162
            }
163
164
            if (Streamer.enabled) {
165
                for (final String s : Streamer.PLAYERS) {
166
                    text = text.replaceAll(s, "Player");
167
                }
168
            }
169
        }
170
171
        GL11.glPushMatrix();
172
        GlStateManager.scale(0.5, 0.5, 1.0);
173
        GlStateManager.enableBlend();
174
        GlStateManager.blendFunc(770, 771);
175
176
        x -= 2.0f;
177
        y -= 2.0f;
178
        x += 0.5f;
179
        y += 0.5f;
180
        x *= 2.0f;
181
        y *= 2.0f;
182
183
        final CharacterData[] characterData = this.regularData;
184
185
        final int length = text.length();
186
        final double multiplier = 255.0 * (shadow ? 4 : 1);
187
188
        final Color c = new Color(color);
189
190
        GL11.glColor4d(c.getRed() / multiplier, c.getGreen() / multiplier, c.getBlue() / multiplier, (color >> 24 & 0xFF) / 255.0);
191
192
        try {
193
            for (int i = 0; i < length; ++i) {
194
                final char character = text.charAt(i);
195
                this.drawChar(character, characterData, x, y);
196
197
                if (character >= characterData.length) continue;
198
199
                final CharacterData charData = characterData[character];
200
                x += charData.width - 8.0f;
201
            }
202
        } catch (final StringIndexOutOfBoundsException ex) {
203
            System.out.println("[Rise] Couldn't render text");
204
            ex.printStackTrace();
205
        }
206
207
        GL11.glPopMatrix();
208
        GlStateManager.disableBlend();
209
        GlStateManager.bindTexture(0);
210
        GlStateManager.resetColor();
211
212
        return (int) x;
213
    }
214
215
    private int renderString(String text, float x, float y, final int color, final boolean shadow, final boolean nickga) {
216
        if (text.equals("") || text.length() == 0) {
217
            return 0;
218
        }
219
220
        x = Math.round(x * 10.0F) / 10.0F;
221
        y = Math.round(y * 10.0F) / 10.0F;
222
223
        final Minecraft mc = Minecraft.getMinecraft();
224
225
        if (mc != null && mc.thePlayer != null && mc.theWorld != null && mc.thePlayer.getName() != null && text.length() > 1) {
226
            if (NameProtect.enabled) {
227
                text = text.replaceAll(mc.thePlayer.getName(), "Rise User");
228
            }
229
230
            if (Streamer.enabled) {
231
                for (final String s : Streamer.PLAYERS) {
232
                    text = text.replaceAll(s, "Player");
233
                }
234
            }
235
        }
236
237
        GL11.glPushMatrix();
238
        GlStateManager.scale(0.5, 0.5, 1.0);
239
        GlStateManager.enableBlend();
240
        GlStateManager.blendFunc(770, 771);
241
242
        x -= 2.0f;
243
        y -= 2.0f;
244
        x += 0.5f;
245
        y += 0.5f;
246
        x *= 2.0f;
247
        y *= 2.0f;
248
249
        CharacterData[] characterData = this.regularData;
250
        boolean underlined = false;
251
        boolean strikethrough = false;
252
        boolean obfuscated = false;
253
        final int length = text.length();
254
        final double multiplier = 255.0 * (shadow ? 4 : 1);
255
        final Color c = new Color(color);
256
        GL11.glColor4d(c.getRed() / multiplier, c.getGreen() / multiplier, c.getBlue() / multiplier, (color >> 24 & 0xFF) / 255.0);
257
        for (int i = 0; i < length; ++i) {
258
            char character = text.charAt(i);
259
            final char previous = (i > 0) ? text.charAt(i - 1) : '.';
260
            if (previous != '§') {
261
                if (character == '§') {
262
                    try {
263
                        int index = "0123456789abcdefklmnor".indexOf(text.toLowerCase(Locale.ENGLISH).charAt(i + 1));
264
                        if (index < 16) {
265
                            obfuscated = false;
266
                            strikethrough = false;
267
                            underlined = false;
268
                            characterData = this.regularData;
269
                            if (index < 0) {
270
                                index = 15;
271
                            }
272
                            if (shadow) {
273
                                index += 16;
274
                            }
275
                            final int textColor = this.colorCodes[index];
276
                            GL11.glColor4d((textColor >> 16) / 255.0, (textColor >> 8 & 0xFF) / 255.0, (textColor & 0xFF) / 255.0, (color >> 24 & 0xFF) / 255.0);
277
                        } else if (index <= 20) {
278
                            switch (index) {
279
                                case 16:
280
                                    obfuscated = true;
281
                                    break;
282
283
                                case 17:
284
                                    characterData = this.boldData;
285
                                    break;
286
287
                                case 18:
288
                                    strikethrough = true;
289
                                    break;
290
291
                                case 19:
292
                                    underlined = true;
293
                                    break;
294
295
                                case 20:
296
                                    characterData = this.italicsData;
297
                                    break;
298
                            }
299
                        } else {
300
                            obfuscated = false;
301
                            strikethrough = false;
302
                            underlined = false;
303
                            characterData = this.regularData;
304
                            GL11.glColor4d((shadow ? 0.25 : 1.0), (shadow ? 0.25 : 1.0), (shadow ? 0.25 : 1.0), (color >> 24 & 0xFF) / 255.0);
305
                        }
306
307
                    } catch (final StringIndexOutOfBoundsException ignored) {
308
                    }
309
                } else if (character <= '\u00ff') {
310
                    if (obfuscated) {
311
                        character += (char) TTFFontRenderer.RANDOM_OFFSET;
312
                    }
313
                    this.drawChar(character, characterData, x, y);
314
                    final CharacterData charData = characterData[character];
315
                    if (strikethrough) {
316
                        this.drawLine(new Vector2f(0.0f, charData.height / 2.0f), new Vector2f(charData.width, charData.height / 2.0f), 3.0f);
317
                    }
318
                    if (underlined) {
319
                        this.drawLine(new Vector2f(0.0f, charData.height - 15.0f), new Vector2f(charData.width, charData.height - 15.0f), 3.0f);
320
                    }
321
                    x += charData.width - 8.0f;
322
                }
323
            }
324
        }
325
326
        GL11.glPopMatrix();
327
        GlStateManager.disableBlend();
328
        GlStateManager.bindTexture(0);
329
        GlStateManager.resetColor();
330
331
        return (int) x;
332
    }
333
334
    public float getWidth(final String text) {
335
        float width = 0.0f;
336
        final CharacterData[] characterData = this.regularData;
337
338
        try {
339
            for (int length = text.length(), i = 0; i < length; ++i) {
340
                final char character = text.charAt(i);
341
342
                final CharacterData charData = characterData[character];
343
                width += (charData.width - 8.0f) / 2.0f;
344
            }
345
        } catch (final ArrayIndexOutOfBoundsException e) {
346
            return getWidth("A");
347
        }
348
349
        return width + 2.0f;
350
    }
351
352
    public float getWidthProtect(String text) {
353
        final Minecraft mc = Minecraft.getMinecraft();
354
355
        if (mc != null && mc.thePlayer != null && mc.theWorld != null && mc.thePlayer.getName() != null && text.length() > 1) {
356
            if (NameProtect.enabled) {
357
                text = text.replaceAll(mc.thePlayer.getName(), "Rise User");
358
            }
359
360
            if (Streamer.enabled) {
361
                for (final String s : Streamer.PLAYERS) {
362
                    text = text.replaceAll(s, "Player");
363
                }
364
            }
365
        }
366
367
        float width = 0.0f;
368
        final CharacterData[] characterData = this.regularData;
369
370
        for (int length = text.length(), i = 0; i < length; ++i) {
371
            final char character = text.charAt(i);
372
373
            final CharacterData charData = characterData[character];
374
            width += (charData.width - 8.0f) / 2.0f;
375
        }
376
377
        return width + 2.0f;
378
    }
379
380
    public float getHeight(final String text) {
381
        float height = 0.0f;
382
        final CharacterData[] characterData = this.regularData;
383
384
        for (int length = text.length(), i = 0; i < length; ++i) {
385
            final char character = text.charAt(i);
386
            final CharacterData charData = characterData[character];
387
            height = Math.max(height, charData.height);
388
        }
389
390
        return height / 2.0f - 2.0f;
391
    }
392
393
    public float getHeight() {
394
        return getHeight("I");
395
    }
396
397
    private void drawChar(final char character, final CharacterData[] characterData, final float x, final float y) {
398
        if (character >= characterData.length) return;
399
400
        final CharacterData charData = characterData[character];
401
        charData.bind();
402
403
        GL11.glBegin(6);
404
        GL11.glTexCoord2f(0.0f, 0.0f);
405
        GL11.glVertex2d(x, y);
406
        GL11.glTexCoord2f(0.0f, 1.0f);
407
        GL11.glVertex2d(x, y + charData.height);
408
        GL11.glTexCoord2f(1.0f, 1.0f);
409
        GL11.glVertex2d(x + charData.width, y + charData.height);
410
        GL11.glTexCoord2f(1.0f, 0.0f);
411
        GL11.glVertex2d(x + charData.width, y);
412
        GL11.glEnd();
413
    }
414
415
    private void drawLine(final Vector2f start, final Vector2f end) {
416
        GL11.glDisable(3553);
417
        GL11.glLineWidth((float) 3.0);
418
        GL11.glBegin(1);
419
        GL11.glVertex2f(start.x, start.y);
420
        GL11.glVertex2f(end.x, end.y);
421
        GL11.glEnd();
422
        GL11.glEnable(3553);
423
    }
424
425
    private void drawLine(final Vector2f start, final Vector2f end, final float width) {
426
        GL11.glDisable(3553);
427
        GL11.glLineWidth(width);
428
        GL11.glBegin(1);
429
        GL11.glVertex2f(start.x, start.y);
430
        GL11.glVertex2f(end.x, end.y);
431
        GL11.glEnd();
432
        GL11.glEnable(3553);
433
    }
434
435
    private void generateColors() {
436
        for (int i = 0; i < 32; ++i) {
437
            final int thingy = (i >> 3 & 0x1) * 85;
438
            int red = (i >> 2 & 0x1) * 170 + thingy;
439
            int green = (i >> 1 & 0x1) * 170 + thingy;
440
            int blue = (i & 0x1) * 170 + thingy;
441
            if (i == 6) {
442
                red += 85;
443
            }
444
            if (i >= 16) {
445
                red /= 4;
446
                green /= 4;
447
                blue /= 4;
448
            }
449
            this.colorCodes[i] = ((red & 0xFF) << 16 | (green & 0xFF) << 8 | (blue & 0xFF));
450
        }
451
    }
452
453
    static {
454
        TTFFontRenderer.RANDOM_OFFSET = 1;
455
    }
456
457
    static class CharacterData {
458
        public char character;
459
        public float width;
460
        public float height;
461
        private final int textureId;
462
463
        public CharacterData(final char character, final float width, final float height, final int textureId) {
464
            this.character = character;
465
            this.width = width;
466
            this.height = height;
467
            this.textureId = textureId;
468
        }
469
470
        public void bind() {
471
            GL11.glBindTexture(3553, this.textureId);
472
        }
473
    }
474
475
    /**
476
     * Trims a string to fit a specified Width.
477
     */
478
    public String trimStringToWidth(final String text, final int width) {
479
        return this.trimStringToWidth(text, width, false);
480
    }
481
482
    /**
483
     * Trims a string to a specified width, and will reverse it if par3 is set.
484
     */
485
    public String trimStringToWidth(final String text, final int width, final boolean reverse) {
486
        final StringBuilder stringbuilder = new StringBuilder();
487
        float f = 0.0F;
488
        final int i = reverse ? text.length() - 1 : 0;
489
        final int j = reverse ? -1 : 1;
490
        boolean flag = false;
491
        boolean flag1 = false;
492
493
        for (int k = i; k >= 0 && k < text.length() && f < (float) width; k += j) {
494
            final char c0 = text.charAt(k);
495
            final float f1 = this.getWidth(String.valueOf(c0));
496
497
            if (flag) {
498
                flag = false;
499
500
                if (c0 != 108 && c0 != 76) {
501
                    if (c0 == 114 || c0 == 82) {
502
                        flag1 = false;
503
                    }
504
                } else {
505
                    flag1 = true;
506
                }
507
            } else if (f1 < 0.0F) {
508
                flag = true;
509
            } else {
510
                f += f1;
511
512
                if (flag1) {
513
                    ++f;
514
                }
515
            }
516
517
            if (f > (float) width) {
518
                break;
519
            }
520
521
            if (reverse) {
522
                stringbuilder.insert(0, c0);
523
            } else {
524
                stringbuilder.append(c0);
525
            }
526
        }
527
528
        return stringbuilder.toString();
529
    }
530
}

What this file does

The consumer: drawString's NameProtect.enabled gates at lines 160, 226 and 356, with the replaceAll substitution to 'Rise User' and the sibling Streamer block that replaces listed names with 'Player'. It is the render pipeline where the alias is applied, which is the entire mechanism of the module.

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 chat Text (outgoing content scoring)

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 chat Text check scores outgoing C01 content: per-word notLetter ratios, squared before weighting, and the letter-count ratio against the 0.5 optimum feed frequency windows that drive textVL toward the captcha chain. NameProtect rewrites only the rendered form of incoming S02 text, so the check never sees the substitution and the outgoing stream is byte-identical. The entry is an honest gap that documents where name handling does and does not live.

anticheat chat Captcha (exact-match 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 an exact-match gate on the outgoing answer message when a captcha challenge is armed. The display-only alias has no influence on the wire message, so the gate behaves exactly as if the module were off. The name-hiding feature can neither help nor hurt captcha completion, which is the honest statement for this entry.

anticheat ChatUtility (formatter, not a check)

ChatUtility.java52 lines · Java
1
package me.vrekt.arc.chat;
2
3
import org.bukkit.ChatColor;
4
5
6
/**
7
 * Adapted from: https://www.spigotmc.org/threads/free-code-sending-perfectly-centered-chat-message.95872/
8
 */
9
public class ChatUtility {
10
11
    private final static int CENTER_PX = 154;
12
13
    /**
14
     * @param message the string to send
15
     * @return string that is centered.
16
     */
17
    public static String getCenteredMessage(String message) {
18
        if (message == null || message.equals("")) return null;
19
        message = ChatColor.translateAlternateColorCodes('&', message);
20
21
        int messagePxSize = 0;
22
        boolean previousCode = false;
23
        boolean isBold = false;
24
25
        for (char c : message.toCharArray()) {
26
            if (c == '§') {
27
                previousCode = true;
28
            } else if (previousCode) {
29
                previousCode = false;
30
                if (c == 'l' || c == 'L') {
31
                    isBold = true;
32
                } else isBold = false;
33
            } else {
34
                DefaultFontInfo dFI = DefaultFontInfo.getDefaultFontInfo(c);
35
                messagePxSize += isBold ? dFI.getBoldLength() : dFI.getLength();
36
                messagePxSize++;
37
            }
38
        }
39
40
        int halvedMessageSize = messagePxSize / 2;
41
        int toCompensate = CENTER_PX - halvedMessageSize;
42
        int spaceLength = DefaultFontInfo.SPACE.getLength() + 1;
43
        int compensated = 0;
44
        StringBuilder sb = new StringBuilder();
45
        while (compensated < toCompensate) {
46
            sb.append(" ");
47
            compensated += spaceLength;
48
        }
49
        return sb.toString() + message;
50
    }
51
52
}

How it counteracts this module

ChatUtility is the only chat-related file Arc v2 contributes to the S02 corpus, and it is not a check: it centers chat lines by padding with spaces around a fixed CENTER_PX 154 pixel width. There is no Arc v2 consumer of the name surface at all, so the module has no Arc-side exposure beyond this resolving rel, which is the honest gap statement.

anticheat PacketConverter8 (C17 protocol conversion)

PacketConverter8.java449 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.util.packet;
20
21
import io.netty.buffer.Unpooled;
22
import me.islandscout.hawk.HawkPlayer;
23
import me.islandscout.hawk.event.*;
24
import me.islandscout.hawk.event.bukkit.HawkAsyncPlayerAbilitiesEvent;
25
import me.islandscout.hawk.event.bukkit.HawkAsyncPlayerMetadataEvent;
26
import me.islandscout.hawk.event.bukkit.HawkAsyncPlayerTeleportEvent;
27
import me.islandscout.hawk.event.bukkit.HawkAsyncPlayerVelocityChangeEvent;
28
import me.islandscout.hawk.util.Debug;
29
import me.islandscout.hawk.util.ServerUtils;
30
import me.islandscout.hawk.wrap.WrappedWatchableObject;
31
import me.islandscout.hawk.wrap.packet.WrappedPacket;
32
import me.islandscout.hawk.wrap.packet.WrappedPacket8;
33
import net.minecraft.server.v1_8_R3.*;
34
import org.bukkit.*;
35
import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
36
import org.bukkit.entity.Player;
37
import org.bukkit.inventory.ItemStack;
38
import org.bukkit.util.Vector;
39
40
import java.io.IOException;
41
import java.util.ArrayList;
42
import java.util.List;
43
import java.util.Set;
44
45
public final class PacketConverter8 {
46
47
    private PacketConverter8() {
48
    }
49
50
    public static Event packetInboundToEvent(Object packet, Player p, HawkPlayer pp) {
51
        if (packet instanceof PacketPlayInFlying) return packetToPosEvent((PacketPlayInFlying) packet, p, pp);
52
        if (packet instanceof PacketPlayInUseEntity) return packetToInterEvent((PacketPlayInUseEntity) packet, p, pp);
53
        if (packet instanceof PacketPlayInBlockDig) return packetToDigEvent((PacketPlayInBlockDig) packet, p, pp);
54
        if (packet instanceof PacketPlayInCustomPayload)
55
            return packetToPayloadEvent((PacketPlayInCustomPayload) packet, p, pp);
56
        if (packet instanceof PacketPlayInAbilities)
57
            return packetToAbilitiesEvent((PacketPlayInAbilities) packet, p, pp);
58
        if (packet instanceof PacketPlayInBlockPlace)
59
            return packetToUseEvent((PacketPlayInBlockPlace) packet, p, pp);
60
        if (packet instanceof PacketPlayInArmAnimation)
61
            return packetToArmSwingEvent((PacketPlayInArmAnimation) packet, p, pp);
62
        if (packet instanceof PacketPlayInHeldItemSlot)
63
            return packetToItemSwitchEvent((PacketPlayInHeldItemSlot) packet, p, pp);
64
        if (packet instanceof PacketPlayInEntityAction)
65
            return packetToPlayerActionEvent((PacketPlayInEntityAction) packet, p, pp);
66
        if (packet instanceof PacketPlayInWindowClick)
67
            return packetToWindowClickEvent((PacketPlayInWindowClick) packet, p, pp);
68
        if(packet instanceof PacketPlayInClientCommand)
69
            return packetToOpenWindowEvent((PacketPlayInClientCommand) packet, p, pp);
70
        if(packet instanceof PacketPlayInCloseWindow)
71
            return packetToCloseWindowEvent((PacketPlayInCloseWindow) packet, p, pp);
72
        return null;
73
    }
74
75
    public static org.bukkit.event.Event packetOutboundToEvent(Object packet, Player p) {
76
        if(packet instanceof PacketPlayOutEntityVelocity || packet instanceof PacketPlayOutExplosion)
77
            return packetToVelocityEvent((Packet)packet, p);
78
        if(packet instanceof PacketPlayOutEntityMetadata)
79
            return packetToPlayerMetadataEvent((PacketPlayOutEntityMetadata)packet, p);
80
        if(packet instanceof PacketPlayOutPosition)
81
            return packetToPlayerTeleportEvent((PacketPlayOutPosition) packet, p);
82
        if(packet instanceof PacketPlayOutAbilities)
83
            return packetToPlayerAbilitiesOutEvent((PacketPlayOutAbilities) packet, p);
84
        return null;
85
    }
86
87
    private static HawkAsyncPlayerTeleportEvent packetToPlayerTeleportEvent(PacketPlayOutPosition packet, Player p) {
88
        PacketDataSerializer serializer = new PacketDataSerializer(Unpooled.buffer());
89
        try {
90
            packet.b(serializer);
91
92
            double x = serializer.readDouble();
93
            double y = serializer.readDouble();
94
            double z = serializer.readDouble();
95
            float yaw = serializer.readFloat();
96
            float pitch = serializer.readFloat();
97
            Set<PacketPlayOutPosition.EnumPlayerTeleportFlags> relMoveFlags = PacketPlayOutPosition.EnumPlayerTeleportFlags.a(serializer.readUnsignedByte());
98
99
            return new HawkAsyncPlayerTeleportEvent(p, x, y, z, yaw, pitch);
100
101
        } catch (Exception e) {
102
            e.printStackTrace();
103
        }
104
        return null;
105
    }
106
107
    private static HawkAsyncPlayerAbilitiesEvent packetToPlayerAbilitiesOutEvent(PacketPlayOutAbilities packet, Player p) {
108
        PacketDataSerializer serializer = new PacketDataSerializer(Unpooled.buffer(0));
109
        try {
110
            packet.b(serializer);
111
            byte mask = serializer.readByte();
112
            boolean invulnerable = (mask & 1) > 0;
113
            boolean flying = (mask & 2) > 0;
114
            boolean allowedToFly = (mask & 4) > 0;
115
            boolean creativeMode = (mask & 8) > 0;
116
            float flySpeed = serializer.readFloat();
117
            float walkSpeed = serializer.readFloat();
118
119
            return new HawkAsyncPlayerAbilitiesEvent(p, invulnerable, allowedToFly, flying, creativeMode, flySpeed, walkSpeed);
120
        }
121
        catch (IOException e) {
122
            e.printStackTrace();
123
        }
124
125
        return null;
126
    }
127
128
    private static HawkAsyncPlayerMetadataEvent packetToPlayerMetadataEvent(PacketPlayOutEntityMetadata packet, Player p) {
129
        PacketDataSerializer serializer = new PacketDataSerializer(Unpooled.buffer(0));
130
        try {
131
            packet.b(serializer);
132
            int id = serializer.e();
133
            List metaData = DataWatcher.b(serializer);
134
            if(id != p.getEntityId() || metaData == null)
135
                return null;
136
137
            List<WrappedWatchableObject> wrappedMetaData = new ArrayList<>();
138
            for(Object object : metaData) {
139
                if(object instanceof DataWatcher.WatchableObject) {
140
141
                    DataWatcher.WatchableObject wO = (DataWatcher.WatchableObject) object;
142
                    WrappedWatchableObject wwO = new WrappedWatchableObject(wO.c(), wO.a(), wO.b());
143
                    wwO.setWatched(wO.d());
144
145
                    wrappedMetaData.add(wwO);
146
                }
147
            }
148
            return new HawkAsyncPlayerMetadataEvent(p, wrappedMetaData);
149
        }
150
        catch (IOException e) {
151
            e.printStackTrace();
152
        }
153
        return null;
154
    }
155
156
    private static HawkAsyncPlayerVelocityChangeEvent packetToVelocityEvent(Packet packet, Player p) {
157
        if(packet instanceof PacketPlayOutExplosion) {
158
            PacketDataSerializer serializer = new PacketDataSerializer(Unpooled.buffer(0));
159
            try {
160
                packet.b(serializer);
161
            }
162
            catch (IOException e) {
163
                e.printStackTrace();
164
            }
165
            serializer.readerIndex(serializer.writerIndex() - 12);
166
            float x = serializer.readFloat();
167
            float y = serializer.readFloat();
168
            float z = serializer.readFloat();
169
            Vector velocity = new Vector(x, y, z);
170
            if(velocity.lengthSquared() == 0)
171
                return null;
172
            return new HawkAsyncPlayerVelocityChangeEvent(velocity, p, true);
173
        }
174
        else if(packet instanceof PacketPlayOutEntityVelocity) {
175
            PacketDataSerializer serializer = new PacketDataSerializer(Unpooled.buffer(0));
176
            try {
177
                packet.b(serializer);
178
            }
179
            catch (IOException e) {
180
                e.printStackTrace();
181
            }
182
            int id = serializer.e();
183
            if(id != p.getEntityId()) {
184
                return null;
185
            }
186
            double x = serializer.readShort() / 8000D;
187
            double y = serializer.readShort() / 8000D;
188
            double z = serializer.readShort() / 8000D;
189
            Vector velocity = new Vector(x, y, z);
190
191
            return new HawkAsyncPlayerVelocityChangeEvent(velocity, p, false);
192
        }
193
        return null;
194
    }
195
196
    private static Event packetToPosEvent(PacketPlayInFlying packet, Player p, HawkPlayer pp) {
197
        //default position
198
        Vector position = pp.getPosition();
199
        Location loc = new Location(pp.getWorld(), position.getX(), position.getY(), position.getZ(), pp.getYaw(), pp.getPitch());
200
201
        //There's an NPE here if someone teleports to another world using a dumb multi-world plugin (which sets the PlayerTeleportEvent#getTo() location to null)
202
        //I don't believe it is my responsibility to "fix" this. If there are enough complaints, I MIGHT consider looking into it.
203
        loc = new Location(pp.getWorld(), loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch());
204
205
        WrappedPacket.PacketType pType = WrappedPacket.PacketType.FLYING;
206
207
        //update if has look
208
        boolean updateRot = false;
209
        if (packet.h()) {
210
            updateRot = true;
211
            pType = WrappedPacket.PacketType.LOOK;
212
            loc.setYaw(packet.d());
213
            loc.setPitch(packet.e());
214
        }
215
216
        //update if has position
217
        boolean updatePos = false;
218
        if (packet.g()) {
219
            updatePos = true;
220
            if (packet.h())
221
                pType = WrappedPacket.PacketType.POSITION_LOOK;
222
            else
223
                pType = WrappedPacket.PacketType.POSITION;
224
            loc.setX(packet.a());
225
            loc.setY(packet.b());
226
            loc.setZ(packet.c());
227
        }
228
229
        if(Math.abs(loc.getX()) >= Integer.MAX_VALUE || Math.abs(loc.getY()) >= Integer.MAX_VALUE || Math.abs(loc.getZ()) >= Integer.MAX_VALUE ||
230
                Double.isNaN(loc.getX()) || Double.isNaN(loc.getY()) || Double.isNaN(loc.getZ())) {
231
            return new BadEvent(p, pp, new WrappedPacket8(packet, pType));
232
        }
233
234
        return new MoveEvent(p, loc, packet.f(), pp, new WrappedPacket8(packet, pType), updatePos, updateRot);
235
    }
236
237
    private static InteractEntityEvent packetToInterEvent(PacketPlayInUseEntity packet, Player p, HawkPlayer pp) {
238
        if (packet.a() == null) return null;
239
        InteractAction action;
240
        if (packet.a() == PacketPlayInUseEntity.EnumEntityUseAction.ATTACK) action = InteractAction.ATTACK;
241
        else action = InteractAction.INTERACT;
242
        //get interacted entity. phew.
243
        Entity nmsEntity = packet.a(((CraftWorld) pp.getWorld()).getHandle());
244
        if (nmsEntity == null) return null; //interacting with a non-existent entity
245
        org.bukkit.entity.Entity entity = nmsEntity.getBukkitEntity();
246
247
        Vector hitVec;
248
        Vec3D vec = packet.b();
249
        if(vec != null) {
250
            hitVec = new Vector(vec.a, vec.b, vec.c);
251
        }
252
        else {
253
            hitVec = null;
254
        }
255
256
        return new InteractEntityEvent(p, pp, action, entity, hitVec, new WrappedPacket8(packet, WrappedPacket.PacketType.USE_ENTITY));
257
    }
258
259
    private static Event packetToDigEvent(PacketPlayInBlockDig packet, Player p, HawkPlayer pp) {
260
        PacketPlayInBlockDig.EnumPlayerDigType digType = packet.c();
261
        BlockDigEvent.DigAction digAction = null;
262
        InteractItemEvent.Action interactAction = null;
263
        switch (digType) {
264
            case START_DESTROY_BLOCK:
265
                digAction = BlockDigEvent.DigAction.START;
266
                break;
267
            case ABORT_DESTROY_BLOCK:
268
                digAction = BlockDigEvent.DigAction.CANCEL;
269
                break;
270
            case STOP_DESTROY_BLOCK:
271
                digAction = BlockDigEvent.DigAction.COMPLETE;
272
                break;
273
            case RELEASE_USE_ITEM:
274
                interactAction = InteractItemEvent.Action.RELEASE_USE_ITEM;
275
                break;
276
            case DROP_ITEM:
277
                interactAction = InteractItemEvent.Action.DROP_HELD_ITEM;
278
                break;
279
            case DROP_ALL_ITEMS:
280
                interactAction = InteractItemEvent.Action.DROP_HELD_ITEM_STACK;
281
                break;
282
            default:
283
                return null;
284
        }
285
        if(interactAction == null) {
286
            BlockPosition pos = packet.a();
287
            Location loc = new Location(p.getWorld(), pos.getX(), pos.getY(), pos.getZ());
288
289
            org.bukkit.block.Block b = ServerUtils.getBlockAsync(loc);
290
            if(b == null)
291
                return null;
292
293
            return new BlockDigEvent(p, pp, digAction, b, new WrappedPacket8(packet, WrappedPacket.PacketType.BLOCK_DIG));
294
        }
295
        ItemStack item = p.getInventory().getItem(pp.getHeldItemSlot());
296
        if(item == null)
297
            return null;
298
        return new InteractItemEvent(p, pp, item, interactAction, new WrappedPacket8(packet, WrappedPacket.PacketType.BLOCK_DIG));
299
300
    }
301
302
    private static CustomPayLoadEvent packetToPayloadEvent(PacketPlayInCustomPayload packet, Player p, HawkPlayer pp) {
303
        return null;
304
    }
305
306
    private static AbilitiesEvent packetToAbilitiesEvent(PacketPlayInAbilities packet, Player p, HawkPlayer pp) {
307
        return new AbilitiesEvent(p, pp, packet.isFlying() && p.getAllowFlight(), new WrappedPacket8(packet, WrappedPacket.PacketType.ABILITIES));
308
    }
309
310
    //it appears that this gets called when interacting with blocks too
311
    private static Event packetToUseEvent(PacketPlayInBlockPlace packet, Player p, HawkPlayer pp) {
312
        org.bukkit.Material mat;
313
        if (packet.getItemStack() != null && packet.getItemStack().getItem() != null) {
314
            Block block = Block.asBlock(packet.getItemStack().getItem());
315
            //noinspection deprecation
316
            mat = org.bukkit.Material.getMaterial(Block.getId(block));
317
        } else {
318
            mat = null;
319
        }
320
321
        BlockPosition bPos = packet.a();
322
        int x = bPos.getX();
323
        int y = bPos.getY();
324
        int z = bPos.getZ();
325
        Vector targetedPosition = new Vector(x, y, z);
326
        InteractWorldEvent.BlockFace face;
327
        //Debug.broadcastMessage("FACE: " + packet.getFace());
328
        //Debug.broadcastMessage(x + " " + y + " " + z);
329
        //Debug.broadcastMessage(mat + "");
330
331
        InteractWorldEvent.InteractionType interactionType;
332
        //first vector is for 1.8 clients, second is for 1.7
333
        if(!targetedPosition.equals(new Vector(-1, -1, -1)) && !targetedPosition.equals(new Vector(-1, 255, -1))) {
334
            if(mat != null && mat != org.bukkit.Material.AIR) {
335
                interactionType = InteractWorldEvent.InteractionType.PLACE_BLOCK;
336
            }
337
            else {
338
                interactionType = InteractWorldEvent.InteractionType.INTERACT_BLOCK;
339
            }
340
        }
341
        else {
342
            ItemStack item = p.getInventory().getItem(pp.getHeldItemSlot());
343
            if(item == null)
344
                return null;
345
            return new InteractItemEvent(p, pp, item, InteractItemEvent.Action.START_USE_ITEM, new WrappedPacket8(packet, WrappedPacket.PacketType.BLOCK_PLACE));
346
        }
347
348
        switch (packet.getFace()) {
349
            case 0:
350
                face = InteractWorldEvent.BlockFace.BOTTOM;
351
                y -= 1;
352
                break;
353
            case 1:
354
                face = InteractWorldEvent.BlockFace.TOP;
355
                y += 1;
356
                break;
357
            case 2:
358
                face = InteractWorldEvent.BlockFace.NORTH;
359
                z -= 1;
360
                break;
361
            case 3:
362
                face = InteractWorldEvent.BlockFace.SOUTH;
363
                z += 1;
364
                break;
365
            case 4:
366
                face = InteractWorldEvent.BlockFace.WEST;
367
                x -= 1;
368
                break;
369
            case 5:
370
                face = InteractWorldEvent.BlockFace.EAST;
371
                x += 1;
372
                break;
373
            default:
374
                face = InteractWorldEvent.BlockFace.INVALID;
375
                break;
376
        }
377
378
        Vector cursorPos = new Vector(packet.d(), packet.e(), packet.f());
379
380
        Location placedLocation = new Location(p.getWorld(), x, y, z);
381
        return new InteractWorldEvent(p, pp, placedLocation, mat, face, cursorPos, interactionType, new WrappedPacket8(packet, WrappedPacket.PacketType.BLOCK_PLACE));
382
    }
383
384
    private static ArmSwingEvent packetToArmSwingEvent(PacketPlayInArmAnimation packet, Player p, HawkPlayer pp) {
385
        return new ArmSwingEvent(p, pp, 0, new WrappedPacket8(packet, WrappedPacket.PacketType.ARM_ANIMATION));
386
    }
387
388
    private static ItemSwitchEvent packetToItemSwitchEvent(PacketPlayInHeldItemSlot packet, Player p, HawkPlayer pp) {
389
        return new ItemSwitchEvent(p, pp, packet.a(), new WrappedPacket8(packet, WrappedPacket.PacketType.HELD_ITEM_SLOT));
390
    }
391
392
    private static PlayerActionEvent packetToPlayerActionEvent(PacketPlayInEntityAction packet, Player p, HawkPlayer pp) {
393
        PacketPlayInEntityAction.EnumPlayerAction nmsAction = packet.b();
394
        PlayerActionEvent.PlayerAction action;
395
        switch (nmsAction) {
396
            case START_SNEAKING:
397
                action = PlayerActionEvent.PlayerAction.SNEAK_START;
398
                break;
399
            case STOP_SNEAKING:
400
                action = PlayerActionEvent.PlayerAction.SNEAK_STOP;
401
                break;
402
            case STOP_SLEEPING:
403
                action = PlayerActionEvent.PlayerAction.BED_LEAVE;
404
                break;
405
            case START_SPRINTING:
406
                action = PlayerActionEvent.PlayerAction.SPRINT_START;
407
                break;
408
            case STOP_SPRINTING:
409
                action = PlayerActionEvent.PlayerAction.SPRINT_STOP;
410
                break;
411
            case RIDING_JUMP:
412
                action = PlayerActionEvent.PlayerAction.HORSE_JUMP;
413
                break;
414
            case OPEN_INVENTORY:
415
                action = PlayerActionEvent.PlayerAction.INVENTORY_OPEN;
416
                break;
417
            default:
418
                action = PlayerActionEvent.PlayerAction.UNKNOWN;
419
        }
420
        return new PlayerActionEvent(p, pp, new WrappedPacket8(packet, WrappedPacket.PacketType.ENTITY_ACTION), action);
421
    }
422
423
    //BEGIN of addition by Havesta
424
    private static ClickInventoryEvent packetToWindowClickEvent(PacketPlayInWindowClick packet, Player p, HawkPlayer pp) {
425
        // packet.b() is the item slot, 0-4 is crafting, 5-8 is armor, 9-44 is the rest of the inventory, when not in inventory clicked = -999
426
427
        // Debug.broadcastMessage("a= " + packet.a() + " b= " + packet.b() + " c= " + packet.c() + " d= " + packet.d() + " e= " + packet.e() + " f= " + packet.f());
428
429
        int windowID = packet.a();
430
        int slot = packet.b();
431
        int button = packet.c();
432
        int mode = packet.f();
433
        //perhaps get clicked ItemStack too?
434
435
        return new ClickInventoryEvent(p, pp, slot, windowID, mode, button, new WrappedPacket8(packet, WrappedPacket.PacketType.ENTITY_ACTION));
436
    }
437
438
    private static OpenPlayerInventoryEvent packetToOpenWindowEvent(PacketPlayInClientCommand packet, Player p, HawkPlayer pp) {
439
        if(packet.a().equals(PacketPlayInClientCommand.EnumClientCommand.OPEN_INVENTORY_ACHIEVEMENT)) { // sadly this works only for player inventory
440
            return new OpenPlayerInventoryEvent(p, pp, new WrappedPacket8(packet, WrappedPacket.PacketType.ENTITY_ACTION));
441
        }
442
        return null;
443
    }
444
445
    private static CloseInventoryEvent packetToCloseWindowEvent(PacketPlayInCloseWindow packet, Player p, HawkPlayer pp) {
446
        return new CloseInventoryEvent(p, pp, new WrappedPacket8(packet, WrappedPacket.PacketType.ENTITY_ACTION));
447
    }
448
    //END of addition by Havesta
449
}

How it counteracts this module

Hawk's only C17-corpus file is the protocol converter: PacketConverter8 translates custom-payload packets between 1.7 and 1.8 layouts, channel remapping and byte payload repacking, with no content or identity validation. Hawk ships no chat-content or name check anywhere in the corpus, so the module is invisible to Hawk by construction; this entry documents the closest Hawk file and why it does not apply.

← Back to Analysis Hub