Some fixes and security updates

This commit is contained in:
tyuXX 2026-10-24 14:53:10 +03:00
parent 43acf366af
commit 68e6fa2353
22 changed files with 1114 additions and 58 deletions

View file

@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Threading.Tasks;
@ -14,6 +15,21 @@ public class FileStorageService
private readonly ServerOptions _options;
private readonly string _filesDirectory;
// Whitelist of allowed MIME types
private static readonly HashSet<string> AllowedContentTypes = new(StringComparer.OrdinalIgnoreCase)
{
// Images
"image/jpeg", "image/png", "image/gif", "image/webp", "image/svg+xml",
// Documents
"application/pdf", "text/plain", "text/csv", "application/octet-stream",
// Archives
"application/zip", "application/x-rar-compressed", "application/x-7z-compressed",
// Audio
"audio/mpeg", "audio/wav", "audio/ogg",
// Video
"video/mp4", "video/webm", "video/quicktime"
};
public FileStorageService(ChatDatabase db, ServerOptions options)
{
_db = db;
@ -22,6 +38,16 @@ public class FileStorageService
Directory.CreateDirectory(_filesDirectory);
}
private bool IsContentTypeAllowed(string contentType)
{
if (string.IsNullOrWhiteSpace(contentType))
{
return false;
}
return AllowedContentTypes.Contains(contentType.Trim());
}
public async Task<FileRecord> StoreFileAsync(
string channelId,
string uploaderId,
@ -60,12 +86,21 @@ public class FileStorageService
throw new InvalidOperationException($"File exceeds maximum allowed size of {_options.MaxFileSizeMb} MB.");
}
// Validate content type
if (!IsContentTypeAllowed(contentType))
{
throw new InvalidOperationException($"File type '{contentType}' is not allowed.");
}
string safeName = Path.GetFileName(originalFileName);
if (string.IsNullOrWhiteSpace(safeName))
{
safeName = "unnamed_file.bin";
}
// Sanitize filename
safeName = InputSanitizer.SanitizeForDisplay(safeName, 255);
string fileId = Guid.NewGuid().ToString("N");
string diskFileName = $"{fileId}_{safeName}";
string diskFilePath = Path.Combine(_filesDirectory, diskFileName);