Exemplo n.º 1
0
        public async Task <bool> DoBan(BanningEventArgs ev)
        {
            string banned_user_id    = ev.Target.UserId;
            string banned_nickname   = ev.Target.Nickname;
            string banned_ip_address = ev.Target.IPAddress;
            int    banduration       = ev.Duration;
            Player adminHub          = ev.Issuer;

            Log.Info("--------------------------------------");
            Log.Info("Ban detected, plugin taking over:");
            Log.Info($"Banned Name: {banned_nickname}");
            Log.Info($"Banned ID: {banned_user_id}");
            Log.Info($"Banned IP: {banned_ip_address}");
            Log.Info($"Admin Name: {adminHub.Nickname}");
            Log.Info($"Admin ID: {adminHub.UserId}");
            Log.Info($"Duration: {banduration}");
            if (banduration.ToString().Contains("1576800000"))
            {
                banduration = 0;
                Log.Info($"Duration: UPDATED TO PERM!");
            }
            string reason = ev.Reason;

            if (reason == "")
            {
                reason = "No reason provided. Please contact a Head Administrator for further details.";
            }
            if (await WebTask.IssueBan(plugin.Config.APIKey, banned_user_id, banned_nickname, banned_ip_address, adminHub.UserId, banduration, reason, ev.Target.ReferenceHub.serverRoles.DoNotTrack))
            {
                Log.Info($"Successfully pushed ban for {banned_user_id} ({banned_ip_address}) to the web API!");
                Log.Info("--------------------------------------");
                SendClientToServer(ev.Target, 7790);
                // We can safely remove the ban since the web client will handle it from here.
                //BanHandler.RemoveBan(ev.Target.UserId, ev.);
                return(true);
            }
            else
            {
                // Error out to requesting admin
                adminHub.Broadcast(15, $"ERROR while adding ban to web API for: {banned_nickname}({banned_user_id})");
                Log.Error($"FATAL BANNING ERROR! WebTask.IssueBan() Failed to push to web API");


                // Actually ban them since the webapi decided to do the funny...
                BanDetails ban = new BanDetails
                {
                    OriginalName = ev.Target.Nickname,
                    Id           = ev.Target.UserId,
                    IssuanceTime = TimeBehaviour.CurrentTimestamp(),
                    Expires      = DateTime.UtcNow.AddMinutes((double)ev.Duration).Ticks,
                    Reason       = ev.Reason,
                    Issuer       = ev.Issuer.UserId
                };
                BanHandler.IssueBan(ban, BanHandler.BanType.UserId);
                Log.Info("Pushed manual server-side ban.");
                Log.Info("--------------------------------------");
                return(false);
            }
            return(false);
        }
Exemplo n.º 2
0
        private string UnbanCommand(string[] arg, JObject jObject)
        {
            if (arg.Count() < 3)
            {
                return($"```{arg[1]} [UserID/Ip]```");
            }

            bool validUID = arg[2].Contains('@');
            bool validIP  = IPAddress.TryParse(arg[2], out IPAddress ip);

            BanDetails details;

            if (!validIP && !validUID)
            {
                return($"```diff\n- Invalid UserID or IP given```");
            }

            if (validUID)
            {
                details = BanHandler.QueryBan(arg[2], null).Key;
            }
            else
            {
                details = BanHandler.QueryBan(null, arg[2]).Value;
            }

            if (details == null)
            {
                return($"No ban found for `{arg[2]}`.\nMake sure you have typed it correctly, and that it has the @domain prefix if it's a UserID");
            }

            BanHandler.RemoveBan(arg[2], (validUID ? BanHandler.BanType.UserId : BanHandler.BanType.IP));

            return($"`{arg[2]}` has been unbanned.");
        }
Exemplo n.º 3
0
        public void Start()
        {
            orig_Start();

            CustomNetworkManager.Modded = true;
            AddLog("[PHEGGMOD] THIS SERVER IS RUNNING PHEGGMOD");

            //Commented out until SmartGuard is fixed
            //new SmartGuard();

            _debug       = ConfigFile.ServerConfig.GetBool("pheggmod_debug", false);
            _restartTime = ConfigFile.ServerConfig.GetString("auto_restart_time", "04:30");

            if (_debug)
            {
                Base.Debug("Debug mode enabled!");
                Base.Debug("Printing file paths:"
                           + $"\nUserIdBans.txt: {BanHandler.GetPath(BanHandler.BanType.UserId)}"
                           + $"\nIpBans.txt: {BanHandler.GetPath(BanHandler.BanType.IP)}"
                           + $"\nUserIdWhitelist.txt: {ConfigSharing.Paths[2] + "UserIDWhitelist.txt"}"
                           + $"\nUserIdReservedSlots.txt: {ConfigSharing.Paths[3] + "UserIDReservedSlots.txt"}");
            }

            ///This is the time that the server will check for with the auto-restarting system.
            ///Uses 24 hour formatting (16:00 is 4PM), and uses the time relative to the server.
            ///Set to 25:00 to disable;


            new Commands.CustomInternalCommands();
            PluginManager.PluginPreLoad();
        }
