using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BoneLib.BoneMenu;
using BonelabAntiCheat;
using HarmonyLib;
using MelonLoader;
using MelonLoader.Utils;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(AntiCrasherMod), "Fusion Anti-Crasher", "1.7.6", "Muck Buck", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyVersion("0.0.0.0")]
namespace BonelabAntiCheat;
public class AntiCrasherMod : MelonMod
{
private static string banFilePath;
private static HashSet<ulong> bannedPlatformIds = new HashSet<ulong>();
private static Dictionary<byte, Dictionary<string, List<float>>> identicalTracker = new Dictionary<byte, Dictionary<string, List<float>>>();
private static Dictionary<byte, List<float>> globalTracker = new Dictionary<byte, List<float>>();
private const int IDENTICAL_LIMIT = 60;
private const int GLOBAL_LIMIT = 120;
private const float WINDOW = 2f;
private static Page rootPage;
private static Page bansPage;
public override void OnInitializeMelon()
{
banFilePath = Path.Combine(MelonEnvironment.UserDataDirectory, "fusion_blacklists.txt");
LoadBanList();
SetupBoneMenu();
SpawnHook.Install(((MelonBase)this).HarmonyInstance);
}
private static void LoadBanList()
{
if (!File.Exists(banFilePath))
{
File.Create(banFilePath).Close();
return;
}
bannedPlatformIds.Clear();
string[] array = File.ReadAllLines(banFilePath);
for (int i = 0; i < array.Length; i++)
{
if (ulong.TryParse(array[i].Trim(), out var result) && result < 1000000000000L && result != 0L)
{
bannedPlatformIds.Add(result);
}
}
}
private static void NoOp()
{
}
private static void SetupBoneMenu()
{
//IL_000a: Unknown result type (might be due to invalid IL or missing references)
//IL_0025: Unknown result type (might be due to invalid IL or missing references)
//IL_004f: Unknown result type (might be due to invalid IL or missing references)
rootPage = Page.Root.CreatePage("Muck Buck Anti-Cheat", Color.red, 0, true);
bansPage = rootPage.CreatePage("View Banned IDs", Color.yellow, 0, true);
rootPage.CreateFunction("Reset/Wipe Ban List", new Color(1f, 0.5f, 0f), (Action)delegate
{
if (File.Exists(banFilePath))
{
File.WriteAllText(banFilePath, string.Empty);
}
bannedPlatformIds.Clear();
UpdateBoneMenuData();
});
UpdateBoneMenuData();
}
private static void UpdateBoneMenuData()
{
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
//IL_0058: Unknown result type (might be due to invalid IL or missing references)
//IL_009b: Unknown result type (might be due to invalid IL or missing references)
bansPage.RemoveAll();
bansPage.CreateFunction("Total Bans: " + bannedPlatformIds.Count, Color.white, (Action)NoOp);
if (bannedPlatformIds.Count == 0)
{
bansPage.CreateFunction("No players banned yet.", Color.gray, (Action)NoOp);
return;
}
foreach (ulong bannedPlatformId in bannedPlatformIds)
{
bansPage.CreateFunction("ID: " + bannedPlatformId, Color.white, (Action)NoOp);
}
}
public static bool IsBanned(ulong platformId)
{
if (platformId != 0L)
{
return bannedPlatformIds.Contains(platformId);
}
return false;
}
private static void AddBan(ulong platformId)
{
if (platformId != 0L && !bannedPlatformIds.Contains(platformId))
{
bannedPlatformIds.Add(platformId);
File.AppendAllText(banFilePath, platformId + Environment.NewLine);
UpdateBoneMenuData();
}
}
public static bool VerifyItemTraffic(byte conn, string barcode)
{
float now = Time.time;
if (!identicalTracker.ContainsKey(conn))
{
identicalTracker[conn] = new Dictionary<string, List<float>>();
}
if (!identicalTracker[conn].ContainsKey(barcode))
{
identicalTracker[conn][barcode] = new List<float>();
}
List<float> list = identicalTracker[conn][barcode];
list.RemoveAll((float t) => now - t > 2f);
list.Add(now);
if (list.Count > 60)
{
Sanction(conn, "Identical flood [" + barcode + "] x" + list.Count);
return false;
}
if (!globalTracker.ContainsKey(conn))
{
globalTracker[conn] = new List<float>();
}
List<float> list2 = globalTracker[conn];
list2.RemoveAll((float t) => now - t > 2f);
list2.Add(now);
if (list2.Count > 120)
{
Sanction(conn, "Mixed flood x" + list2.Count);
return false;
}
return true;
}
public static void Sanction(byte conn, string reason)
{
ulong platformId = SpawnHook.GetPlatformId(conn);
MelonLogger.Warning("[AntiCrasher] Sanctioning connection " + conn + " (platform " + platformId + "): " + reason);
AddBan(platformId);
SpawnHook.TryKick(conn, platformId);
identicalTracker.Remove(conn);
globalTracker.Remove(conn);
}
}
public static class SpawnHook
{
private static int reqLogged;
private static Dictionary<byte, List<float>> unknownHits = new Dictionary<byte, List<float>>();
private const bool KICK_ZERO_PLATFORM = true;
public static void Install(Harmony harmony)
{
//IL_0018: Unknown result type (might be due to invalid IL or missing references)
//IL_001e: Expected O, but got Unknown
int num = 0;
HarmonyMethod val = new HarmonyMethod(typeof(SpawnHook).GetMethod("RequestPrefix", BindingFlags.Static | BindingFlags.Public));
Type type = FindType("SpawnRequestMessage");
if (type != null)
{
MethodInfo method = type.GetMethod("OnHandleMessage", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (method != null)
{
try
{
harmony.Patch((MethodBase)method, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
num++;
MelonLogger.Msg("[AntiCrasher] Hooked " + type.FullName + ".OnHandleMessage");
}
catch (Exception ex)
{
MelonLogger.Warning("[AntiCrasher] Hook failed: " + ex.Message);
}
}
}
if (num == 0)
{
MelonLogger.Warning("[AntiCrasher] NO spawn hook installed. Flood detection is OFF.");
}
LogKickCandidates();
RegisterJoinHook();
}
private static void LogKickCandidates()
{
try
{
foreach (Type item in AllFusionTypes())
{
MethodInfo[] methods = item.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
foreach (MethodInfo methodInfo in methods)
{
if (methodInfo.Name.IndexOf("kick", StringComparison.OrdinalIgnoreCase) >= 0)
{
string text = string.Join(", ", from p in methodInfo.GetParameters()
select p.ParameterType.Name + " " + p.Name);
MelonLogger.Msg("[AntiCrasher] KICK CANDIDATE " + item.FullName + "." + methodInfo.Name + "(" + text + ")" + (methodInfo.IsStatic ? " static" : ""));
}
}
}
}
catch (Exception ex)
{
MelonLogger.Warning("[AntiCrasher] Kick scan failed: " + ex.Message);
}
}
private static IEnumerable<Type> AllFusionTypes()
{
List<Type> list = new List<Type>();
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
if (!assembly.GetName().Name.StartsWith("LabFusion"))
{
continue;
}
Type[] collection;
try
{
collection = assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
collection = ex.Types.Where((Type x) => x != null).ToArray();
}
list.AddRange(collection);
}
return list;
}
private static Type FindType(string name)
{
foreach (Type item in AllFusionTypes())
{
if (item.Name == name)
{
return item;
}
}
return null;
}
private static bool IsHost()
{
try
{
Type type = FindType("NetworkInfo");
if (type == null)
{
return true;
}
PropertyInfo property = type.GetProperty("IsHost", BindingFlags.Static | BindingFlags.Public);
if (property != null)
{
return (bool)property.GetValue(null);
}
FieldInfo field = type.GetField("IsHost", BindingFlags.Static | BindingFlags.Public);
if (field != null)
{
return (bool)field.GetValue(null);
}
}
catch
{
}
return true;
}
private static object GetPlayerObj(byte id)
{
try
{
Type type = FindType("PlayerIDManager");
if (type == null)
{
return null;
}
MethodInfo method = type.GetMethod("GetPlayerID", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(byte) }, null);
if (method == null)
{
return null;
}
return method.Invoke(null, new object[1] { id });
}
catch
{
}
return null;
}
public static ulong GetPlatformId(byte id)
{
object playerObj = GetPlayerObj(id);
if (playerObj == null)
{
return 0uL;
}
object member = GetMember(playerObj, "PlatformID");
if (member is ulong)
{
return (ulong)member;
}
return 0uL;
}
public static void TryKick(byte conn, ulong platform)
{
try
{
object playerObj = GetPlayerObj(conn);
foreach (Type item in AllFusionTypes())
{
MethodInfo[] methods = item.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public);
foreach (MethodInfo methodInfo in methods)
{
if (!methodInfo.Name.StartsWith("Kick", StringComparison.OrdinalIgnoreCase))
{
continue;
}
ParameterInfo[] parameters = methodInfo.GetParameters();
if (parameters.Length != 1)
{
continue;
}
object obj = null;
if (parameters[0].ParameterType == typeof(byte))
{
obj = conn;
}
else if (parameters[0].ParameterType == typeof(ulong) && platform != 0L)
{
obj = platform;
}
else if (parameters[0].ParameterType.Name == "PlayerID" && playerObj != null)
{
obj = playerObj;
}
if (obj != null)
{
try
{
methodInfo.Invoke(null, new object[1] { obj });
MelonLogger.Msg("[AntiCrasher] Kick called: " + item.FullName + "." + methodInfo.Name);
return;
}
catch (Exception ex)
{
MelonLogger.Warning("[AntiCrasher] Kick " + methodInfo.Name + " failed: " + ex.Message);
}
}
}
}
MelonLogger.Warning("[AntiCrasher] No usable kick method for connection " + conn + ". See KICK CANDIDATE lines.");
}
catch (Exception ex2)
{
MelonLogger.Warning("[AntiCrasher] TryKick error: " + ex2.Message);
}
}
public static bool RequestPrefix(object[] __args)
{
try
{
if (__args == null || __args.Length == 0 || __args[0] == null)
{
return true;
}
if (!IsHost())
{
return true;
}
object obj = __args[0];
object member = GetMember(obj, "Sender");
if (!(((member == null) ? null : ((member is byte) ? member : GetMember(member, "Value"))) is byte b))
{
if (reqLogged < 5)
{
reqLogged++;
MelonLogger.Warning("[AntiCrasher] Could not read sender from " + obj.GetType().FullName);
}
return true;
}
float now = Time.time;
object playerObj = GetPlayerObj(b);
if (playerObj != null)
{
object member2 = GetMember(playerObj, "IsMe");
bool flag = default(bool);
int num;
if (member2 is bool)
{
flag = (bool)member2;
num = 1;
}
else
{
num = 0;
}
if (((uint)num & (flag ? 1u : 0u)) != 0)
{
return true;
}
}
if (playerObj == null)
{
if (!unknownHits.ContainsKey(b))
{
unknownHits[b] = new List<float>();
}
List<float> list = unknownHits[b];
list.RemoveAll((float t) => now - t > 5f);
list.Add(now);
MelonLogger.Warning("[AntiCrasher] Blocked spawn from unknown sender " + b + " (hit " + list.Count + ")");
if (list.Count >= 3)
{
MelonLogger.Warning("[AntiCrasher] Unknown sender " + b + " persisted, kicking.");
TryKick(b, 0uL);
unknownHits.Remove(b);
}
return false;
}
ulong num2 = 0uL;
if (GetMember(playerObj, "PlatformID") is ulong num3)
{
num2 = num3;
}
if (AntiCrasherMod.IsBanned(num2))
{
MelonLogger.Warning("[AntiCrasher] Banned platform ID " + num2 + " tried to spawn, kicking.");
TryKick(b, num2);
return false;
}
string text = "unknown";
try
{
Type type = FindType("SerializedSpawnData");
if (type != null)
{
MethodInfo methodInfo = obj.GetType().GetMethods().FirstOrDefault((MethodInfo m) => m.Name == "ReadData" && m.IsGenericMethodDefinition && m.GetParameters().Length == 0);
if (methodInfo != null)
{
object member3 = GetMember(methodInfo.MakeGenericMethod(type).Invoke(obj, null), "Barcode");
if (member3 != null)
{
text = member3.ToString();
}
}
}
}
catch
{
}
if (reqLogged < 15)
{
reqLogged++;
MelonLogger.Msg("[AntiCrasher] REQUEST sender=" + b + " platform=" + num2 + " barcode=" + text);
}
return AntiCrasherMod.VerifyItemTraffic(b, text);
}
catch (Exception ex)
{
MelonLogger.Warning("[AntiCrasher] RequestPrefix error: " + ex.Message);
}
return true;
}
private static void RegisterJoinHook()
{
try
{
Type type = FindType("MultiplayerHooking");
if (type == null)
{
MelonLogger.Warning("[AntiCrasher] MultiplayerHooking not found, join filter OFF.");
return;
}
BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
MethodInfo method = typeof(SpawnHook).GetMethod("OnJoin", BindingFlags.Static | BindingFlags.Public);
EventInfo eventInfo = type.GetEvent("OnPlayerJoined", bindingAttr);
if (eventInfo != null)
{
eventInfo.AddEventHandler(null, Delegate.CreateDelegate(eventInfo.EventHandlerType, method));
MelonLogger.Msg("[AntiCrasher] Join hook registered (event).");
return;
}
FieldInfo field = type.GetField("OnPlayerJoined", bindingAttr);
if (field != null)
{
Delegate b = Delegate.CreateDelegate(field.FieldType, method);
Delegate a = (Delegate)field.GetValue(null);
field.SetValue(null, Delegate.Combine(a, b));
MelonLogger.Msg("[AntiCrasher] Join hook registered (field).");
}
else
{
MelonLogger.Warning("[AntiCrasher] OnPlayerJoined not found, join filter OFF.");
}
}
catch (Exception ex)
{
MelonLogger.Warning("[AntiCrasher] Join hook failed: " + ex.Message);
}
}
public static void OnJoin(object pid)
{
try
{
if (pid == null || !IsHost())
{
return;
}
object member = GetMember(pid, "IsMe");
bool flag = default(bool);
int num;
if (member is bool)
{
flag = (bool)member;
num = 1;
}
else
{
num = 0;
}
if (((uint)num & (flag ? 1u : 0u)) == 0)
{
ulong num2 = ((GetMember(pid, "PlatformID") is ulong num3) ? num3 : 0);
byte conn = (byte)((GetMember(pid, "SmallID") is byte b) ? b : 0);
MelonLogger.Msg("[AntiCrasher] JOIN connection=" + conn + " platform=" + num2);
if (AntiCrasherMod.IsBanned(num2))
{
MelonLogger.Warning("[AntiCrasher] Banned player " + num2 + " joined, kicking.");
TryKick(conn, num2);
}
else if (num2 == 0L)
{
MelonLogger.Warning("[AntiCrasher] Joiner with no platform ID, kicking connection " + conn);
TryKick(conn, 0uL);
}
}
}
catch (Exception ex)
{
MelonLogger.Warning("[AntiCrasher] OnJoin error: " + ex.Message);
}
}
private static object GetMember(object o, string name)
{
try
{
if (o == null)
{
return null;
}
Type type = o.GetType();
FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (field != null)
{
return field.GetValue(o);
}
PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (property != null && property.GetIndexParameters().Length == 0)
{
return property.GetValue(o);
}
}
catch
{
}
return null;
}
}