Example #1
0
        internal bool CheckBan(TSPlayer player)
        {
            List <string> identifiers = new List <string>
            {
                $"{Identifier.UUID}{player.UUID}",
                $"{Identifier.Name}{player.Name}",
                $"{Identifier.IP}{player.IP}"
            };

            if (player.Account != null)
            {
                identifiers.Add($"{Identifier.Account}{player.Account.Name}");
            }

            Ban ban = TShock.Bans.Bans.FirstOrDefault(b => identifiers.Contains(b.Value.Identifier) && TShock.Bans.IsValidBan(b.Value, player)).Value;

            if (ban != null)
            {
                if (ban.ExpirationDateTime == DateTime.MaxValue)
                {
                    player.Disconnect("You are banned: " + ban.Reason);
                    return(true);
                }

                TimeSpan ts = ban.ExpirationDateTime - DateTime.UtcNow;
                player.Disconnect($"You are banned: {ban.Reason} ({ban.GetPrettyExpirationString()} remaining)");
                return(true);
            }

            return(false);
        }
Example #2
0
        private void OnServerConnect(ConnectEventArgs args)
        {
            if (TShock.ShuttingDown)
            {
                NetMessage.SendData(2, args.Who, -1, NetworkText.FromLiteral("Server is shutting down..."));
                args.Handled = true;
                return;
            }

            var player = new TSPlayer(args.Who);

            Utils.CacheIP?.SetValue(player, _forward[args.Who].IP);
            if (TShock.Utils.ActivePlayers() + 1 > TShock.Config.MaxSlots + TShock.Config.ReservedSlots)
            {
                player.Disconnect(TShock.Config.ServerFullNoReservedReason);
                args.Handled = true;
                return;
            }

            if (!FileTools.OnWhitelist(player.IP))
            {
                player.Disconnect(TShock.Config.WhitelistKickReason);
                args.Handled = true;
                return;
            }

            if (TShock.Geo != null)
            {
                var code = TShock.Geo.TryGetCountryCode(IPAddress.Parse(player.IP));
                player.Country = code == null ? "N/A" : GeoIPCountry.GetCountryNameByCode(code);
                if (code == "A1" && TShock.Config.KickProxyUsers)
                {
                    player.Disconnect("Proxies are not allowed.");
                    args.Handled = true;
                    return;
                }
            }

            TShock.Players[args.Who] = player;
        }
Example #3
0
        /// <summary>
        /// Asserts that the group reference can be safely assigned to the player object.
        /// <para>If this assertion fails, and <paramref name="kick"/> is true, the player is disconnected. If <paramref name="kick"/> is false, the player will receive an error message.</para>
        /// </summary>
        /// <param name="player">The player in question</param>
        /// <param name="group">The group we want to assign them</param>
        /// <param name="kick">Whether or not failing this check disconnects the player.</param>
        /// <returns></returns>
        public bool AssertGroupValid(TSPlayer player, Group group, bool kick)
        {
            if (group == null)
            {
                if (kick)
                {
                    player.Disconnect("Your account's group could not be loaded. Please contact server administrators about this.");
                }
                else
                {
                    player.SendErrorMessage("Your account's group could not be loaded. Please contact server administrators about this.");
                }
                return(false);
            }

            return(true);
        }
Example #4
0
        private void OnJoin(JoinEventArgs args)
        {
            TSPlayer plr  = new TSPlayer(args.Who);//实例化一个玩家对象
            string   name = plr.Name;

            players.Add(name, new TSPlayer(args.Who)); //将玩家以TSPlayer对象存储在players字典中
            if (_config.Disabled == true)              //检测插件是否开启
            {
                TShock.Log.ConsoleInfo(_translation.language["NotEnabled"]);
            }
            else
            {
                if (!_config.WhitePlayers.Contains(name))               //检测玩家是否在白名单
                {
                    plr.Disconnect(_translation.language["NotOnList"]); //阻止非白名单玩家进入服务器
                }
            }
        }
