From 8b24cd01f204c4f9a3cb28c2856b3078901e3df1 Mon Sep 17 00:00:00 2001 From: Aizistral Date: Thu, 22 Sep 2022 00:10:40 +0200 Subject: Add command encryption support --- .../nochatreports/config/NCRConfigEncryption.java | 74 +++++++++++++++++++++- .../nochatreports/gui/EncryptionConfigScreen.java | 12 +++- .../mixins/client/MixinChatComponent.java | 21 ++++-- .../mixins/client/MixinChatScreen.java | 17 +++-- .../server/MixinServerGamePacketListenerImpl.java | 10 ++- 5 files changed, 119 insertions(+), 15 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java b/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java index 858b5cc..69aa9f0 100644 --- a/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java +++ b/src/main/java/com/aizistral/nochatreports/config/NCRConfigEncryption.java @@ -1,5 +1,6 @@ package com.aizistral.nochatreports.config; +import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.util.ArrayList; import java.util.List; @@ -15,11 +16,13 @@ import net.minecraft.util.StringUtil; public class NCRConfigEncryption extends JSONConfig { protected static final String FILE_NAME = "NoChatReports/NCR-Encryption.json"; - protected boolean skipWarning = false, enableEncryption = false; + protected boolean skipWarning = false, enableEncryption = false, encryptPublic = true; protected String encryptionKey = Encryption.AES_CFB8.getDefaultKey(), encryptionPassphrase = "", algorithmName = Encryption.AES_CFB8.getName(); + protected List encryptableCommands = List.of("msg:1", "w:1", "whisper:1", "tell:1", "r:0", "dm:1", "me:0"); private transient Encryption algorithm; private transient boolean isValid = false; + private transient String lastMessage = "???"; protected NCRConfigEncryption() { super(FILE_NAME); @@ -43,6 +46,7 @@ public class NCRConfigEncryption extends JSONConfig { public void toggleEncryption() { this.enableEncryption = !this.enableEncryption; + this.saveFile(); } public void setAlgorithm(Encryption encryption) { @@ -63,6 +67,11 @@ public class NCRConfigEncryption extends JSONConfig { this.saveFile(); } + public void setEncryptPublic(boolean encryptPublic) { + this.encryptPublic = encryptPublic; + this.saveFile(); + } + public void disableWarning() { this.skipWarning = true; } @@ -87,6 +96,10 @@ public class NCRConfigEncryption extends JSONConfig { return this.isValid; } + public boolean shouldEncryptPublic() { + return this.encryptPublic; + } + public boolean isEnabledAndValid() { return this.isEnabled() && this.isValid(); } @@ -95,6 +108,65 @@ public class NCRConfigEncryption extends JSONConfig { return this.algorithm; } + public boolean shouldEncrypt(String message) { + return this.isEnabledAndValid() && this.getEncryptionStartIndex(message) != -1; + } + + public int getEncryptionStartIndex(String message) { + if (!message.startsWith("/")) + return this.encryptPublic ? 0 : -1; + else { + for (String rule : this.encryptableCommands) { + String[] splat = rule.split(":"); + + if (splat.length != 2) + throw new IllegalArgumentException("Invalid encryptable command definition: " + rule + + ", in file: " + FILE_NAME); + + String cmd = splat[0]; + String args = splat[1]; + int argnum = 0; + + try { + argnum = Integer.valueOf(args); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException("Invalid encryptable command definition: " + rule + + ", in file: " + FILE_NAME); + } + + String prefix = "/" + cmd + " "; + if (message.startsWith(prefix)) { + char[] array = message.substring(prefix.length(), message.length()).toCharArray(); + + for (int i = 0; i < array.length; i++) { + char ch = array[i]; + if (argnum > 0) { + if (ch == ' ') { + argnum--; + } + continue; + } else { + int index = i + prefix.length(); + return index < message.length() ? index : -1; + } + } + } else { + continue; + } + } + + return -1; + } + } + + public void setLastMessage(String lastMessage) { + this.lastMessage = lastMessage; + } + + public String getLastMessage() { + return this.lastMessage; + } + /** * @return Chat encryptor, if encryption is enabled and user specified valid key in config. */ diff --git a/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java b/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java index 3aa41b9..4875340 100644 --- a/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java +++ b/src/main/java/com/aizistral/nochatreports/gui/EncryptionConfigScreen.java @@ -16,6 +16,7 @@ import net.fabricmc.api.Environment; import net.minecraft.ChatFormatting; import net.minecraft.client.gui.Font; import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.Checkbox; import net.minecraft.client.gui.components.CycleButton; import net.minecraft.client.gui.components.EditBox; import net.minecraft.client.gui.components.ImageButton; @@ -44,6 +45,7 @@ public class EncryptionConfigScreen extends Screen { private static final Component VALIDATION_FAILED = Component.translatable("gui.nochatreports.encryption_config.validation_failed"); private static final Component DICE_TOOLTIP = Component.translatable("gui.nochatreports.encryption_config.dice_tooltip"); private static final Component PASS_NOT_ALLOWED = Component.translatable("gui.nochatreports.encryption_config.pass_not_allowed"); + private static final Component ENCRYPT_PUBLIC = Component.translatable("gui.nochatreports.encryption_config.encrypt_public"); private static final int FIELDS_Y_START = 45; private final Screen previous; @@ -51,6 +53,7 @@ public class EncryptionConfigScreen extends Screen { private ImageButton validationIcon; private CycleButton algorithmButton; private MultiLineLabel keyDesc = MultiLineLabel.EMPTY, passDesc = MultiLineLabel.EMPTY; + protected Checkbox encryptPublicCheck; private boolean settingPassKey = false; public EncryptionConfigScreen(Screen previous) { @@ -131,8 +134,12 @@ public class EncryptionConfigScreen extends Screen { this.addRenderableOnly(button); + int checkWidth = this.font.width(ENCRYPT_PUBLIC); + this.encryptPublicCheck = new Checkbox(this.width / 2 - checkWidth / 2 - 8, this.passField.y + 24, checkWidth + 24, 20, + ENCRYPT_PUBLIC, NCRConfig.getEncryption().shouldEncryptPublic()); + this.addRenderableWidget(this.encryptPublicCheck); - this.addRenderableWidget(new Button(this.width / 2 + 4, this.passField.y + 42, 219, 20, + this.addRenderableWidget(new Button(this.width / 2 + 4, this.passField.y + 48, 219, 20, CommonComponents.GUI_DONE, btn -> { this.onDone(); this.onClose(); @@ -143,7 +150,7 @@ public class EncryptionConfigScreen extends Screen { }).withValues(Encryption.getRegistered()).displayOnlyValue().withInitialValue(this.getConfig() .getAlgorithm()).withTooltip(value -> this.minecraft.font.split( Component.translatable("algorithm.nochatreports." + value.getID()), 250)) - .create(this.width / 2 - 4 - 218, this.passField.y + 42, 218, 20, CommonComponents.EMPTY, + .create(this.width / 2 - 4 - 218, this.passField.y + 48, 218, 20, CommonComponents.EMPTY, (cycleButton, value) -> { this.unfocusFields(); this.onAlgorithmUpdate(value); @@ -265,6 +272,7 @@ public class EncryptionConfigScreen extends Screen { config.setAlgorithm(encryption); config.setEncryptionKey(!StringUtil.isNullOrEmpty(this.keyField.getValue()) ? this.keyField.getValue() : encryption.getDefaultKey()); + config.setEncryptPublic(this.encryptPublicCheck.selected()); } @Override diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java index bbac7c9..9df4fd0 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatComponent.java @@ -31,8 +31,8 @@ public class MixinChatComponent { @ModifyVariable(method = "addRecentChat", at = @At("HEAD"), argsOnly = true) private String onAddRecentChat(String message) { - if (!message.startsWith("/")) - return NCRConfig.getEncryption().getEncryptor().map(e -> e.decrypt(message)).orElse(message); + if (NCRConfig.getEncryption().isEnabledAndValid()) + return NCRConfig.getEncryption().getLastMessage(); else return message; } @@ -42,7 +42,7 @@ public class MixinChatComponent { at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/components/ComponentRenderUtils;" + "wrapComponents(Lnet/minecraft/network/chat/FormattedText;ILnet/minecraft/client/gui/Font;" + ")Ljava/util/List;", ordinal = 0, shift = Shift.AFTER), argsOnly = true) - private GuiMessageTag modifyGUITag(GuiMessageTag tag) { + private synchronized GuiMessageTag modifyGUITag(GuiMessageTag tag) { if (this.lastMessageEncrypted) { this.lastMessageEncrypted = false; Component tooltip = Component.empty().append(Component.translatable("tag.nochatreports.encrypted", @@ -50,6 +50,8 @@ public class MixinChatComponent { .withStyle(ChatFormatting.BOLD))).append(CommonComponents.NEW_LINE).append( Component.translatable("tag.nochatreports.encrypted_original", this.lastMessageOriginal)); + + //System.out.println("Last message original: " + last); return new GuiMessageTag(0x8B3EC7, ENCRYPTED_ICON, tooltip, "Encrypted"); } else return tag; @@ -62,12 +64,13 @@ public class MixinChatComponent { + "Lnet/minecraft/client/gui/Font;)Ljava/util/List;", ordinal = 0)) private FormattedText modifyGUIMessage(FormattedText msg) { var optional = NCRConfig.getEncryption().getEncryptor(); - if (optional.isEmpty()) return msg; + Encryptor encryption = optional.get(); - this.lastMessageOriginal = Component.Serializer.fromJson(Component.Serializer.toStableJson(((Component) msg))); - ComponentContents contents = ((Component)msg).getContents(); + Component copy = this.recreate((Component) msg); + this.lastMessageOriginal = this.recreate(copy); + ComponentContents contents = copy.getContents(); if (contents instanceof TranslatableContents translatable) { for (Object arg : translatable.args) { @@ -86,7 +89,11 @@ public class MixinChatComponent { } } - return msg; + return copy; + } + + private Component recreate(Component component) { + return Component.Serializer.fromJson(Component.Serializer.toStableJson(component)); } } diff --git a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java index 64e594d..1062de0 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/client/MixinChatScreen.java @@ -54,10 +54,18 @@ public abstract class MixinChatScreen extends Screen { @Inject(method = "normalizeChatMessage", at = @At("RETURN"), cancellable = true) public void onBeforeMessage(String original, CallbackInfoReturnable info) { String message = info.getReturnValue(); + NCRConfig.getEncryption().setLastMessage(message); - if (!message.isEmpty() && !message.startsWith("/")) { - NCRConfig.getEncryption().getEncryptor().ifPresent(e -> - info.setReturnValue(e.encrypt("#%" + message))); + if (!message.isEmpty() && NCRConfig.getEncryption().shouldEncrypt(message)) { + NCRConfig.getEncryption().getEncryptor().ifPresent(e -> { + int index = NCRConfig.getEncryption().getEncryptionStartIndex(message); + String noencrypt = message.substring(0, index); + String encrypt = message.substring(index, message.length()); + + if (encrypt.length() > 0) { + info.setReturnValue(noencrypt + e.encrypt("#%" + encrypt)); + } + }); } } @@ -124,7 +132,8 @@ public abstract class MixinChatScreen extends Screen { } private void openEncryptionConfig() { - if (!EncryptionWarningScreen.seenOnThisSession() && !NCRConfig.getEncryption().isWarningDisabled()) { + if (!EncryptionWarningScreen.seenOnThisSession() && !NCRConfig.getEncryption().isWarningDisabled() + && !NCRConfig.getEncryption().isEnabledAndValid()) { Minecraft.getInstance().setScreen(new EncryptionWarningScreen(this)); } else { Minecraft.getInstance().setScreen(new EncryptionConfigScreen(this)); diff --git a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java index 7d9df00..c6fcbe0 100644 --- a/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java +++ b/src/main/java/com/aizistral/nochatreports/mixins/server/MixinServerGamePacketListenerImpl.java @@ -7,6 +7,7 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import com.aizistral.nochatreports.NoChatReports; import com.aizistral.nochatreports.config.NCRConfig; import net.minecraft.network.PacketSendListener; @@ -32,6 +33,10 @@ public abstract class MixinServerGamePacketListenerImpl implements ServerPlayerC @Inject(method = "send(Lnet/minecraft/network/protocol/Packet;)V", at = @At("HEAD"), cancellable = true) private void onSend(Packet packet, CallbackInfo info) { + if (NCRConfig.getCommon().enableDebugLog() && packet instanceof ClientboundPlayerChatPacket chat) { + NoChatReports.LOGGER.info("Sending message: {}", chat.message().serverContent()); + } + if (NCRConfig.getCommon().convertToGameMessage()) { if (packet instanceof ClientboundPlayerChatHeaderPacket) { info.cancel(); @@ -39,7 +44,6 @@ public abstract class MixinServerGamePacketListenerImpl implements ServerPlayerC packet = new ClientboundSystemChatPacket(chat.chatType().resolve(this.player.level.registryAccess()) .get().decorate(chat.message().serverContent()), false); - info.cancel(); this.send(packet); } @@ -54,6 +58,10 @@ public abstract class MixinServerGamePacketListenerImpl implements ServerPlayerC @Inject(method = "send(Lnet/minecraft/network/protocol/Packet;Lnet/minecraft/network/PacketSendListener;)V", at = @At("HEAD"), cancellable = true) private void onSend(Packet packet, @Nullable PacketSendListener packetSendListener, CallbackInfo info) { + if (NCRConfig.getCommon().enableDebugLog() && packet instanceof ClientboundPlayerChatPacket chat) { + NoChatReports.LOGGER.info("Sending message: {}", chat.message().serverContent()); + } + if (NCRConfig.getCommon().convertToGameMessage()) { if (packet instanceof ClientboundPlayerChatHeaderPacket) { info.cancel(); -- cgit v1.2.3