Decompiled source of PerfectGuard v1.0.0

plugins/Marioalexsan.PerfectGuard.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Marioalexsan.PerfectGuard;
using Microsoft.CodeAnalysis;
using Mirror;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Marioalexsan.PerfectGuard")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+8dc95c767d116edb3ecf4e4eec1673c3c76f392e")]
[assembly: AssemblyProduct("PerfectGuard")]
[assembly: AssemblyTitle("Marioalexsan.PerfectGuard")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
[HarmonyPatch]
internal static class PreventTeleportSpamRpc
{
	private static readonly Dictionary<Player, DateTime> TimeSinceLastEffect = new Dictionary<Player, DateTime>();

	private static readonly Dictionary<Player, int> Warns = new Dictionary<Player, int>();

	private static bool IsAbusingEffect(Player player)
	{
		DateTime value;
		return TimeSinceLastEffect.TryGetValue(player, out value) && value + TimeSpan.FromSeconds(1.0) >= DateTime.Now;
	}

	[HarmonyPatch(typeof(PlayerVisual), "Init_TeleportEffect")]
	[HarmonyPrefix]
	private static bool CheckLocalTeleporterEffect(PlayerVisual __instance)
	{
		return !IsAbusingEffect(__instance._player);
	}

	[HarmonyPatch(typeof(PlayerVisual), "Rpc_PlayTeleportEffect")]
	[HarmonyPrefix]
	private static bool CheckRpcTeleporterEffect(PlayerVisual __instance)
	{
		foreach (Player item in TimeSinceLastEffect.Keys.ToList())
		{
			if (!Object.op_Implicit((Object)(object)item))
			{
				TimeSinceLastEffect.Remove(item);
				Warns.Remove(item);
			}
		}
		if (IsAbusingEffect(__instance._player))
		{
			if (Warns[__instance._player] == 0)
			{
				PerfectGuard.Logger.LogWarning((object)("Player " + ((Object)__instance._player).name + " is potentially trying to crash the server using portal spam."));
			}
			Warns[__instance._player]++;
		}
		else
		{
			TimeSinceLastEffect[__instance._player] = DateTime.Now;
			Warns[__instance._player] = 0;
		}
		return Warns[__instance._player] == 0;
	}
}
namespace Marioalexsan.PerfectGuard
{
	[BepInPlugin("Marioalexsan.PerfectGuard", "PerfectGuard", "1.0.0")]
	public class PerfectGuard : BaseUnityPlugin
	{
		internal static ManualLogSource Logger;

		private readonly Harmony _harmony = new Harmony("Marioalexsan.PerfectGuard");

		private readonly ConfigEntry<KeyCode> _windowKey;

		private Rect _windowRect;

		private bool _windowShown;

		public PerfectGuard()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			_windowKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "WindowKey", (KeyCode)290, "Key to trigger PerfectGuard's configuration window with.");
		}

		public void Awake()
		{
			_harmony.PatchAll();
			Debug.Log((object)("$" + Application.version + " loaded."));
		}

		public void Update()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			if (Input.GetKeyDown(_windowKey.Value))
			{
				_windowShown = !_windowShown;
			}
		}

		public void OnGUI()
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			if (_windowShown)
			{
				_windowRect = GUILayout.Window(GUIUtility.GetControlID((FocusType)2), new Rect((float)Screen.width * 0.1f, (float)Screen.height * 0.1f, (float)Screen.width * 0.5f, (float)Screen.height * 0.5f), new WindowFunction(DrawWindow), "PerfectGuard", Array.Empty<GUILayoutOption>());
			}
		}

		private void DrawWindow(int windowID)
		{
		}
	}
	internal static class ModInfo
	{
		public const string GUID = "Marioalexsan.PerfectGuard";

		public const string NAME = "PerfectGuard";

		public const string VERSION = "1.0.0";
	}
}
namespace Marioalexsan.PerfectGuard.Patches
{
	[HarmonyPatch]
	internal static class PatchCommands
	{
		[CompilerGenerated]
		private sealed class <TargetMethods>d__0 : IEnumerable<MethodInfo>, IEnumerable, IEnumerator<MethodInfo>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private MethodInfo <>2__current;

			private int <>l__initialThreadId;