Example #5
0
        /// <summary>
        ///     Checks the infractions. If the total number of points exceeds the threshold set in the configuration, then a
        ///     temporary ban will be issued.
        /// </summary>
        public void CheckInfractions()
        {
            if (_infractions.RemoveAll(i => DateTime.UtcNow > i.Expiration) > 0)
            {
                Save();
            }

            var config      = NoCheatConfig.Instance;
            var totalPoints = _infractions.Sum(i => i.Points);

            if (totalPoints > config.PointThreshold && !_player.HasPermission(Permissions.immunetoban))
            {
                _player.Disconnect($"Banned: {config.BanMessage}");
                TSPlayer.All.SendInfoMessage($"{_player.Name} was banned for '{config.BanMessage}'.");
                TShock.Bans.AddBan(_player.IP, _player.Name, _player.UUID, config.BanMessage,
                                   expiration: DateTime.UtcNow.Add(config.BanDuration).ToString("s"));
            }
        }
Example #6
0
        /// <summary>Fired when a player joins the server</summary>
        /// <param name="args">The JoinEventArgs object</param>
        public void OnJoin(JoinEventArgs args)
        {
            //If player was disconnected by another component, skip
            if (args.Handled)
            {
                return;
            }
            //If IP banning isn't used, skip
            if (!TShock.Config.EnableIPBans)
            {
                return;
            }
            //Creates TSPlayer player object for easy access
            TSPlayer player = TShock.Players[args.Who];
            //Searches a ban by player's IP
            CIDRBan ban = cidrbans.GetCIDRBanByIP(player.IP);

            //If no ban is found or ban has expired, skip
            if (ban == null)
            {
                return;
            }
            //DateTime exp object
            DateTime exp;

            //If player's ban has no expiration date, say ban forever
            if (!DateTime.TryParse(ban.Expiration, out exp))
            {
                player.Disconnect("You are banned forever: " + ban.Reason);
            }
            //If player's ban is temporary, check if it has expired or not
            else
            {
                //If player's ban has expired, remove the ban
                if (DateTime.UtcNow >= exp)
                {
                    cidrbans.DelCIDRBanByRange(ban.CIDR);
                    return;
                }
                //Finds time left from now to expiration date
                TimeSpan ts = exp - DateTime.UtcNow;
                //Makes 30 days count shows as one month
                int months = ts.Days / 30;
                //Converts timespan object into time string to inform player
                if (months > 0)
                {
                    player.Disconnect(String.Format("You are banned for {0} month{1} and {2} day{3}: {4}",
                                                    months, months == 1 ? "" : "s", ts.Days, ts.Days == 1 ? "" : "s", ban.Reason));
                }
                else if (ts.Days > 0)
                {
                    player.Disconnect(String.Format("You are banned for {0} day{1} and {2} hour{3}: {4}",
                                                    ts.Days, ts.Days == 1 ? "" : "s", ts.Hours, ts.Hours == 1 ? "" : "s", ban.Reason));
                }
                else if (ts.Hours > 0)
                {
                    player.Disconnect(String.Format("You are banned for {0} hour{1} and {2} minute{3}: {4}",
                                                    ts.Hours, ts.Hours == 1 ? "" : "s", ts.Minutes, ts.Minutes == 1 ? "" : "s", ban.Reason));
                }
                else if (ts.Minutes > 0)
                {
                    player.Disconnect(String.Format("You are banned for {0} minute{1} and {2} second{3}: {4}",
                                                    ts.Minutes, ts.Minutes == 1 ? "" : "s", ts.Seconds, ts.Seconds == 1 ? "" : "s", ban.Reason));
                }
                else
                {
                    player.Disconnect(String.Format("You are banned for {0} second{1}: {2}",
                                                    ts.Seconds, ts.Seconds == 1 ? "" : "s", ban.Reason));
                }
            }
            //Sets player's connection handled
            args.Handled = true;
        }
        public async Task Ban(CommandContext ctx, string user, string time, string reason = "no reason")
        {
            bool   parsedOkay            = false;
            bool   success               = false;
            string targetGeneralizedName = "";
            int    banLengthInSeconds    = 0;

            List <TSPlayer> players            = TSPlayer.FindByNameOrID(user);
            UserAccount     offlineUserAccount = TShock.UserAccounts.GetUserAccountByName(user);

            if (time != "0")
            {
                parsedOkay = TShock.Utils.TryParseTime(time, out banLengthInSeconds);
            }
            else
            {
                parsedOkay = true;
            }

            if (!parsedOkay)
            {
                var emojitime = DiscordEmoji.FromName(ctx.Client, ":warning:");
                var embedtime = new DiscordEmbedBuilder
                {
                    Title       = "Invalid time format",
                    Description = $"{emojitime} Example: *0 (permanent), 10d 5h 3m 2s*",
                    Color       = new DiscordColor(0xFF0000) // red
                };
                await ctx.RespondAsync("", embed : embedtime);

                return;
            }

            if (players.Count == 1)
            {
                TSPlayer target = players[0];
                if (target.HasPermission(Permissions.immunetoban))
                {
                    var emojiimmune = DiscordEmoji.FromName(ctx.Client, ":warning:");
                    var embedimmune = new DiscordEmbedBuilder
                    {
                        Title       = "Permissions denied!",
                        Description = $"{emojiimmune} Player is immune to ban!",
                        Color       = new DiscordColor(0xFF0000) // red
                    };
                    await ctx.RespondAsync("", embed : embedimmune);

                    return;
                }

                targetGeneralizedName = target.Name;
                success = TShock.Bans.AddBan(target.IP, target.Name, target.UUID, target.Account?.Name ?? "", reason, false, ctx.User.Username + "#" + ctx.User.Discriminator,
                                             banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));

                //Terraria4PDA.CommandManager.AdvancedBan.AddBanToDB(target.IP, target.Name, target.UUID, target.Account?.Name ?? "", reason, ctx.User.Username + "#" + ctx.User.Discriminator,
                //    banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));

                if (success)
                {
                    if (banLengthInSeconds == 0)
                    {
                        target.Disconnect(string.Format("Permanently banned for {0}", reason));
                    }
                    else
                    {
                        target.Disconnect(string.Format("Banned for {0} seconds for {1}", banLengthInSeconds, reason));
                    }
                }
            }
            if (players.Count == 0)
            {
                // If the target is a valid IP...
                string pattern = @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
                Regex  r       = new Regex(pattern, RegexOptions.IgnoreCase);
                if (r.IsMatch(user))
                {
                    targetGeneralizedName = "IP: " + user;
                    success = TShock.Bans.AddBan(user, "", "", "", reason,
                                                 false, ctx.User.Username, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));

                    //CommandManager.AdvancedBan.AddBanToDB(user, "", "", "", reason,
                    //    ctx.User.Username, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));


                    if (success && offlineUserAccount != null)
                    {
                        var emojiip = DiscordEmoji.FromName(ctx.Client, ":b:");
                        var embedip = new DiscordEmbedBuilder
                        {
                            Title       = $"{emojiip} IP banned successfully!",
                            Description = $"**IP:** `{user}`\n**Time:** `{time}`\n**Reason:** `{reason}`",
                            Color       = new DiscordColor(0x00fd2c) // green
                        };
                        await ctx.RespondAsync("", embed : embedip);
                    }
                }
                else
                {
                    // Apparently there is no way to not IP ban someone
                    // This means that where we would normally just ban a "character name" here
                    // We can't because it requires some IP as a primary key.
                    if (offlineUserAccount == null)
                    {
                        var emojierror = DiscordEmoji.FromName(ctx.Client, ":warning:");
                        var embederror = new DiscordEmbedBuilder
                        {
                            Title       = "Invalid player/IP!",
                            Description = $"{emojierror} `{user}` not found!!",
                            Color       = new DiscordColor(0xFF0000) // red
                        };
                        await ctx.RespondAsync("", embed : embederror);

                        return;
                    }
                }
            }
            if (players.Count == 0 && offlineUserAccount != null)
            {
                // Catch: we don't know an offline player's last login character name
                // This means that we're banning their *user name* on the assumption that
                // user name == character name
                // (which may not be true)
                // This needs to be fixed in a future implementation.
                targetGeneralizedName = offlineUserAccount.Name;

                if (TShock.Groups.GetGroupByName(offlineUserAccount.Group).HasPermission(TShockAPI.Permissions.immunetoban))
                {
                    var emojiimmune = DiscordEmoji.FromName(ctx.Client, ":warning:");
                    var embedimmune = new DiscordEmbedBuilder
                    {
                        Title       = "Permissions denied!",
                        Description = $"{emojiimmune} Player is immune to ban!",
                        Color       = new DiscordColor(0xFF0000) // red
                    };
                    await ctx.RespondAsync("", embed : embedimmune);

                    return;
                }

                if (offlineUserAccount.KnownIps == null)
                {
                    var emojierror = DiscordEmoji.FromName(ctx.Client, ":warning:");
                    var embederror = new DiscordEmbedBuilder
                    {
                        Title       = "Error!",
                        Description = $"{emojierror} `{user}` have no valid IP to ban.",
                        Color       = new DiscordColor(0xFF0000) // red
                    };
                    await ctx.RespondAsync("", embed : embederror);

                    return;
                }

                string lastIP = JsonConvert.DeserializeObject <List <string> >(offlineUserAccount.KnownIps).Last();

                success =
                    TShock.Bans.AddBan(lastIP,
                                       "", offlineUserAccount.UUID, offlineUserAccount.Name, reason, false, ctx.User.Username,
                                       banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));

                //CommandManager.AdvancedBan.AddBanToDB(lastIP,
                //    "", offlineUserAccount.UUID, offlineUserAccount.Name, reason, ctx.User.Username,
                //    banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
            }

            if (success)
            {
                var emojiban = DiscordEmoji.FromName(ctx.Client, ":b:");
                var embedban = new DiscordEmbedBuilder
                {
                    Title = "Player successfully banned!",
                    Color = new DiscordColor(0x00fd2c) // green
                };
                if (banLengthInSeconds == 0)
                {
                    embedban.AddField("Description", $"{emojiban} Player `{user}` was successfully banned **PERMANENTLY** for `{reason}`!*");
                }
                else
                {
                    embedban.AddField("Description", $"{emojiban} Player `{user}` was successfully banned for *{time}* for `{reason}`!*");
                }

                await ctx.RespondAsync("", embed : embedban);
            }
            else
            {
                var emojierror = DiscordEmoji.FromName(ctx.Client, ":warning:");
                var embederror = new DiscordEmbedBuilder
                {
                    Title       = "System error!",
                    Description = $"{emojierror} Player was NOT banned due to a database error or other system problem.",
                    Color       = new DiscordColor(0xFF0000) // red
                };
                await ctx.RespondAsync("", embed : embederror);
            }

            return;
        }