Exemplo n.º 4
0
        public async Task <BanPage> GetBanPageAsync(int page = 1)
        {
            if (!_webManager.IsAuthenticated)
            {
                throw new Exception("User must be authenticated before using this method.");
            }

            var result = await _webManager.GetDataAsync(string.Format(EndPoints.RapSheet, page));

            var document = await _webManager.Parser.ParseAsync(result.ResultHtml);

            return(BanHandler.ParseBanPage(document));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Get the Banned Members page.
        /// </summary>
        /// <param name="page">The page number to start parsing from. Defaults to 1.</param>
        /// <param name="token">A CancellationToken.</param>
        /// <returns>A BanPage.</returns>
        public async Task <BanPage> GetBanPageAsync(int page = 1, CancellationToken token = default)
        {
            if (!this.webManager.IsAuthenticated)
            {
                throw new UserAuthenticationException(Awful.Core.Resources.ExceptionMessages.UserAuthenticationError);
            }

            var result = await this.webManager.GetDataAsync(string.Format(CultureInfo.InvariantCulture, EndPoints.RapSheet, page), token).ConfigureAwait(false);

            var document = await this.webManager.Parser.ParseDocumentAsync(result.ResultHtml, token).ConfigureAwait(false);

            return(BanHandler.ParseBanPage(document));
        }
Exemplo n.º 6
0
        public bool Execute(ArraySegment <string> arguments, ICommandSender sender, out string response)
        {
            if (arguments.Count >= 2)
            {
                response = EasyUnban.Singleton.Config.PardonNumCmdRunningMsg;

                if (!int.TryParse(arguments.At(1), out int id))
                {
                    response = "\n" + EasyUnban.Singleton.Config.PardonNumCmdNumArgInvalid;
                    return(false);
                }

                if (arguments.At(0).ToLower() == "id")
                {
                    if (EasyUnban.IdBans.Exists(e => e.Id == id))
                    {
                        BanHandler.RemoveBan(EasyUnban.IdBans.Find(e => e.Id == id).Ban, BanHandler.BanType.UserId);
                    }
                    else
                    {
                        response += "\n" +
                                    EasyUnban.Singleton.Config.PardonNumCmdCantFindIpOrIdUserBannedWithNumber.Replace(
                            "{BanType}", "UserId");
                    }
                }
                else if (arguments.At(0).ToLower() == "ip")
                {
                    if (EasyUnban.IpBans.Exists(e => e.Id == id))
                    {
                        BanHandler.RemoveBan(EasyUnban.IpBans.Find(e => e.Id == id).Ban, BanHandler.BanType.IP);
                    }
                    else
                    {
                        response += "\n" +
                                    EasyUnban.Singleton.Config.PardonNumCmdCantFindIpOrIdUserBannedWithNumber.Replace(
                            "{BanType}", "Ip");
                    }
                }
                else
                {
                    response += "\n" + EasyUnban.Singleton.Config.PardonNumFirstArgBeIdOrIp;
                    return(false);
                }

                return(true);
            }

            response = "\n" + EasyUnban.Singleton.Config.PardonNumArgumentsMissing;
            return(false);
        }
Exemplo n.º 7
0
        public void cmd_oban(CommandInfo info)
        {
            CommandSender sender = info.commandSender;

            string[] arg = info.commandArgs;

            if (arg.Count() < 4)
            {
                sender.RaReply(arg[0].ToUpper() + "#Command expects 3 or more arguments ([UserID], [Minutes], [Reason])", false, true, "");
                return;
            }
            else if (!arg[1].Contains('@'))
            {
                sender.RaReply(arg[0].ToUpper() + "#Invalid UserID given", false, true, "");
                return;
            }

            char unit = arg[2].ToString().Where(Char.IsLetter).ToArray()[0];

            if (!int.TryParse(new string(arg[2].Where(Char.IsDigit).ToArray()), out int amount) || !CustomInternalCommands.validUnits.Contains(unit) || amount < 1)
            {
                sender.RaReply(arg[0].ToUpper() + "#Invalid duration", false, true, "");
                return;
            }

            TimeSpan duration = CustomInternalCommands.GetBanDuration(unit, amount);
            string   reason   = string.Join(" ", arg.Skip(3));

            if (duration.Minutes > 60 && !CustomInternalCommands.CheckPermissions(sender, arg[0], PlayerPermissions.KickingAndShortTermBanning))
            {
                return;
            }
            else if (duration.Minutes > 1440 && !CustomInternalCommands.CheckPermissions(sender, arg[0], PlayerPermissions.BanningUpToDay))
            {
                return;
            }

            BanHandler.IssueBan(new BanDetails
            {
                OriginalName = "Offline player",
                Id           = arg[1],
                Issuer       = sender.Nickname,
                IssuanceTime = DateTime.UtcNow.Ticks,
                Expires      = DateTime.UtcNow.Add(duration).Ticks,
                Reason       = reason.Replace(Environment.NewLine, "")
            }, BanHandler.BanType.UserId);

            sender.RaReply(arg[0].ToUpper() + $"#{arg[1]} was offline banned for {arg[2]}", true, true, "");
        }
Exemplo n.º 8
0
        /// <summary>
        /// Pings the main forums page and checks if the user under probation.
        /// </summary>
        /// <param name="token">A CancellationToken.</param>
        /// <returns>A ProbationItem.</returns>
        public async Task <ProbationItem> CheckForProbation(CancellationToken token = default)
        {
            if (!this.webManager.IsAuthenticated)
            {
                throw new UserAuthenticationException(Awful.Core.Resources.ExceptionMessages.UserAuthenticationError);
            }

            var result = await this.webManager.GetDataAsync(EndPoints.BaseUrl, token).ConfigureAwait(false);

            var document = await this.webManager.Parser.ParseDocumentAsync(result.ResultHtml, token).ConfigureAwait(false);

            var prob = BanHandler.ParseForProbation(document);

            this.webManager.Probation = prob;
            return(prob);
        }
Exemplo n.º 9
0
        public async Task <ProbationItem> CheckForProbation()
        {
            if (!_webManager.IsAuthenticated)
            {
                throw new Exception("User must be authenticated before using this method.");
            }

            var result = await _webManager.GetDataAsync(EndPoints.BaseUrl);

            var document = await _webManager.Parser.ParseAsync(result.ResultHtml);

            var prob = BanHandler.ParseForProbation(document);

            _webManager.Probation = prob;
            return(prob);
        }
Exemplo n.º 10
0
        public bool IsBanned()
        {
            var bans = BanHandler.GetBans(BanHandler.BanType.UserId);

            foreach (var playerban in bans)
            {
                if (playerban.Id != Id + "@" + Authentication)
                {
                    return(false);
                }
                if (BanHandler.CheckExpiration(playerban, BanHandler.BanType.UserId))
                {
                    return(true);
                }
                return(false);
            }
            return(false);
        }
Exemplo n.º 11
0
        public void Ban(int duration, string reason = "No reason provided", string issuer = "SERVER", bool banIP = true)
        {
            BanHandler.IssueBan(new BanDetails
            {
                OriginalName = name,
                Id           = userId,
                Issuer       = issuer,
                IssuanceTime = DateTime.UtcNow.Ticks,
                Expires      = DateTimeOffset.UtcNow.AddMinutes(duration).Ticks,
                Reason       = reason
            }, BanHandler.BanType.UserId);

            BanHandler.IssueBan(new BanDetails
            {
                OriginalName = name,
                Id           = ipAddress,
                Issuer       = issuer,
                IssuanceTime = DateTime.UtcNow.Ticks,
                Expires      = DateTimeOffset.UtcNow.AddMinutes(duration).Ticks,
                Reason       = reason
            }, BanHandler.BanType.IP);
        }
Exemplo n.º 12
0
        private void HandlePunishments(GameObject go, string reason)
        {
            if (_banDurationOne < 0)
            {
                return;
            }

            Base.Disconnect(go, $"You have been automatically disconnected from the server by SmartGuard.\nReason: {reason}");

            Base.SmartGuard($"{go.GetComponent<NicknameSync>().MyNick} was {(_banDurationOne > 0 ? "banned" : "kicked")}: {reason}");

            if (_banDurationOne > 0)
            {
                Base.Disconnect(go, $"You have been automatically disconnected from the server by SmartGuard.\nReason: {reason}\nNote: This action was performed automatically by a server modification!");

                BanHandler.IssueBan(new BanDetails
                {
                    OriginalName = go.GetComponent <NicknameSync>().MyNick,
                    Id           = go.GetComponent <CharacterClassManager>().UserId,
                    Expires      = DateTime.UtcNow.AddMinutes(_banDurationOne).Ticks,
                    Reason       = $"SMARTGUARD - {reason}",
                    Issuer       = "SMARTGUARD",
                    IssuanceTime = DateTime.UtcNow.Ticks
                }, BanHandler.BanType.UserId);

                BanHandler.IssueBan(new BanDetails
                {
                    OriginalName = go.GetComponent <NicknameSync>().MyNick,
                    Id           = go.GetComponent <NetworkIdentity>().connectionToClient.address,
                    Expires      = DateTime.UtcNow.AddMinutes(_banDurationOne).Ticks,
                    Reason       = $"SMARTGUARD - {reason}",
                    Issuer       = "SMARTGUARD",
                    IssuanceTime = DateTime.UtcNow.Ticks
                }, BanHandler.BanType.IP);

                Base.SmartGuard($"{go.GetComponent<NicknameSync>().MyNick} was banned for: {reason}");
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Called by the Server API when this plugin is initialized.
        /// This should never be called by a plugin.
        /// </summary>
        public override void Initialize()
        {
            try
            {
                HandleCommandLine(Environment.GetCommandLineArgs());

                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
                if (!Directory.Exists(LogPath))
                {
                    Directory.CreateDirectory(LogPath);
                }
                if (!Directory.Exists(PluginPath))
                {
                    Directory.CreateDirectory(PluginPath);
                }

                ConfigFile.ConfigRead += OnConfigRead;
                if (File.Exists(ConfigPath))
                {
                    Config = ConfigFile.Read(ConfigPath);
                }
                Config.Write(ConfigPath);

                if (Config.StorageType.ToLower() == "sqlite")
                {
                    string sql = Path.Combine(SavePath, "orion.sqlite");
                    Database = new SqliteConnection(String.Format("uri=file://{0},Version=3", sql));
                }
                else if (Config.StorageType.ToLower() == "mysql")
                {
                    try
                    {
                        string[] hostport = Config.MySqlHost.Split(':');
                        Database = new MySqlConnection
                        {
                            ConnectionString = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
                                                             hostport[0],
                                                             hostport.Length > 1 ? hostport[1] : "3306",
                                                             Config.MySqlDbName,
                                                             Config.MySqlUsername,
                                                             Config.MySqlPassword
                                                             )
                        };
                    }
                    catch (MySqlException ex)
                    {
                        ServerApi.LogWriter.PluginWriteLine(this, ex.ToString(), TraceLevel.Error);
                        throw new Exception(Strings.MySqlException);
                    }
                }
                else
                {
                    throw new Exception(Strings.InvalidDbTypeException);
                }

                if (Config.UseSqlLogging)
                {
                    Log = new SqlLog(this, Path.Combine(LogPath, "log.log"), false);
                }
                else
                {
                    //Log = new TextLog(this, Path.Combine(LogPath, "log.log"), false);
                    Log = new Log(Path.Combine(SavePath, "log4net.config"));
                }

                Users       = new UserHandler(this);
                Bans        = new BanHandler(this);
                Utils       = new Utils();
                HashHandler = new Hasher(this);

                LoadPlugins();
            }
            catch (Exception ex)
            {
                Log.Error(Strings.StartupException);
                Log.Error(ex.ToString());
                Environment.Exit(1);
            }
        }
Exemplo n.º 14
0
        public static void HandleCommand(JObject o)
        {
            try
            {
                string type = (string)o["type"];
                if (type == "IDENT")
                {
                    if ((string)o["data"] == "PASS")
                    {
                        Log.Debug($"Server {ServerConsole.Port} passed identification.");
                    }
                    else if ((string)o["data"] == "FAIL")
                    {
                        Log.Warn($"Server {ServerConsole.Port} failed identification.");
                    }
                }
                else if (type == "UPDATE")
                {
                    EventHandlers.tcp.SendData(new Update());
                }
                else if (type == "ROLESYNC")
                {
                    Log.Warn(o);

                    string userid = (string)o["userid"];

                    if (o["group"] == null)
                    {
                        Log.Debug($"No role sync found for {userid}");
                        SCPDiscord.VerifyReservedSlot(userid);
                        return;
                    }

                    string group = (string)o["group"];

                    UserGroup userGroup = ServerStatic.PermissionsHandler.GetGroup(group);
                    if (userGroup == null)
                    {
                        Log.Error($"Attempted to assign invalid user group {group} to {userid}");
                        return;
                    }

                    Player player = Player.Get(userid);
                    if (player == null)
                    {
                        Log.Error($"Error assigning user group to {userid}, player not found.");
                        return;
                    }

                    if (SCPDiscord.setRoleGroups.Contains(group))
                    {
                        Log.Debug($"Assigning role: {userGroup} to {userid}.");
                        player.Group = userGroup;
                    }

                    string tag = (string)o["tag"];
                    if (SCPDiscord.setTagGroups.Contains(group) && tag != null)
                    {
                        Log.Debug($"Changing tag of {userid} to {tag}.");
                        player.RankName = tag;
                    }

                    if (SCPDiscord.reservedSlotGroups.Contains(group))
                    {
                        // grant reserved slot
                        Log.Debug("Player has necessary rank for reserved slot, checking...");
                        List <string> lines = File.ReadAllLines(SCPDiscord.reservedSlots).ToList();
                        if (!lines.Contains(userid))
                        {
                            Log.Debug("Reserved slot not found, adding player...");
                            lines.Add(userid);
                            File.WriteAllLines(SCPDiscord.reservedSlots, lines);
                            // This only reloads the slots on the current server, change this to reload on every server?
                            // Might not work
                            ReservedSlot.Reload();
                        }
                    }
                    else
                    {
                        SCPDiscord.VerifyReservedSlot(userid);
                    }
                }
                else if (type == "COMMAND")
                {
                    GameCore.Console.singleton.TypeCommand((string)o["command"]);
                }
                else if (type == "BAN")
                {
                    bool   isuid = false;
                    string uid   = (string)o["user"];
                    if (!uid.Contains("@steam") && !uid.Contains("@discord"))
                    {
                        if (!uid.Contains("."))
                        {
                            isuid = true;
                            uid  += "@steam";
                        }
                    }
                    else
                    {
                        isuid = true;
                    }
                    Player player = Player.Get(uid);
                    int    min    = (int)o["min"];
                    string reason = (string)o["reason"];

                    Ban ban = new Ban
                    {
                        player   = null,
                        duration = min,
                        success  = true,
                        offline  = false
                    };

                    if (player != null)
                    {
                        PlayerManager.localPlayer.GetComponent <BanPlayer>().BanUser(player.GameObject, min, reason, "Server");

                        ban.player = new User
                        {
                            name   = player.Nickname,
                            userid = player.UserId
                        };
                    }
                    else
                    {
                        if (isuid)
                        {
                            ban.offline = true;

                            ban.player = new User
                            {
                                name   = "Offline Player",
                                userid = uid
                            };

                            if (SCPDiscord.instance.Config.SteamApiKey != string.Empty)
                            {
                                string data = null;
                                try
                                {
                                    data = webclient.DownloadString($"https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/?key={SCPDiscord.instance.Config.SteamApiKey}&format=json&steamids={uid.Replace("@steam", "")}");
                                }
                                catch
                                {
                                    Log.Debug("Failed to get profile data from SteamAPI.");
                                }
                                JObject o2 = JObject.Parse(data);

                                if (o2 != null)
                                {
                                    ban.player.name = (string)o2["response"]["players"][0]["personaname"];
                                }
                            }

                            BanHandler.IssueBan(new BanDetails()
                            {
                                OriginalName = ban.player.name,
                                Id           = uid,
                                IssuanceTime = TimeBehaviour.CurrentTimestamp(),
                                Expires      = DateTime.UtcNow.AddMinutes((double)min).Ticks,
                                Reason       = reason,
                                Issuer       = "Server"
                            }, BanHandler.BanType.UserId);
                        }
                        else if (uid.Contains("."))
                        {
                            ban.offline = true;

                            BanHandler.IssueBan(new BanDetails()
                            {
                                OriginalName = "IP Address",
                                Id           = uid,
                                IssuanceTime = TimeBehaviour.CurrentTimestamp(),
                                Expires      = DateTime.UtcNow.AddMinutes((double)min).Ticks,
                                Reason       = reason,
                                Issuer       = "Server"
                            }, BanHandler.BanType.IP);
                        }
                        else
                        {
                            ban.success = false;
                        }
                    }
                    EventHandlers.tcp.SendData(ban);
                }
                else if (type == "KICK")
                {
                    string uid = (string)o["user"];
                    if (!uid.Contains("@steam") && !uid.Contains("@discord"))
                    {
                        uid += "@steam";
                    }
                    Player player = Player.Get(uid);

                    Kick kick = new Kick
                    {
                        player = null
                    };

                    if (player != null)
                    {
                        kick.player = new User
                        {
                            name   = player.Nickname,
                            userid = player.UserId
                        };

                        ServerConsole.Disconnect(player.GameObject, (string)o["reason"]);
                    }
                    EventHandlers.tcp.SendData(kick);
                }
                else if (type == "UNBAN")
                {
                    Unban unban = new Unban();

                    List <string> ipBans     = File.ReadAllLines(SCPDiscord.ipBans).ToList();
                    List <string> userIDBans = File.ReadAllLines(SCPDiscord.useridBans).ToList();

                    string id = (string)o["user"];
                    if (!id.Contains("."))
                    {
                        if (!id.Contains("@steam") && !id.Contains("@discord"))
                        {
                            id += "@steam";
                        }
                    }
                    List <string> matchingIPBans      = ipBans.FindAll(s => s.Contains(id));
                    List <string> matchingSteamIDBans = userIDBans.FindAll(s => s.Contains(id));

                    if (matchingIPBans.Count == 0 && matchingSteamIDBans.Count == 0)
                    {
                        unban.success = false;
                        EventHandlers.tcp.SendData(unban);
                        return;
                    }

                    ipBans.RemoveAll(s => s.Contains(id));
                    userIDBans.RemoveAll(s => s.Contains(id));

                    foreach (var row in matchingIPBans)
                    {
                        userIDBans.RemoveAll(s => s.Contains(row.Split(';').Last()));
                    }
                    foreach (var row in matchingSteamIDBans)
                    {
                        ipBans.RemoveAll(s => s.Contains(row.Split(';').Last()));
                    }

                    File.WriteAllLines(SCPDiscord.ipBans, ipBans);
                    File.WriteAllLines(SCPDiscord.useridBans, userIDBans);

                    EventHandlers.tcp.SendData(unban);
                }
            }
            catch (Exception x)
            {
                Log.Error("SCPDiscord handle command error: " + x.Message);
            }
        }
Exemplo n.º 15
0
 public BanModule(BanHandler banHandler)
 {
     this.banHandler = banHandler;
 }
Exemplo n.º 16
0
        /// <summary>
        /// Handle the player connection.
        /// </summary>
        /// <param name="request">The <see cref="ConnectionRequest"/> instance.</param>
        private static void HandleConnection(ConnectionRequest request)
        {
            try
            {
                int position = request.Data.Position;
                if (!request.Data.TryGetByte(out byte result1) || !request.Data.TryGetByte(out byte result2) || !request.Data.TryGetByte(out byte result3) || result1 != CustomNetworkManager.Major || result2 != CustomNetworkManager.Minor || result3 != CustomNetworkManager.SyncedRevision)
                {
                    CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                    CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)3);
                    request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                }
                else
                {
                    bool flag = request.Data.TryGetInt(out int result4);
                    if (!request.Data.TryGetBytesWithLength(out byte[] result5))
                    {
                        flag = false;
                    }
                    if (!flag)
                    {
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)15);
                        request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                    }
                    else if (CustomLiteNetLib4MirrorTransport.DelayConnections)
                    {
                        CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)17);
                        CustomLiteNetLib4MirrorTransport.RequestWriter.Put(CustomLiteNetLib4MirrorTransport.DelayTime);
                        if (CustomLiteNetLib4MirrorTransport.DelayVolume < byte.MaxValue)
                        {
                            ++CustomLiteNetLib4MirrorTransport.DelayVolume;
                        }
                        if (CustomLiteNetLib4MirrorTransport.DelayVolume < CustomLiteNetLib4MirrorTransport.DelayVolumeThreshold)
                        {
                            ServerConsole.AddLog(
                                $"Delayed connection incoming from endpoint {request.RemoteEndPoint} by {CustomLiteNetLib4MirrorTransport.DelayTime} seconds.");
                            request.Reject(CustomLiteNetLib4MirrorTransport.RequestWriter);
                        }
                        else
                        {
                            ServerConsole.AddLog(
                                $"Force delayed connection incoming from endpoint {request.RemoteEndPoint} by {CustomLiteNetLib4MirrorTransport.DelayTime} seconds.");
                            request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                        }
                    }
                    else
                    {
                        if (CustomLiteNetLib4MirrorTransport.UseChallenge)
                        {
                            if (result4 == 0 || result5 == null || result5.Length == 0)
                            {
                                if (!CustomLiteNetLib4MirrorTransport.CheckIpRateLimit(request))
                                {
                                    return;
                                }
                                int    num = 0;
                                string key = string.Empty;
                                for (byte index = 0; index < 3; ++index)
                                {
                                    num = RandomGenerator.GetInt32();
                                    if (num == 0)
                                    {
                                        num = 1;
                                    }
                                    key = request.RemoteEndPoint.Address + "-" + num;
                                    if (CustomLiteNetLib4MirrorTransport.Challenges.ContainsKey(key))
                                    {
                                        if (index == 2)
                                        {
                                            CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                            CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)4);
                                            request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                            ServerConsole.AddLog(
                                                $"Failed to generate ID for challenge for incoming connection from endpoint {request.RemoteEndPoint}.");
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                byte[] bytes = RandomGenerator.GetBytes(CustomLiteNetLib4MirrorTransport.ChallengeInitLen + CustomLiteNetLib4MirrorTransport.ChallengeSecretLen, true);
                                ServerConsole.AddLog(
                                    $"Requested challenge for incoming connection from endpoint {request.RemoteEndPoint}.");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)13);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)CustomLiteNetLib4MirrorTransport.ChallengeMode);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put(num);
                                switch (CustomLiteNetLib4MirrorTransport.ChallengeMode)
                                {
                                case ChallengeType.MD5:
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(bytes, 0, CustomLiteNetLib4MirrorTransport.ChallengeInitLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.Put(CustomLiteNetLib4MirrorTransport.ChallengeSecretLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(Md.Md5(bytes));
                                    CustomLiteNetLib4MirrorTransport.Challenges.Add(key, new PreauthChallengeItem(new ArraySegment <byte>(bytes, CustomLiteNetLib4MirrorTransport.ChallengeInitLen, CustomLiteNetLib4MirrorTransport.ChallengeSecretLen)));
                                    break;

                                case ChallengeType.SHA1:
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(bytes, 0, CustomLiteNetLib4MirrorTransport.ChallengeInitLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.Put(CustomLiteNetLib4MirrorTransport.ChallengeSecretLen);
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(Sha.Sha1(bytes));
                                    CustomLiteNetLib4MirrorTransport.Challenges.Add(key, new PreauthChallengeItem(new ArraySegment <byte>(bytes, CustomLiteNetLib4MirrorTransport.ChallengeInitLen, CustomLiteNetLib4MirrorTransport.ChallengeSecretLen)));
                                    break;

                                default:
                                    CustomLiteNetLib4MirrorTransport.RequestWriter.PutBytesWithLength(bytes);
                                    CustomLiteNetLib4MirrorTransport.Challenges.Add(key, new PreauthChallengeItem(new ArraySegment <byte>(bytes)));
                                    break;
                                }

                                request.Reject(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                                return;
                            }

                            string key1 = request.RemoteEndPoint.Address + "-" + result4;
                            if (!CustomLiteNetLib4MirrorTransport.Challenges.ContainsKey(key1))
                            {
                                ServerConsole.AddLog(
                                    $"Security challenge response of incoming connection from endpoint {request.RemoteEndPoint} has been REJECTED (invalid Challenge ID).");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)14);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                return;
                            }

                            ArraySegment <byte> validResponse = CustomLiteNetLib4MirrorTransport.Challenges[key1].ValidResponse;
                            if (!result5.SequenceEqual(validResponse))
                            {
                                ServerConsole.AddLog(
                                    $"Security challenge response of incoming connection from endpoint {request.RemoteEndPoint} has been REJECTED (invalid response).");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)15);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                                return;
                            }

                            CustomLiteNetLib4MirrorTransport.Challenges.Remove(key1);
                            CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                            ServerConsole.AddLog(
                                $"Security challenge response of incoming connection from endpoint {request.RemoteEndPoint} has been accepted.");
                        }
                        else if (!CustomLiteNetLib4MirrorTransport.CheckIpRateLimit(request))
                        {
                            return;
                        }

                        if (!CharacterClassManager.OnlineMode)
                        {
                            KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(null, request.RemoteEndPoint.Address.ToString());
                            if (keyValuePair.Value != null)
                            {
                                ServerConsole.AddLog($"Player tried to connect from banned endpoint {request.RemoteEndPoint}.");
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)6);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put(keyValuePair.Value.Expires);
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put(keyValuePair.Value?.Reason ?? string.Empty);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                            }
                            else
                            {
                                request.Accept();
                                CustomLiteNetLib4MirrorTransport.PreauthDisableIdleMode();
                            }
                        }
                        else
                        {
                            if (!request.Data.TryGetString(out string result6) || result6 == string.Empty)
                            {
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Reset();
                                CustomLiteNetLib4MirrorTransport.RequestWriter.Put((byte)5);
                                request.RejectForce(CustomLiteNetLib4MirrorTransport.RequestWriter);
                            }
Exemplo n.º 17
0
        private static void HandleConnection(ConnectionRequest request)
        {
            NetDataWriter rejectData = new NetDataWriter();

            try
            {
                byte result1;
                byte result2;
                int  position = request.Data.Position;
                if (!request.Data.TryGetByte(out result1) || !request.Data.TryGetByte(out result2) || result1 != CustomNetworkManager.Major || result2 != CustomNetworkManager.Minor)
                {
                    rejectData.Reset();
                    rejectData.Put(3);
                    request.Reject(rejectData);
                }
                else
                {
                    if (CustomLiteNetLib4MirrorTransport.IpRateLimiting)
                    {
                        if (CustomLiteNetLib4MirrorTransport.IpRateLimit.Contains(request.RemoteEndPoint.Address.ToString()))
                        {
                            ServerConsole.AddLog(string.Format("Incoming connection from endpoint {0} rejected due to exceeding the rate limit.", request.RemoteEndPoint));
                            ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Incoming connection from endpoint {0} rejected due to exceeding the rate limit.", request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                            rejectData.Reset();
                            rejectData.Put(12);
                            request.Reject(rejectData);
                            return;
                        }
                        CustomLiteNetLib4MirrorTransport.IpRateLimit.Add(request.RemoteEndPoint.Address.ToString());
                    }
                    if (!CharacterClassManager.OnlineMode)
                    {
                        KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(null, request.RemoteEndPoint.Address.ToString());
                        if (keyValuePair.Value != null)
                        {
                            ServerConsole.AddLog(string.Format("Player tried to connect from banned endpoint {0}.", request.RemoteEndPoint));
                            rejectData.Reset();
                            rejectData.Put(6);
                            rejectData.Put(keyValuePair.Value.Expires);
                            rejectData.Put(keyValuePair.Value?.Reason ?? string.Empty);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            request.Accept();
                        }
                    }
                    else
                    {
                        string result3;
                        if (!request.Data.TryGetString(out result3) || result3 == string.Empty)
                        {
                            rejectData.Reset();
                            rejectData.Put(5);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            ulong  result4;
                            byte   result5;
                            string result6;
                            byte[] result7;
                            if (!request.Data.TryGetULong(out result4) || !request.Data.TryGetByte(out result5) || !request.Data.TryGetString(out result6) || !request.Data.TryGetBytesWithLength(out result7))
                            {
                                rejectData.Reset();
                                rejectData.Put(4);
                                request.Reject(rejectData);
                            }
                            else
                            {
                                CentralAuthPreauthFlags flags = (CentralAuthPreauthFlags)result5;
                                try
                                {
                                    if (!ECDSA.VerifyBytes(string.Format("{0};{1};{2};{3}", result3, result5, result6, result4), result7, ServerConsole.PublicKey))
                                    {
                                        ServerConsole.AddLog(string.Format("Player from endpoint {0} sent preauthentication token with invalid digital signature.", request.RemoteEndPoint));
                                        rejectData.Reset();
                                        rejectData.Put(2);
                                        request.Reject(rejectData);
                                    }
                                    else if (TimeBehaviour.CurrentUnixTimestamp > result4)
                                    {
                                        ServerConsole.AddLog(string.Format("Player from endpoint {0} sent expired preauthentication token.", request.RemoteEndPoint));
                                        ServerConsole.AddLog("Make sure that time and timezone set on server is correct. We recommend synchronizing the time.");
                                        rejectData.Reset();
                                        rejectData.Put(11);
                                        request.Reject(rejectData);
                                    }
                                    else
                                    {
                                        if (CustomLiteNetLib4MirrorTransport.UserRateLimiting)
                                        {
                                            if (CustomLiteNetLib4MirrorTransport.UserRateLimit.Contains(result3))
                                            {
                                                ServerConsole.AddLog(string.Format("Incoming connection from {0} ({1}) rejected due to exceeding the rate limit.", result3, request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Incoming connection from endpoint {0} ({1}) rejected due to exceeding the rate limit.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                                                rejectData.Reset();
                                                rejectData.Put(12);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                            CustomLiteNetLib4MirrorTransport.UserRateLimit.Add(result3);
                                        }
                                        if (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreBans) || !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(result3, request.RemoteEndPoint.Address.ToString());
                                            if (keyValuePair.Key != null || keyValuePair.Value != null)
                                            {
                                                ServerConsole.AddLog(string.Format("{0} {1} tried to connect from {2} endpoint {3}.", keyValuePair.Key == null ? "Player" : "Banned player", result3, keyValuePair.Value == null ? "" : "banned ", request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} {1} tried to connect from {2} endpoint {3}.", keyValuePair.Key == null ? "Player" : "Banned player", result3, keyValuePair.Value == null ? "" : "banned ", request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                rejectData.Reset();
                                                rejectData.Put(6);
                                                NetDataWriter netDataWriter1 = rejectData;
                                                BanDetails    key            = keyValuePair.Key;
                                                netDataWriter1.Put(key != null ? key.Expires : keyValuePair.Value.Expires);
                                                NetDataWriter netDataWriter2 = rejectData;
                                                string        str;
                                                if ((str = keyValuePair.Key?.Reason) == null)
                                                {
                                                    str = keyValuePair.Value?.Reason ?? string.Empty;
                                                }
                                                netDataWriter2.Put(str);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                        }
                                        if (flags.HasFlagFast(CentralAuthPreauthFlags.GloballyBanned) && !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            bool useGlobalBans = CustomLiteNetLib4MirrorTransport.UseGlobalBans;
                                        }
                                        if ((!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreWhitelist) || !ServerStatic.GetPermissionsHandler().IsVerified) && !WhiteList.IsWhitelisted(result3))
                                        {
                                            ServerConsole.AddLog(string.Format("Player {0} tried joined from endpoint {1}, but is not whitelisted.", result3, request.RemoteEndPoint));
                                            rejectData.Reset();
                                            rejectData.Put(7);
                                            request.Reject(rejectData);
                                        }
                                        else if (CustomLiteNetLib4MirrorTransport.Geoblocking != GeoblockingMode.None && (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreGeoblock) || !ServerStatic.GetPermissionsHandler().BanTeamBypassGeo) && (!CustomLiteNetLib4MirrorTransport.GeoblockIgnoreWhitelisted || !WhiteList.IsOnWhitelist(result3)) && (CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Whitelist && !CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper()) || CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Blacklist && CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper())))
                                        {
                                            ServerConsole.AddLog(string.Format("Player {0} ({1}) tried joined from blocked country {2}.", result3, request.RemoteEndPoint, result6.ToUpper()));
                                            rejectData.Reset();
                                            rejectData.Put(9);
                                            request.Reject(rejectData);
                                        }
                                        else
                                        {
                                            int num = CustomNetworkManager.slots;
                                            if (flags.HasFlagFast(CentralAuthPreauthFlags.ReservedSlot) && ServerStatic.GetPermissionsHandler().BanTeamSlots)
                                            {
                                                num = LiteNetLib4MirrorNetworkManager.singleton.maxConnections;
                                            }
                                            else if (ConfigFile.ServerConfig.GetBool("use_reserved_slots", true) && ReservedSlot.HasReservedSlot(result3))
                                            {
                                                num += CustomNetworkManager.reservedSlots;
                                            }
                                            if (LiteNetLib4MirrorCore.Host.PeersCount < num)
                                            {
                                                if (CustomLiteNetLib4MirrorTransport.UserIds.ContainsKey(request.RemoteEndPoint))
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds[request.RemoteEndPoint].SetUserId(result3);
                                                }
                                                else
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds.Add(request.RemoteEndPoint, new PreauthItem(result3));
                                                }
                                                bool allow = true;
                                                Events.InvokePreAuth(result3, request, position, result5, result6, ref allow);
                                                if (allow)
                                                {
                                                    request.Accept();
                                                    ServerConsole.AddLog(string.Format("Player {0} preauthenticated from endpoint {1}.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} preauthenticated from endpoint {1}.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                                else
                                                {
                                                    ServerConsole.AddLog(string.Format("Player {0} tried to preauthenticate from endpoint {1}, but the request has been rejected by a plugin.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} tried to preauthenticate from endpoint {1}, but the request has been rejected by a plugin.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                            }
                                            else
                                            {
                                                rejectData.Reset();
                                                rejectData.Put(1);
                                                request.Reject(rejectData);
                                            }
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    ServerConsole.AddLog(string.Format("Player from endpoint {0} sent an invalid preauthentication token. {1}", request.RemoteEndPoint, exception.Message));
                                    rejectData.Reset();
                                    rejectData.Put(2);
                                    request.Reject(rejectData);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ServerConsole.AddLog(string.Format("Player from endpoint {0} failed to preauthenticate: {1}", request.RemoteEndPoint, exception.Message));
                rejectData.Reset();
                rejectData.Put(4);
                request.Reject(rejectData);
            }
        }
Exemplo n.º 18
0
        private static bool Prefix(GameObject user, int duration, string reason, string issuer, bool isGlobalBan)
        {
            try
            {
                if (isGlobalBan && ConfigFile.ServerConfig.GetBool("gban_ban_ip", false))
                {
                    duration = int.MaxValue;
                }

                string userId  = null;
                string address = user.GetComponent <NetworkIdentity>().connectionToClient.address;

                API.Features.Player targetPlayer = API.Features.Player.Get(user);
                API.Features.Player issuerPlayer = API.Features.Player.Get(issuer) ?? API.Features.Server.Host;

                try
                {
                    if (ConfigFile.ServerConfig.GetBool("online_mode", false))
                    {
                        userId = targetPlayer.UserId;
                    }
                }
                catch
                {
                    ServerConsole.AddLog("Failed during issue of User ID ban (1)!");
                    return(false);
                }

                string message = $"You have been {((duration > 0) ? "banned" : "kicked")}. ";
                if (!string.IsNullOrEmpty(reason))
                {
                    message = message + "Reason: " + reason;
                }

                if (!ServerStatic.PermissionsHandler.IsVerified || !targetPlayer.IsStaffBypassEnabled)
                {
                    if (duration > 0)
                    {
                        var ev = new BanningEventArgs(targetPlayer, issuerPlayer, duration, reason, message);

                        Player.OnBanning(ev);

                        duration = ev.Duration;
                        reason   = ev.Reason;
                        message  = ev.FullMessage;

                        if (!ev.IsAllowed)
                        {
                            return(false);
                        }

                        string originalName = string.IsNullOrEmpty(targetPlayer.Nickname)
                            ? "(no nick)"
                            : targetPlayer.Nickname;
                        long issuanceTime   = TimeBehaviour.CurrentTimestamp();
                        long banExpieryTime = TimeBehaviour.GetBanExpirationTime((uint)duration);
                        try
                        {
                            if (userId != null && !isGlobalBan)
                            {
                                BanHandler.IssueBan(
                                    new BanDetails
                                {
                                    OriginalName = originalName,
                                    Id           = userId,
                                    IssuanceTime = issuanceTime,
                                    Expires      = banExpieryTime,
                                    Reason       = reason,
                                    Issuer       = issuer,
                                }, BanHandler.BanType.UserId);

                                if (!string.IsNullOrEmpty(targetPlayer.CustomUserId))
                                {
                                    BanHandler.IssueBan(
                                        new BanDetails
                                    {
                                        OriginalName = originalName,
                                        Id           = targetPlayer.CustomUserId,
                                        IssuanceTime = issuanceTime,
                                        Expires      = banExpieryTime,
                                        Reason       = reason,
                                        Issuer       = issuer,
                                    }, BanHandler.BanType.UserId);
                                }
                            }
                        }
                        catch
                        {
                            ServerConsole.AddLog("Failed during issue of User ID ban (2)!");
                            return(false);
                        }

                        try
                        {
                            if (ConfigFile.ServerConfig.GetBool("ip_banning", false) || isGlobalBan)
                            {
                                BanHandler.IssueBan(
                                    new BanDetails
                                {
                                    OriginalName = originalName,
                                    Id           = address,
                                    IssuanceTime = issuanceTime,
                                    Expires      = banExpieryTime,
                                    Reason       = reason,
                                    Issuer       = issuer,
                                }, BanHandler.BanType.IP);
                            }
                        }
                        catch
                        {
                            ServerConsole.AddLog("Failed during issue of IP ban!");
                            return(false);
                        }
                    }
                    else if (duration == 0)
                    {
                        var ev = new KickingEventArgs(targetPlayer, issuerPlayer, reason, message);

                        Player.OnKicking(ev);

                        reason  = ev.Reason;
                        message = ev.FullMessage;

                        if (!ev.IsAllowed)
                        {
                            return(false);
                        }
                    }
                }

                ServerConsole.Disconnect(targetPlayer.ReferenceHub.gameObject, message);

                return(false);
            }
            catch (Exception e)
            {
                Exiled.API.Features.Log.Error($"Exiled.Events.Patches.Events.Player.BanningAndKicking: {e}\n{e.StackTrace}");

                return(true);
            }
        }
Exemplo n.º 19
0
        public static bool Prefix(GameObject user, int duration, string reason, string issuer, bool isGlobalBan)
        {
            if (isGlobalBan && ConfigFile.ServerConfig.GetBool("gban_ban_ip", false))
            {
                duration = int.MaxValue;
            }
            string userId  = null;
            string address = user.GetComponent <NetworkIdentity>().connectionToClient.address;
            CharacterClassManager characterClassManager = null;
            ReferenceHub          userHub = Extensions.Player.GetPlayer(user);

            try
            {
                if (ConfigFile.ServerConfig.GetBool("online_mode", false))
                {
                    characterClassManager = userHub.characterClassManager;
                    userId = characterClassManager.UserId;
                }
            }
            catch
            {
                ServerConsole.AddLog("Failed during issue of User ID ban (1)!");
                return(false);
            }
            string message = $"You have been {((duration > 0) ? "banned" : "kicked")}. ";

            if (!string.IsNullOrEmpty(reason))
            {
                message = message + "Reason: " + reason;
            }
            try
            {
                bool allow = true;
                Events.InvokePlayerBan(ref userHub, ref userId, ref duration, ref allow, ref message, ref reason);

                if (!allow)
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Error in OnBanPlayer event: {ex.ToString()}");
            }

            if (duration > 0 && (!ServerStatic.PermissionsHandler.IsVerified || !userHub.serverRoles.BypassStaff))
            {
                string originalName   = string.IsNullOrEmpty(userHub.nicknameSync.MyNick) ? "(no nick)" : userHub.nicknameSync.MyNick;
                long   issuanceTime   = TimeBehaviour.CurrentTimestamp();
                long   banExpieryTime = TimeBehaviour.GetBanExpieryTime((uint)duration);
                try
                {
                    if (userId != null && !isGlobalBan)
                    {
                        BanHandler.IssueBan(new BanDetails
                        {
                            OriginalName = originalName,
                            Id           = userId,
                            IssuanceTime = issuanceTime,
                            Expires      = banExpieryTime,
                            Reason       = reason,
                            Issuer       = issuer
                        }, BanHandler.BanType.UserId);
                        if (!string.IsNullOrEmpty(characterClassManager.UserId2))
                        {
                            BanHandler.IssueBan(new BanDetails
                            {
                                OriginalName = originalName,
                                Id           = characterClassManager.UserId2,
                                IssuanceTime = issuanceTime,
                                Expires      = banExpieryTime,
                                Reason       = reason,
                                Issuer       = issuer
                            }, BanHandler.BanType.UserId);
                        }
                    }
                }
                catch
                {
                    ServerConsole.AddLog("Failed during issue of User ID ban (2)!");
                    return(false);
                }
                try
                {
                    if (ConfigFile.ServerConfig.GetBool("ip_banning", false) || isGlobalBan)
                    {
                        BanHandler.IssueBan(new BanDetails
                        {
                            OriginalName = originalName,
                            Id           = address,
                            IssuanceTime = issuanceTime,
                            Expires      = banExpieryTime,
                            Reason       = reason,
                            Issuer       = issuer
                        }, BanHandler.BanType.IP);
                    }
                }
                catch
                {
                    ServerConsole.AddLog("Failed during issue of IP ban!");
                    return(false);
                }
            }
            List <GameObject> playersToBan = new List <GameObject>();

            foreach (GameObject gameObject in PlayerManager.players)
            {
                characterClassManager = gameObject.GetComponent <CharacterClassManager>();
                if ((userId != null && characterClassManager.UserId == userId) || (address != null && characterClassManager.connectionToClient.address == address))
                {
                    playersToBan.Add(characterClassManager.gameObject);
                }
            }
            foreach (GameObject player in playersToBan)
            {
                ServerConsole.Disconnect(player, message);
            }
            return(false);
        }
Exemplo n.º 20
0
        public override void OnEnabled()
        {
            Singleton = this;
            bool ipBans = true;
            bool idBans = true;

            string[] idBansTxt;
            string[] ipBansTxt;

            if (Config.ManualDirectory == false)
            {
                ipBansTxt = File.ReadAllLines(BanHandler.GetPath(BanHandler.BanType.IP));
                idBansTxt = File.ReadAllLines(BanHandler.GetPath(BanHandler.BanType.UserId));
            }
            else
            {
                try
                {
                    ipBansTxt = File.ReadAllLines(Config.ManualIpBanDirectory);
                    idBansTxt = File.ReadAllLines(Config.ManualIdBanDirectory);
                }
                catch
                {
                    Log.Error("MANUAL IP OR ID DIRECTORIES DOES NOT EXIST! DOES THE FILE EXISTS AT LEAST??");
                    Log.Error("MANUAL IP OR ID DIRECTORIES DOES NOT EXIST! DOES THE FILE EXISTS AT LEAST??");
                    Log.Error("MANUAL IP OR ID DIRECTORIES DOES NOT EXIST! DOES THE FILE EXISTS AT LEAST??");
                    return;
                }
            }


            List <BannedUserInfo> bannedUserIds = new List <BannedUserInfo>();
            List <BannedUserInfo> bannedUserIps = new List <BannedUserInfo>();

            for (int i = 0; i < ipBansTxt.Length; i++)
            {
                string[] e = ipBansTxt[i].Split(';');
                bannedUserIps.Add(new BannedUserInfo(e[0], e[1]));
            }

            for (int i = 0; i < idBansTxt.Length; i++)
            {
                string[] e = idBansTxt[i].Split(';');
                bannedUserIds.Add(new BannedUserInfo(e[0], e[1]));
            }

            if (bannedUserIds.Count == 0)
            {
                idBans = false;
            }
            else
            {
                for (int i = 0; i < bannedUserIds.Count; i++)
                {
                    IdBans.Add(new UserBans(bannedUserIds[i].Name, bannedUserIds[i].Ban, i));
                }
            }

            if (bannedUserIps.Count == 0)
            {
                ipBans = false;
            }
            else
            {
                for (int i = 0; i < bannedUserIps.Count; i++)
                {
                    IpBans.Add(new UserBans(bannedUserIps[i].Name, bannedUserIps[i].Ban, i));
                }
            }

            if (idBans == false && ipBans == false)
            {
                IdBans = null;
                IpBans = null;
            }

            base.OnEnabled();
        }
Exemplo n.º 21
0
        private string BanCommand(string[] arg, JObject jObject)
        {
            try
            {
                if (arg.Count() < 5)
                {
                    return($"```{arg[1]} [UserID/Ip] [Duration] [Reason]```");
                }

                bool validUID = arg[2].Contains('@');
                bool validIP  = IPAddress.TryParse(arg[2], out IPAddress ip);

                if (!validIP && !validUID)
                {
                    return($"```diff\n- Invalid UserID or IP given```");
                }

                var chars = arg[3].Where(Char.IsLetter).ToArray();

                //return string.Join(" ", chars);

                if (chars.Length < 1 || !int.TryParse(new string(arg[3].Where(Char.IsDigit).ToArray()), out int amount) || !validUnits.Contains(chars[0]) || amount < 1)
                {
                    return("```diff\n- Invalid duration```");
                }

                TimeSpan duration = GetBanDuration(chars[0], amount);
                string   reason   = string.Join(" ", arg.Skip(4));

                ReferenceHub player = null;
                if (validIP)
                {
                    var list = ReferenceHub.GetAllHubs().Where(p => p.Value.characterClassManager.connectionToClient.address == arg[2]);
                    if (list.Count() > 0)
                    {
                        player = list.First().Value;
                    }
                }
                else
                {
                    var list = ReferenceHub.GetAllHubs().Where(p => p.Value.characterClassManager.UserId == arg[2]);
                    if (list.Count() > 0)
                    {
                        player = list.First().Value;
                    }
                }

                if (player != null)
                {
                    BanHandler.IssueBan(new BanDetails
                    {
                        OriginalName = player.nicknameSync.MyNick,
                        Id           = player.characterClassManager.UserId,
                        Issuer       = jObject["Staff"].ToString(),
                        IssuanceTime = DateTime.UtcNow.Ticks,
                        Expires      = DateTime.UtcNow.Add(duration).Ticks,
                        Reason       = reason
                    }, BanHandler.BanType.UserId);

                    BanHandler.IssueBan(new BanDetails
                    {
                        OriginalName = player.nicknameSync.MyNick,
                        Id           = player.characterClassManager.connectionToClient.address,
                        Issuer       = jObject["Staff"].ToString(),
                        IssuanceTime = DateTime.UtcNow.Ticks,
                        Expires      = DateTime.UtcNow.Add(duration).Ticks,
                        Reason       = reason
                    }, BanHandler.BanType.IP);

                    ServerConsole.Disconnect(player.gameObject, reason);

                    return($"`{player.nicknameSync.MyNick} ({player.characterClassManager.UserId})` was banned for {arg[3]} with reason: {reason}");
                }
                else
                {
                    BanHandler.IssueBan(new BanDetails
                    {
                        OriginalName = "Offline player",
                        Id           = arg[2],
                        Issuer       = jObject["Staff"].ToString(),
                        IssuanceTime = DateTime.UtcNow.Ticks,
                        Expires      = DateTime.UtcNow.Add(duration).Ticks,
                        Reason       = reason
                    }, (validUID ? BanHandler.BanType.UserId : BanHandler.BanType.IP));
                    return($"`{arg[2]}` was banned for {arg[3]} with reason {reason}!");
                }
            }
            catch (Exception e)
            {
                return(e.ToString());
            }
        }
Exemplo n.º 22
0
        public bool Execute(ArraySegment <string> arguments, ICommandSender sender, out string response)
        {
            string target;

            if (!sender.CheckPermission("scputils.unwarn"))
            {
                target = Exiled.API.Features.Player.Get(((CommandSender)sender).SenderId).ToString().Split(new string[] { " " }, StringSplitOptions.None)[2];
            }
            else
            {
                if (arguments.Count < 2)
                {
                    response = $"<color=yellow>Usage: {Command} <player name/id> <WarnID></color>";
                    return(false);
                }
                else
                {
                    target = arguments.Array[1].ToString();
                }
            }
            Player databasePlayer = target.GetDatabasePlayer();

            if (databasePlayer == null)
            {
                response = $"<color=yellow>Player not found on Database or Player is loading data!</color>";
                return(false);
            }
            bool success = int.TryParse(arguments.Array[2], out int id);

            if (!success)
            {
                response = $"Parameter is not an integer!";
                return(false);
            }

            if ((databasePlayer.SuicideScp.Count - 1) < id || id < 0)
            {
                response = $"Warning with index {id} not found!";
                return(true);
            }
            string message = "Success!";

            switch (databasePlayer.SuicidePunishment[id])
            {
            case "Warn":
                databasePlayer.ScpSuicideCount--;
                databasePlayer.SuicidePunishment[id] = "REMOVED";
                databasePlayer.LogStaffer[id]        = sender.LogName;
                databasePlayer.UserNotified[id]      = true;
                Database.LiteDatabase.GetCollection <Player>().Update(databasePlayer);
                break;

            case "Kick":
                databasePlayer.ScpSuicideCount--;
                databasePlayer.TotalScpSuicideKicks--;
                databasePlayer.SuicidePunishment[id] = "REMOVED";
                databasePlayer.LogStaffer[id]        = sender.LogName;
                databasePlayer.UserNotified[id]      = true;
                Database.LiteDatabase.GetCollection <Player>().Update(databasePlayer);
                break;

            case "Ban":
                databasePlayer.ScpSuicideCount--;
                databasePlayer.TotalScpSuicideBans--;
                databasePlayer.SuicidePunishment[id] = "REMOVED";
                databasePlayer.LogStaffer[id]        = sender.LogName;
                databasePlayer.UserNotified[id]      = true;
                Database.LiteDatabase.GetCollection <Player>().Update(databasePlayer);
                if (DateTime.Now < DateTime.Now.AddMinutes(databasePlayer.TotalScpSuicideBans) && !ScpUtils.StaticInstance.Config.MultiplyBanDurationEachBan)
                {
                    BanHandler.RemoveBan($"{databasePlayer.Id}@{databasePlayer.Authentication}", BanHandler.BanType.UserId);
                    BanHandler.RemoveBan(databasePlayer.Ip, BanHandler.BanType.IP);
                }
                else if (DateTime.Now < DateTime.Now.AddMinutes(databasePlayer.TotalScpSuicideBans * ScpUtils.StaticInstance.Config.AutoBanDuration) && ScpUtils.StaticInstance.Config.MultiplyBanDurationEachBan)
                {
                    BanHandler.RemoveBan($"{databasePlayer.Id}@{databasePlayer.Authentication}", BanHandler.BanType.UserId);
                    BanHandler.RemoveBan(databasePlayer.Ip, BanHandler.BanType.IP);
                }
                break;

            case "REMOVED":
                message = "This sanction has already been removed!";
                break;

            default:
                break;
            }


            response = $"{message}";

            return(true);
        }
Exemplo n.º 23
0
        private string BanCommand(string[] arg, JObject jObject)
        {
            if (arg.Count() < 5)
            {
                return($"```{arg[1]} [UserID/Ip] [Duration] [Reason]```");
            }

            bool validUID = arg[2].Contains('@');
            bool validIP  = IPAddress.TryParse(arg[2], out IPAddress ip);

            //BanDetails details;

            if (!validIP && !validUID)
            {
                return($"```diff\n- Invalid UserID or IP given```");
            }


            char unit = arg[3].ToString().Where(Char.IsLetter).ToArray()[0];

            if (!int.TryParse(new string(arg[3].Where(Char.IsDigit).ToArray()), out int amount) || !validUnits.Contains(unit) || amount < 1)
            {
                return("```diff\n- Invalid duration```");
            }

            TimeSpan duration = GetBanDuration(unit, amount);
            string   reason   = string.Join(" ", arg.Skip(4));


            int index;

            if (validUID)
            {
                index = PlayerManager.players.FindIndex(p => p.GetComponent <CharacterClassManager>().UserId == arg[2]);
            }
            else
            {
                index = PlayerManager.players.FindIndex(p => p.GetComponent <CharacterClassManager>().connectionToClient.address == arg[2]);
            }

            if (index > -1)
            {
                PheggPlayer player = new PheggPlayer(PlayerManager.players[index]);

                player.Ban(duration.Minutes, reason, jObject["Staff"].ToString(), true);
                player.Kick(reason);
            }
            else
            {
                BanHandler.IssueBan(new BanDetails
                {
                    OriginalName = "Offline player",
                    Id           = arg[2],
                    Issuer       = jObject["Staff"].ToString(),
                    IssuanceTime = DateTime.UtcNow.Ticks,
                    Expires      = DateTime.UtcNow.Add(duration).Ticks,
                    Reason       = reason
                }, (validUID ? BanHandler.BanType.UserId : BanHandler.BanType.IP));
            }

            return($"`{arg[2]}` was banned for {arg[3]} with reason {reason}!");
        }
Exemplo n.º 24
0
        public bool Execute(ArraySegment <string> arguments, ICommandSender sender, out string response)
        {
            EasyUnban.IpBans = new List <UserBans>();
            EasyUnban.IdBans = new List <UserBans>();

            bool ipBans = true;
            bool idBans = true;

            string[] ipBansTxt;
            string[] idBansTxt;

            if (EasyUnban.Singleton.Config.ManualDirectory == false)
            {
                ipBansTxt = File.ReadAllLines(BanHandler.GetPath(BanHandler.BanType.IP));
                idBansTxt = File.ReadAllLines(BanHandler.GetPath(BanHandler.BanType.UserId));
            }
            else
            {
                try
                {
                    ipBansTxt = File.ReadAllLines(EasyUnban.Singleton.Config.ManualIpBanDirectory);
                    idBansTxt = File.ReadAllLines(EasyUnban.Singleton.Config.ManualIdBanDirectory);
                }
                catch
                {
                    Log.Error("MANUAL IP OR ID DIRECTORIES DOES NOT EXIST! DOES THE FILE EXISTS AT LEAST??");
                    Log.Error("MANUAL IP OR ID DIRECTORIES DOES NOT EXIST! DOES THE FILE EXISTS AT LEAST??");
                    Log.Error("MANUAL IP OR ID DIRECTORIES DOES NOT EXIST! DOES THE FILE EXISTS AT LEAST??");
                    response = "ERROR: could not update! the Manual directories are invalid in config file!";
                    return(false);
                }
            }

            List <BannedUserInfo> bannedUserIds = new List <BannedUserInfo>();
            List <BannedUserInfo> bannedUserIps = new List <BannedUserInfo>();

            for (int i = 0; i < ipBansTxt.Length; i++)
            {
                string[] e = ipBansTxt[i].Split(';');
                bannedUserIps.Add(new BannedUserInfo(e[0], e[1]));
            }

            for (int i = 0; i < idBansTxt.Length; i++)
            {
                string[] e = idBansTxt[i].Split(';');
                bannedUserIds.Add(new BannedUserInfo(e[0], e[1]));
            }

            if (bannedUserIds.Count == 0)
            {
                idBans = false;
            }
            else
            {
                for (int i = 0; i < bannedUserIds.Count; i++)
                {
                    EasyUnban.IdBans.Add(new UserBans(bannedUserIds[i].Name, bannedUserIds[i].Ban, i));
                }
            }

            if (bannedUserIps.Count == 0)
            {
                ipBans = false;
            }
            else
            {
                for (int i = 0; i < bannedUserIps.Count; i++)
                {
                    EasyUnban.IpBans.Add(new UserBans(bannedUserIps[i].Name, bannedUserIps[i].Ban, i));
                }
            }

            if (idBans == false && ipBans == false)
            {
                EasyUnban.IdBans = null;
                EasyUnban.IpBans = null;
            }

            response = EasyUnban.Singleton.Config.ReloadBansCmdDoneMsg;
            return(true);
        }
        /// <summary>
        /// Clear a punish to the specified <see cref="Player"/>.
        /// </summary>
        /// <param name="player">The <see cref="Collections.Player"/> player.</param>
        /// <param name="type"> the <see cref="Enums.PunishType"/>.</param>
        /// <param name="id"> the punish id.</param>
        /// <param name="server"> the server port.</param>
        public static void ClearPunishment(Collections.Player player, PunishType?type, int id, int server)
        {
            switch (type)
            {
            case PunishType.Ban:
                Ban ban = BanCollection.FindOne(b => b.Target == player && b.BanId == id && b.Server == server);

                JsonManager.PunishToCache(type, JsonConvert.SerializeObject(ban), player, ActionType.Remove);

                if (player.IsBanned())
                {
                    BanHandler.RemoveBan($"{player.Id}@{player.Authentication}", BanHandler.BanType.IP);
                }

                BanCollection.Delete(ban.Id);
                break;

            case PunishType.Kick:
                Kick kick = KickCollection.FindOne(k => k.Target == player && k.KickId == id && k.Server == server);

                JsonManager.PunishToCache(type, JsonConvert.SerializeObject(kick), player, ActionType.Remove);

                KickCollection.Delete(kick.Id);
                break;

            case PunishType.Mute:
                Mute mute = MuteCollection.FindOne(m => m.Target == player && m.MuteId == id && m.Server == server);

                JsonManager.PunishToCache(type, JsonConvert.SerializeObject(mute), player, ActionType.Remove);

                if (player.IsMuted())
                {
                    MuteHandler.RevokePersistentMute($"{player.Id}@{player.Authentication}");
                }

                MuteCollection.Delete(mute.Id);
                break;

            case PunishType.Warn:
                Warn warn = WarnCollection.FindOne(w => w.Target == player && w.WarnId == id && w.Server == server);

                JsonManager.PunishToCache(type, JsonConvert.SerializeObject(warn), player, ActionType.Remove);

                WarnCollection.Delete(warn.Id);
                break;

            case PunishType.SoftWarn:
                SoftWarn softWarn = SoftWarnCollection.FindOne(sw => sw.Target == player && sw.SoftWarnId == id && sw.Server == server);

                JsonManager.PunishToCache(type, JsonConvert.SerializeObject(softWarn), player, ActionType.Remove);

                SoftWarnCollection.Delete(softWarn.Id);
                break;

            case PunishType.SoftBan:
                SoftBan softBan = SoftBanCollection.FindOne(sb => sb.Target == player && sb.SoftBanId == id && sb.Server == server);

                JsonManager.PunishToCache(type, JsonConvert.SerializeObject(softBan), player, ActionType.Remove);

                SoftBanCollection.Delete(softBan.Id);
                break;

            case PunishType.WatchList:
                WatchList watchList = WatchListCollection.FindOne(wl => wl.Target == player && wl.WatchListId == id && wl.Server == server);

                JsonManager.PunishToCache(type, JsonConvert.SerializeObject(watchList), player, ActionType.Remove);

                WatchListCollection.Delete(watchList.Id);
                break;
            }
        }
Exemplo n.º 26
0
        public bool Execute(ArraySegment <string> arguments, ICommandSender sender, out string response)
        {
            BanHandler.GetPath(BanHandler.BanType.IP);
            if (arguments.Count != 0)
            {
                response = EasyUnban.Singleton.Config.PardonCmdRunningMsg;

                string plyName = arguments.At(0);

                string steamId = string.Empty;
                string userIp  = string.Empty;

                string[] ipBansTxt = File.ReadAllLines(BanHandler.GetPath(BanHandler.BanType.IP));
                string[] idBansTxt = File.ReadAllLines(BanHandler.GetPath(BanHandler.BanType.UserId));

                List <BannedUserInfo> bannedUserIds = new List <BannedUserInfo>();
                List <BannedUserInfo> bannedUserIps = new List <BannedUserInfo>();

                for (int i = 0; i < ipBansTxt.Length; i++)
                {
                    string[] e = ipBansTxt[i].Split(';');
                    bannedUserIps.Add(new BannedUserInfo(e[0], e[1]));
                }

                for (int i = 0; i < idBansTxt.Length; i++)
                {
                    string[] e = idBansTxt[i].Split(';');
                    bannedUserIds.Add(new BannedUserInfo(e[0], e[1]));
                }

                if (bannedUserIps.Exists(e => e.Name == plyName))
                {
                    userIp = bannedUserIps.Find(e => e.Name == plyName).Ban;
                }
                else
                {
                    response += "\n" +
                                EasyUnban.Singleton.Config.PardonCmdUserNotIpOrIdBanned.Replace("{BanType}", "Ip");
                }

                if (bannedUserIds.Exists(e => e.Name == plyName))
                {
                    steamId = bannedUserIds.Find(e => e.Name == plyName).Ban;
                }
                else
                {
                    response += "\n" +
                                EasyUnban.Singleton.Config.PardonCmdUserNotIpOrIdBanned.Replace("{BanType}", "UserId");
                }

                if (steamId != string.Empty)
                {
                    BanHandler.RemoveBan(steamId, BanHandler.BanType.UserId);
                }
                if (userIp != string.Empty)
                {
                    BanHandler.RemoveBan(userIp, BanHandler.BanType.IP);
                }
                if (steamId == string.Empty && userIp == string.Empty)
                {
                    response += EasyUnban.Singleton.Config.PardonCmdUserIsNotBanned;
                    return(false);
                }

                response += EasyUnban.Singleton.Config.PardonCmdUserIsUnbanned;
                return(true);
            }

            response = EasyUnban.Singleton.Config.PardonCmdUserArgumentMissing;
            return(false);
        }
Exemplo n.º 27
0
        public bool Execute(ArraySegment <string> arguments, ICommandSender sender, out string response)
        {
            string target;

            if (!sender.CheckPermission("scputils.unwarn"))
            {
                response = "You need a higher administration level to use this command!";
                return(false);
            }
            else
            {
                if (arguments.Count < 2)
                {
                    response = $"<color=yellow>Usage: {Command} <player name/id> <WarnID></color>";
                    return(false);
                }
                else
                {
                    target = arguments.Array[1].ToString();
                }
            }
            Player databasePlayer = target.GetDatabasePlayer();

            if (databasePlayer == null)
            {
                response = $"<color=yellow>Player not found on Database or Player is loading data!</color>";
                return(false);
            }
            bool success = int.TryParse(arguments.Array[2], out int id);

            if (!success)
            {
                response = $"Parameter is not an integer!";
                return(false);
            }

            if ((databasePlayer.SuicideScp.Count - 1) < id || id < 0)
            {
                response = $"Warning with index {id} not found!";
                return(true);
            }
            string message = "Success!";

            switch (databasePlayer.SuicidePunishment[id])
            {
            case "Warn":
                databasePlayer.ScpSuicideCount--;
                databasePlayer.SuicidePunishment[id] = "REMOVED";
                databasePlayer.LogStaffer[id]        = sender.LogName;
                databasePlayer.UserNotified[id]      = true;
                Database.LiteDatabase.GetCollection <Player>().Update(databasePlayer);
                break;

            case "Kick":
                databasePlayer.ScpSuicideCount--;
                databasePlayer.TotalScpSuicideKicks--;
                databasePlayer.SuicidePunishment[id] = "REMOVED";
                databasePlayer.LogStaffer[id]        = sender.LogName;
                databasePlayer.UserNotified[id]      = true;
                Database.LiteDatabase.GetCollection <Player>().Update(databasePlayer);
                break;

            case "Ban":
                databasePlayer.ScpSuicideCount--;
                databasePlayer.TotalScpSuicideBans--;
                databasePlayer.SuicidePunishment[id] = "REMOVED";
                databasePlayer.LogStaffer[id]        = sender.LogName;
                databasePlayer.UserNotified[id]      = true;
                Database.LiteDatabase.GetCollection <Player>().Update(databasePlayer);
                if (DateTime.Now < databasePlayer.Expire[id])
                {
                    BanHandler.RemoveBan($"{databasePlayer.Id}@{databasePlayer.Authentication}", BanHandler.BanType.UserId);
                    BanHandler.RemoveBan(databasePlayer.Ip, BanHandler.BanType.IP);
                }
                break;

            case "Round-Ban":
                databasePlayer.ScpSuicideCount--;
                databasePlayer.TotalScpSuicideBans--;
                databasePlayer.SuicidePunishment[id] = "REMOVED";
                databasePlayer.LogStaffer[id]        = sender.LogName;
                databasePlayer.UserNotified[id]      = true;

                databasePlayer.RoundBanLeft -= databasePlayer.RoundsBan[id];
                if (databasePlayer.RoundBanLeft < 0)
                {
                    databasePlayer.RoundBanLeft = 0;
                }


                Database.LiteDatabase.GetCollection <Player>().Update(databasePlayer);

                break;

            case "REMOVED":
                message = "This sanction has already been removed!";
                break;

            default:
                break;
            }


            response = $"{message}";

            return(true);
        }