Skip to content

Commit

Permalink
Merge pull request #625
Browse files Browse the repository at this point in the history
* Basic rate limiting for chat messages (#21907)

* Yep

* Merge remote-tracking branch 'upstream/master' into 23-11-26-chat-rat…
  • Loading branch information
dvir001 authored Dec 10, 2023
1 parent f290021 commit b9f658d
Show file tree
Hide file tree
Showing 7 changed files with 151 additions and 3 deletions.
84 changes: 84 additions & 0 deletions Content.Server/Chat/Managers/ChatManager.RateLimit.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
using System.Runtime.InteropServices;
using Content.Shared.CCVar;
using Content.Shared.Database;
using Robust.Shared.Enums;
using Robust.Shared.Player;
using Robust.Shared.Timing;

namespace Content.Server.Chat.Managers;

internal sealed partial class ChatManager
{
private readonly Dictionary<ICommonSession, RateLimitDatum> _rateLimitData = new();

public bool HandleRateLimit(ICommonSession player)
{
ref var datum = ref CollectionsMarshal.GetValueRefOrAddDefault(_rateLimitData, player, out _);
var time = _gameTiming.RealTime;
if (datum.CountExpires < time)
{
// Period expired, reset it.
var periodLength = _configurationManager.GetCVar(CCVars.ChatRateLimitPeriod);
datum.CountExpires = time + TimeSpan.FromSeconds(periodLength);
datum.Count = 0;
datum.Announced = false;
}

var maxCount = _configurationManager.GetCVar(CCVars.ChatRateLimitCount);
datum.Count += 1;

if (datum.Count <= maxCount)
return true;

// Breached rate limits, inform admins if configured.
if (_configurationManager.GetCVar(CCVars.ChatRateLimitAnnounceAdmins))
{
if (datum.NextAdminAnnounce < time)
{
SendAdminAlert(Loc.GetString("chat-manager-rate-limit-admin-announcement", ("player", player.Name)));
var delay = _configurationManager.GetCVar(CCVars.ChatRateLimitAnnounceAdminsDelay);
datum.NextAdminAnnounce = time + TimeSpan.FromSeconds(delay);
}
}

if (!datum.Announced)
{
DispatchServerMessage(player, Loc.GetString("chat-manager-rate-limited"), suppressLog: true);
_adminLogger.Add(LogType.ChatRateLimited, LogImpact.Medium, $"Player {player} breached chat rate limits");

datum.Announced = true;
}

return false;
}

private void PlayerStatusChanged(object? sender, SessionStatusEventArgs e)
{
if (e.NewStatus == SessionStatus.Disconnected)
_rateLimitData.Remove(e.Session);
}

private struct RateLimitDatum
{
/// <summary>
/// Time stamp (relative to <see cref="IGameTiming.RealTime"/>) this rate limit period will expire at.
/// </summary>
public TimeSpan CountExpires;

/// <summary>
/// How many messages have been sent in the current rate limit period.
/// </summary>
public int Count;

/// <summary>
/// Have we announced to the player that they've been blocked in this rate limit period?
/// </summary>
public bool Announced;

/// <summary>
/// Time stamp (relative to <see cref="IGameTiming.RealTime"/>) of the
/// next time we can send an announcement to admins about rate limit breach.
/// </summary>
public TimeSpan NextAdminAnnounce;
}
}
15 changes: 12 additions & 3 deletions Content.Server/Chat/Managers/ChatManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,20 @@
using Content.Shared.Chat;
using Content.Shared.Database;
using Content.Shared.Mind;
using Robust.Server.Player;
using Robust.Shared.Configuration;
using Robust.Shared.Network;
using Robust.Shared.Player;
using Robust.Shared.Replays;
using Robust.Shared.Timing;
using Robust.Shared.Utility;

namespace Content.Server.Chat.Managers
{
/// <summary>
/// Dispatches chat messages to clients.
/// </summary>
internal sealed class ChatManager : IChatManager
internal sealed partial class ChatManager : IChatManager
{
private static readonly Dictionary<string, string> PatronOocColors = new()
{
Expand All @@ -41,6 +43,8 @@ internal sealed class ChatManager : IChatManager
[Dependency] private readonly IConfigurationManager _configurationManager = default!;
[Dependency] private readonly INetConfigurationManager _netConfigManager = default!;
[Dependency] private readonly IEntityManager _entityManager = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;

/// <summary>
/// The maximum length a player-sent message can be sent
Expand All @@ -59,6 +63,8 @@ public void Initialize()

_configurationManager.OnValueChanged(CCVars.OocEnabled, OnOocEnabledChanged, true);
_configurationManager.OnValueChanged(CCVars.AdminOocEnabled, OnAdminOocEnabledChanged, true);

_playerManager.PlayerStatusChanged += PlayerStatusChanged;
}

private void OnOocEnabledChanged(bool val)
Expand Down Expand Up @@ -178,6 +184,9 @@ public void SendHookOOC(string sender, string message)
/// <param name="type">The type of message.</param>
public void TrySendOOCMessage(ICommonSession player, string message, OOCChatType type)
{
if (!HandleRateLimit(player))
return;

// Check if message exceeds the character limit
if (message.Length > MaxMessageLength)
{
Expand Down Expand Up @@ -215,7 +224,7 @@ private void SendOOC(ICommonSession player, string message)
}

Color? colorOverride = null;
var wrappedMessage = Loc.GetString("chat-manager-send-ooc-wrap-message", ("playerName",player.Name), ("message", FormattedMessage.EscapeText(message)));
var wrappedMessage = Loc.GetString("chat-manager-send-ooc-wrap-message", ("playerName", player.Name), ("message", FormattedMessage.EscapeText(message)));
if (_adminManager.HasAdminFlag(player, AdminFlags.Admin))
{
var prefs = _preferencesManager.GetPreferences(player.UserId);
Expand All @@ -224,7 +233,7 @@ private void SendOOC(ICommonSession player, string message)
if (player.ConnectedClient.UserData.PatronTier is { } patron &&
PatronOocColors.TryGetValue(patron, out var patronColor))
{
wrappedMessage = Loc.GetString("chat-manager-send-ooc-patron-wrap-message", ("patronColor", patronColor),("playerName", player.Name), ("message", FormattedMessage.EscapeText(message)));
wrappedMessage = Loc.GetString("chat-manager-send-ooc-patron-wrap-message", ("patronColor", patronColor), ("playerName", player.Name), ("message", FormattedMessage.EscapeText(message)));
}

//TODO: player.Name color, this will need to change the structure of the MsgChatMessage
Expand Down
8 changes: 8 additions & 0 deletions Content.Server/Chat/Managers/IChatManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,13 @@ void ChatMessageToMany(ChatChannel channel, string message, string wrappedMessag

[return: NotNullIfNotNull(nameof(author))]
ChatUser? EnsurePlayer(NetUserId? author);

/// <summary>
/// Called when a player sends a chat message to handle rate limits.
/// Will update counts and do necessary actions if breached.
/// </summary>
/// <param name="player">The player sending a chat message.</param>
/// <returns>False if the player has violated rate limits and should be blocked from sending further messages.</returns>
bool HandleRateLimit(ICommonSession player);
}
}
6 changes: 6 additions & 0 deletions Content.Server/Chat/Systems/ChatSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,9 @@ public void TrySendInGameICMessage(
return;
}

if (player != null && !_chatManager.HandleRateLimit(player))
return;

// Sus
if (player?.AttachedEntity is { Valid: true } entity && source != entity)
{
Expand Down Expand Up @@ -267,6 +270,9 @@ public void TrySendInGameOOCMessage(
if (!CanSendInGame(message, shell, player))
return;

if (player != null && !_chatManager.HandleRateLimit(player))
return;

// It doesn't make any sense for a non-player to send in-game OOC messages, whereas non-players may be sending
// in-game IC messages.
if (player?.AttachedEntity is not { Valid: true } entity || source != entity)
Expand Down
5 changes: 5 additions & 0 deletions Content.Shared.Database/LogType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ public enum LogType
DeviceLinking = 85,
Tile = 86,

/// <summary>
/// A client has sent too many chat messages recently and is temporarily blocked from sending more.
/// </summary>
ChatRateLimited = 87,

// Frontier Station Spesific
ATMUsage = 200,
ShipYardUsage = 201,
Expand Down
33 changes: 33 additions & 0 deletions Content.Shared/CCVar/CCVars.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1480,6 +1480,39 @@ public static readonly CVarDef<int>
* CHAT
*/

/// <summary>
/// Chat rate limit values are accounted in periods of this size (seconds).
/// After the period has passed, the count resets.
/// </summary>
/// <seealso cref="ChatRateLimitCount"/>
public static readonly CVarDef<int> ChatRateLimitPeriod =
CVarDef.Create("chat.rate_limit_period", 2, CVar.SERVERONLY);

/// <summary>
/// How many chat messages are allowed in a single rate limit period.
/// </summary>
/// <remarks>
/// The total rate limit throughput per second is effectively
/// <see cref="ChatRateLimitCount"/> divided by <see cref="ChatRateLimitCount"/>.
/// </remarks>
/// <seealso cref="ChatRateLimitPeriod"/>
/// <seealso cref="ChatRateLimitAnnounceAdmins"/>
public static readonly CVarDef<int> ChatRateLimitCount =
CVarDef.Create("chat.rate_limit_count", 10, CVar.SERVERONLY);

/// <summary>
/// If true, announce when a player breached chat rate limit to game administrators.
/// </summary>
/// <seealso cref="ChatRateLimitAnnounceAdminsDelay"/>
public static readonly CVarDef<bool> ChatRateLimitAnnounceAdmins =
CVarDef.Create("chat.rate_limit_announce_admins", true, CVar.SERVERONLY);

/// <summary>
/// Minimum delay (in seconds) between announcements from <see cref="ChatRateLimitAnnounceAdmins"/>.
/// </summary>
public static readonly CVarDef<int> ChatRateLimitAnnounceAdminsDelay =
CVarDef.Create("chat.rate_limit_announce_admins_delay", 15, CVar.SERVERONLY);

public static readonly CVarDef<int> ChatMaxMessageLength =
CVarDef.Create("chat.max_message_length", 1000, CVar.SERVER | CVar.REPLICATED);

Expand Down
3 changes: 3 additions & 0 deletions Resources/Locale/en-US/chat/managers/chat-manager.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ chat-manager-send-hook-ooc-wrap-message = OOC: [bold](D){$senderName}:[/bold] {$
chat-manager-dead-channel-name = DEAD
chat-manager-admin-channel-name = ADMIN
chat-manager-rate-limited = You are sending messages too quickly!
chat-manager-rate-limit-admin-announcement = Player { $player } breached chat rate limits. Watch them if this is a regular occurence.
## Speech verbs for chat

chat-speech-verb-suffix-exclamation = !
Expand Down

0 comments on commit b9f658d

Please sign in to comment.