Some fixes and security updates
This commit is contained in:
parent
43acf366af
commit
68e6fa2353
22 changed files with 1114 additions and 58 deletions
|
|
@ -38,7 +38,7 @@ public class ChatWebSocketManager
|
|||
|
||||
public int ConnectedCount => _clients.Count;
|
||||
|
||||
public async Task HandleClientAsync(WebSocket socket, User user, CancellationToken cancellationToken)
|
||||
public async Task HandleClientAsync(WebSocket socket, User user, CancellationToken cancellationToken, int maxMessageSizeBytes = 1048576)
|
||||
{
|
||||
var client = new ConnectedClient(socket, user);
|
||||
_clients[client.ConnectionId] = client;
|
||||
|
|
@ -104,7 +104,7 @@ public class ChatWebSocketManager
|
|||
|
||||
// Broadcast Presence Update
|
||||
await BroadcastUserListAsync();
|
||||
await BroadcastSystemNoticeAsync($"[+] {user.Username} connected.", "Info");
|
||||
await BroadcastSystemNoticeAsync($"[+] {InputSanitizer.SanitizeUsername(user.Username)} connected.", "Info");
|
||||
|
||||
// Main Receive Loop
|
||||
var buffer = new byte[8192];
|
||||
|
|
@ -123,6 +123,14 @@ public class ChatWebSocketManager
|
|||
{
|
||||
messageAccumulator.AddRange(buffer.Take(result.Count));
|
||||
|
||||
// Check message size limit
|
||||
if (messageAccumulator.Count > maxMessageSizeBytes)
|
||||
{
|
||||
messageAccumulator.Clear();
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Message too large." }, cancellationToken);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (result.EndOfMessage)
|
||||
{
|
||||
string json = Encoding.UTF8.GetString(messageAccumulator.ToArray());
|
||||
|
|
@ -135,11 +143,11 @@ public class ChatWebSocketManager
|
|||
catch (OperationCanceledException) { }
|
||||
catch (WebSocketException ex)
|
||||
{
|
||||
_logger.LogDebug("WebSocket error for {Username}: {Msg}", user.Username, ex.Message);
|
||||
SafeLogger.LogDebug(_logger, "WebSocket error for {Username}: {Msg}", InputSanitizer.SanitizeUsername(user.Username), ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Unexpected error handling client {Username}", user.Username);
|
||||
SafeLogger.LogError(_logger, ex, "Unexpected error handling client {Username}", InputSanitizer.SanitizeUsername(user.Username));
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -156,7 +164,7 @@ public class ChatWebSocketManager
|
|||
catch { }
|
||||
|
||||
await BroadcastUserListAsync();
|
||||
await BroadcastSystemNoticeAsync($"[-] {user.Username} disconnected.", "Info");
|
||||
await BroadcastSystemNoticeAsync($"[-] {InputSanitizer.SanitizeUsername(user.Username)} disconnected.", "Info");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -282,9 +290,9 @@ public class ChatWebSocketManager
|
|||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch (Exception)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to process message from client {Username}", client.User.Username);
|
||||
SafeLogger.LogWarning(_logger, "Failed to process message from client {Username}", InputSanitizer.SanitizeUsername(client.User.Username));
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Failed to process message." }, ct);
|
||||
}
|
||||
}
|
||||
|
|
@ -370,7 +378,7 @@ public class ChatWebSocketManager
|
|||
{
|
||||
await BroadcastToMembersAsync(dm.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket
|
||||
{
|
||||
Text = $"@{client.User.Username} reset their E2EE keypair.",
|
||||
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} reset their E2EE keypair.",
|
||||
Level = "Warning"
|
||||
});
|
||||
}
|
||||
|
|
@ -398,7 +406,7 @@ public class ChatWebSocketManager
|
|||
await SyncChannelListForUsersAsync(affectedUsers);
|
||||
await BroadcastToMembersAsync(affectedUsers, MessageTypes.SystemNotice, new SystemNoticePacket
|
||||
{
|
||||
Text = $"@{client.User.Username} {(packet.Enabled ? "enabled" : "disabled")} E2EE for their account.",
|
||||
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} {(packet.Enabled ? "enabled" : "disabled")} E2EE for their account.",
|
||||
Level = packet.Enabled ? "Success" : "Warning"
|
||||
});
|
||||
}
|
||||
|
|
@ -423,7 +431,7 @@ public class ChatWebSocketManager
|
|||
await SyncChannelListForUsersAsync(channel.MemberIds);
|
||||
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket
|
||||
{
|
||||
Text = $"@{client.User.Username} {(packet.Enabled ? "enabled" : "disabled")} E2EE for this Direct Message.",
|
||||
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} {(packet.Enabled ? "enabled" : "disabled")} E2EE for this Direct Message.",
|
||||
Level = packet.Enabled ? "Success" : "Warning"
|
||||
});
|
||||
}
|
||||
|
|
@ -544,6 +552,12 @@ public class ChatWebSocketManager
|
|||
|
||||
private async Task HandleStartDmAsync(ConnectedClient client, StartDmPacket packet, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(packet.TargetUserId) && !InputSanitizer.IsValidUserId(packet.TargetUserId))
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Invalid user ID." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
User? targetUser = null;
|
||||
if (!string.IsNullOrWhiteSpace(packet.TargetUserId))
|
||||
{
|
||||
|
|
@ -551,7 +565,7 @@ public class ChatWebSocketManager
|
|||
}
|
||||
if (targetUser == null && !string.IsNullOrWhiteSpace(packet.TargetUsername))
|
||||
{
|
||||
string cleanName = packet.TargetUsername.Trim().TrimStart('@');
|
||||
string cleanName = InputSanitizer.SanitizeUsername(packet.TargetUsername.Trim().TrimStart('@'));
|
||||
targetUser = await _db.GetUserByUsernameAsync(cleanName);
|
||||
}
|
||||
|
||||
|
|
@ -579,6 +593,13 @@ public class ChatWebSocketManager
|
|||
return;
|
||||
}
|
||||
|
||||
string sanitizedName = InputSanitizer.SanitizeChannelName(packet.Name);
|
||||
if (sanitizedName.Length < 2)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Group name contains invalid characters." }, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
int serverMax = Math.Max(2, _options.MaxGroupChatUsers);
|
||||
int groupMax = packet.MaxUsers.HasValue && packet.MaxUsers.Value > 0 ? packet.MaxUsers.Value : serverMax;
|
||||
|
||||
|
|
@ -601,7 +622,7 @@ public class ChatWebSocketManager
|
|||
var parts = rawName.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (var p in parts)
|
||||
{
|
||||
string cleanUser = p.Trim().TrimStart('@');
|
||||
string cleanUser = InputSanitizer.SanitizeUsername(p.Trim().TrimStart('@'));
|
||||
if (string.IsNullOrWhiteSpace(cleanUser)) continue;
|
||||
var u = await _db.GetUserByUsernameAsync(cleanUser);
|
||||
if (u == null)
|
||||
|
|
@ -623,7 +644,7 @@ public class ChatWebSocketManager
|
|||
return;
|
||||
}
|
||||
|
||||
var group = await _db.CreateGroupChatAsync(packet.Name.Trim(), packet.Topic ?? string.Empty, client.User.Id, memberIds, groupMax);
|
||||
var group = await _db.CreateGroupChatAsync(sanitizedName, InputSanitizer.SanitizeForDisplay(packet.Topic ?? string.Empty), client.User.Id, memberIds, groupMax);
|
||||
client.ActiveChannelId = group.Id;
|
||||
|
||||
await SyncChannelListForUsersAsync(group.MemberIds);
|
||||
|
|
@ -638,7 +659,7 @@ public class ChatWebSocketManager
|
|||
MessageTypes.SystemNotice,
|
||||
new SystemNoticePacket
|
||||
{
|
||||
Text = $"Group chat '{group.Name}' created by @{client.User.Username} ({group.MemberIds.Count}/{group.MaxUsers} members).",
|
||||
Text = $"Group chat '{InputSanitizer.SanitizeChannelName(group.Name)}' created by @{InputSanitizer.SanitizeUsername(client.User.Username)} ({group.MemberIds.Count}/{group.MaxUsers} members).",
|
||||
Level = "Success"
|
||||
});
|
||||
}
|
||||
|
|
@ -699,7 +720,7 @@ public class ChatWebSocketManager
|
|||
MessageTypes.SystemNotice,
|
||||
new SystemNoticePacket
|
||||
{
|
||||
Text = $"@{targetUser.Username} was added to group '{group.Name}' by @{client.User.Username}.",
|
||||
Text = $"@{InputSanitizer.SanitizeUsername(targetUser.Username)} was added to group '{InputSanitizer.SanitizeChannelName(group.Name)}' by @{InputSanitizer.SanitizeUsername(client.User.Username)}.",
|
||||
Level = "Info"
|
||||
});
|
||||
}
|
||||
|
|
@ -741,7 +762,7 @@ public class ChatWebSocketManager
|
|||
MessageTypes.SystemNotice,
|
||||
new SystemNoticePacket
|
||||
{
|
||||
Text = $"@{client.User.Username} left group '{group.Name}'.",
|
||||
Text = $"@{InputSanitizer.SanitizeUsername(client.User.Username)} left group '{InputSanitizer.SanitizeChannelName(group.Name)}'.",
|
||||
Level = "Info"
|
||||
});
|
||||
}
|
||||
|
|
@ -783,7 +804,7 @@ public class ChatWebSocketManager
|
|||
ChannelId = channel.Id,
|
||||
Messages = new()
|
||||
}, ct);
|
||||
await BroadcastSystemNoticeAsync($"Channel #{cleanName} was created by {client.User.Username}.", "Success");
|
||||
await BroadcastSystemNoticeAsync($"Channel #{cleanName} was created by {InputSanitizer.SanitizeUsername(client.User.Username)}.", "Success");
|
||||
}
|
||||
|
||||
private async Task HandleDeleteChannelAsync(ConnectedClient client, string channelId, CancellationToken ct)
|
||||
|
|
@ -819,7 +840,7 @@ public class ChatWebSocketManager
|
|||
|
||||
await BroadcastChannelListAsync();
|
||||
await Task.WhenAll(_clients.Values.Select(c => SendFileListToClientAsync(c, ct)));
|
||||
await BroadcastSystemNoticeAsync($"Channel #{channel.Name} was deleted.", "Warning");
|
||||
await BroadcastSystemNoticeAsync($"Channel #{InputSanitizer.SanitizeChannelName(channel.Name)} was deleted.", "Warning");
|
||||
}
|
||||
|
||||
private async Task HandleCommandAsync(ConnectedClient client, ExecuteCommandPacket packet, CancellationToken ct)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue