From df55125c48d17e9c7d467280be33d549ae12fb0f Mon Sep 17 00:00:00 2001 From: Dominic Villemure Date: Wed, 10 Jul 2024 01:51:08 -0400 Subject: [PATCH] Look signature for file type --- .../AzureBlob/AzureBlobStorageService.cs | 2 +- src/Infrastructure/AzureBlob/ContentTypes.cs | 25 +++++++++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/Infrastructure/AzureBlob/AzureBlobStorageService.cs b/src/Infrastructure/AzureBlob/AzureBlobStorageService.cs index a7598a7..8f12630 100644 --- a/src/Infrastructure/AzureBlob/AzureBlobStorageService.cs +++ b/src/Infrastructure/AzureBlob/AzureBlobStorageService.cs @@ -44,7 +44,7 @@ public class AzureBlobStorageService : IAzureBlobStorageService } // 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."); throw new InvalidOperationException("Unsupported file type. Only PNG and JPEG are allowed."); diff --git a/src/Infrastructure/AzureBlob/ContentTypes.cs b/src/Infrastructure/AzureBlob/ContentTypes.cs index ae4261b..2637fc9 100644 --- a/src/Infrastructure/AzureBlob/ContentTypes.cs +++ b/src/Infrastructure/AzureBlob/ContentTypes.cs @@ -8,8 +8,29 @@ public static class ContentTypes public static HashSet AllowedContentTypes = new HashSet { 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; } }