Look signature for file type

This commit is contained in:
Dominic Villemure
2024-07-10 01:51:08 -04:00
parent d2c6209954
commit df55125c48
2 changed files with 24 additions and 3 deletions

View File

@@ -44,7 +44,7 @@ public class AzureBlobStorageService : IAzureBlobStorageService
} }
// Validate content type // Validate content type
if (!ContentTypes.IsAllowed(contentType)) if (!ContentTypes.IsAllowed(contentType, memoryStream))
{ {
_logger.LogInformation($"Blob storage: Unsupported file type {contentType}. Only PNG and JPEG are allowed."); _logger.LogInformation($"Blob storage: Unsupported file type {contentType}. Only PNG and JPEG are allowed.");
throw new InvalidOperationException("Unsupported file type. Only PNG and JPEG are allowed."); throw new InvalidOperationException("Unsupported file type. Only PNG and JPEG are allowed.");

View File

@@ -8,8 +8,29 @@ public static class ContentTypes
public static HashSet<string> AllowedContentTypes = new HashSet<string> { ImagePng, ImageJpeg, ImageJpg }; public static HashSet<string> AllowedContentTypes = new HashSet<string> { ImagePng, ImageJpeg, ImageJpg };
public static bool IsAllowed(string contentType) public static bool IsAllowed(string contentType, Stream fileStream)
{ {
return AllowedContentTypes.Contains(contentType); return IsValidFileType(fileStream) && AllowedContentTypes.Contains(contentType);
}
private static bool IsValidFileType(Stream fileStream)
{
byte[] buffer = new byte[4];
fileStream.Read(buffer, 0, buffer.Length);
fileStream.Position = 0;
// PNG file signature: 89 50 4E 47 (in hex)
if (buffer[0] == 0x89 && buffer[1] == 0x50 && buffer[2] == 0x4E && buffer[3] == 0x47)
{
return true;
}
// JPEG file signature: FF D8 FF (in hex)
if (buffer[0] == 0xFF && buffer[1] == 0xD8 && buffer[2] == 0xFF)
{
return true;
}
return false;
} }
} }