			MethodInfo IEnumerator<MethodInfo>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <TargetMethods>d__0(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = AccessTools.Method(typeof(HostConsole), "Kick_Peer", (Type[])null, (Type[])null);
					<>1__state = 1;
					return true;
				case 1:
					<>1__state = -1;
					<>2__current = AccessTools.Method(typeof(HostConsole), "Ban_Peer", (Type[])null, (Type[])null);
					<>1__state = 2;
					return true;
				case 2:
					<>1__state = -1;
					<>2__current = AccessTools.Method(typeof(HostConsole), "Init_Shutdown", (Type[])null, (Type[])null);
					<>1__state = 3;
					return true;
				case 3:
					<>1__state = -1;
					return false;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<MethodInfo> IEnumerable<MethodInfo>.GetEnumerator()
			{
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					return this;
				}
				return new <TargetMethods>d__0(0);
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<MethodInfo>)this).GetEnumerator();
			}
		}

		[IteratorStateMachine(typeof(<TargetMethods>d__0))]
		private static IEnumerable<MethodInfo> TargetMethods()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <TargetMethods>d__0(-2);
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> code)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			CodeMatcher val = new CodeMatcher(code, (ILGenerator)null);
			while (true)
			{
				val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
				{
					new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction ins) => CodeInstructionExtensions.Calls(ins, AccessTools.Method(typeof(HostConsole), "Init_ServerMessage", (Type[])null, (Type[])null))), (string)null)
				});
				if (val.IsInvalid)
				{
					break;
				}
				val.RemoveInstruction();
				val.Insert((CodeInstruction[])(object)new CodeInstruction[1]
				{
					new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(PreventServerCommandExecution), "ProcessHostConsoleMessage", (Type[])null, (Type[])null))
				});
			}
			return val.InstructionEnumeration();
		}
	}
	[HarmonyPatch]
	internal static class PreventServerCommandExecution
	{
		[HarmonyPatch(typeof(HostConsole), "Init_ServerMessage")]
		[HarmonyPrefix]
		private static bool RemoveCommandExecutionFromMessages(HostConsole __instance, string _message)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			ServerMessage val = default(ServerMessage);
			val.servMsg = _message;
			NetworkServer.SendToAll<ServerMessage>(val, 0, false);
			__instance.New_LogMessage(_message ?? "");
			if (_message != null)
			{
				if (_message.Trim().StartsWith("/"))
				{
					PerfectGuard.Logger.LogWarning((object)"An attempt to execute a command on the host console was done by a client.");
					PerfectGuard.Logger.LogWarning((object)("Offending message: " + _message));
				}
				else if (_message.Contains("/"))
				{
					PerfectGuard.Logger.LogWarning((object)"A suspicious message that might be an attempt to execute commands on the host console was detected.");
					PerfectGuard.Logger.LogWarning((object)("Offending message: " + _message));
				}
			}
			return false;
		}

		[HarmonyPatch(typeof(HostConsole), "Send_ServerMessage")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> ExecuteCommandsFromHostConsole(IEnumerable<CodeInstruction> code)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Expected O, but got Unknown
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			CodeMatcher val = new CodeMatcher(code, (ILGenerator)null);
			val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1]
			{
				new CodeMatch((Func<CodeInstruction, bool>)((CodeInstruction ins) => CodeInstructionExtensions.Calls(ins, AccessTools.Method(typeof(HostConsole), "Init_ServerMessage", (Type[])null, (Type[])null))), (string)null)
			});
			if (!val.IsValid)
			{
				PerfectGuard.Logger.LogWarning((object)"Failed to patch host console command sending!");
				return code;
			}
			val.RemoveInstruction();
			val.Insert((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(PreventServerCommandExecution), "ProcessHostConsoleMessage", (Type[])null, (Type[])null))
			});
			return val.InstructionEnumeration();
		}

		internal static void ProcessHostConsoleMessage(HostConsole instance, string message)
		{
			if (!string.IsNullOrEmpty(message))
			{
				if (message.Trim().StartsWith('/'))
				{
					string text = message.Trim();
					string[] array = text.Substring(1, text.Length - 1).Split(' ', StringSplitOptions.RemoveEmptyEntries);
					string text2 = ((array.Length >= 1) ? array[0] : "");
					string text3 = ((array.Length >= 2) ? array[1] : "");
					instance._cmdManager.Init_ConsoleCommand(text2, text3);
				}
				else
				{
					instance.Init_ServerMessage(message);
				}
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}