Example #8
0
        public void OnJoin(JoinEventArgs args)
        {
            if (args.Handled)
            {
                return;
            }
            if (!TShock.Config.EnableIPBans)
            {
                return;
            }

            // search a ban by player's IP
            TSPlayer player = TShock.Players[args.Who];
            CIDRBan  ban    = cidrbans.GetCIDRBanByIP(player.IP);

            if (ban == null)
            {
                return;
            }

            // parse expiration date
            DateTime exp;

            if (!DateTime.TryParse(ban.Expiration, out exp))
            {
                // no expiration date implies permaban
                player.Disconnect("You are banned forever: " + ban.Reason);
            }
            else
            {
                // remove a ban past the expiration date
                if (DateTime.UtcNow >= exp)
                {
                    cidrbans.DelCIDRBanByRange(ban.CIDR);
                    return;
                }

                // generate remaining ban time string for player
                TimeSpan ts     = exp - DateTime.UtcNow;
                int      months = ts.Days / 30;
                if (months > 0)
                {
                    player.Disconnect(String.Format("You are banned for {0} month{1} and {2} day{3}: {4}",
                                                    months, months == 1 ? "" : "s", ts.Days, ts.Days == 1 ? "" : "s", ban.Reason));
                }
                else if (ts.Days > 0)
                {
                    player.Disconnect(String.Format("You are banned for {0} day{1} and {2} hour{3}: {4}",
                                                    ts.Days, ts.Days == 1 ? "" : "s", ts.Hours, ts.Hours == 1 ? "" : "s", ban.Reason));
                }
                else if (ts.Hours > 0)
                {
                    player.Disconnect(String.Format("You are banned for {0} hour{1} and {2} minute{3}: {4}",
                                                    ts.Hours, ts.Hours == 1 ? "" : "s", ts.Minutes, ts.Minutes == 1 ? "" : "s", ban.Reason));
                }
                else if (ts.Minutes > 0)
                {
                    player.Disconnect(String.Format("You are banned for {0} minute{1} and {2} second{3}: {4}",
                                                    ts.Minutes, ts.Minutes == 1 ? "" : "s", ts.Seconds, ts.Seconds == 1 ? "" : "s", ban.Reason));
                }
                else
                {
                    player.Disconnect(String.Format("You are banned for {0} second{1}: {2}",
                                                    ts.Seconds, ts.Seconds == 1 ? "" : "s", ban.Reason));
                }
            }

            args.Handled = true;
        }