Skip to content

ByteGuard File Validator is a security-focused .NET library for validating user-supplied files, providing a configurable API to help you enforce safe and consistent file handling across your applications.

License

Notifications You must be signed in to change notification settings

ByteGuard-HQ/byteguard-file-validator-net

Repository files navigation

ByteGuard File Validator NuGet Version

ByteGuard.FileValidator is a lightweight security-focused library for validating user-supplied files in .NET applications.
It helps you enforce consistent file upload rules by checking:

  • Allowed file extensions
  • File size limits
  • File signatures (magic numbers) to detect spoofed types
  • Specification conformance for Office Open XML / Open Document Formats (.docx, .xlsx, .pptx, .odt)
  • Malware scan result using a varity of scanners (requires the addition of a specific ByteGuard.FileValidator scanner package)

⚠️ Important: This package is one layer in a defense-in-depth strategy.
It does not replace endpoint protection, sandboxing, input validation, or other security controls.

Features

  • ✅ Validate files by extension
  • ✅ Validate files by size
  • ✅ Validate files by signature (magic-numbers)
  • ✅ Validate files by specification conformance for archive-based formats (Open XML and Open Document Formats)
  • Ensure no malware through a variety of antimalware scanners
  • ✅ Validate using file path, Stream, or byte[]
  • ✅ Configure which file types to support
  • ✅ Configure whether to throw exceptions or simply return a boolean
  • Fluent configuration API for easy setup

Getting Started

Installation

This package is published and installed via NuGet.

Reference the package in your project:

dotnet add package ByteGuard.FileValidator

Antimalware scanners

In order to use the antimalware scanning capabilities, ensure you have a ByteGuard.FileValidator antimalware package referenced as well. Youo can find the relevant scanner package on NuGet under the namespace ByteGuard.FileValidator.Scanners.

Usage

Basic validation

// Without antimalware scanner
var configuration = new FileValidatorConfiguration
{
  SupportedFileTypes = [FileExtensions.Pdf, FileExtensions.Jpg, FileExtensions.Png],
  FileSizeLimit = ByteSize.MegaBytes(25),
  ThrowExceptionOnInvalidFile = false
};

var fileValidator = new FileValidator(configuration);
var isValid = fileValidator.IsValidFile("example.pdf", fileStream);

// With antimalware
var antimalwareScanner = AntimalwareScannerImplementation();
var fileValidator = new FileValidator(configuration, antimalwareScanner);
var isValid = fileValidator.IsValidFile("example.pdf", fileStream);

Using the fluent builder

var configuration = new FileValidatorConfigurationBuilder()
  .AllowFileTypes(FileExtensions.Pdf, FileExtensions.Jpg, FileExtensions.Png)
  .SetFileSizeLimit(ByteSize.MegaBytes(25))
  .SetThrowExceptionOnInvalidFile(false)
  .Build();

var fileValidator = new FileValidator(configuration);
var isValid = fileValidator.IsValidFile("example.pdf", fileStream);

Validating specific aspects

The FileValidator class provides methods to validate specific aspects of a file.

⚠️ It’s recommended to use IsValidFile for comprehensive validation.

IsValidFile performs, in order:

  1. Extension validation
  2. File size validation
  3. Signature (magic-number) validation
  4. Optional Open XML / Open Document Format specification conformance validation (for supported types)
  5. Optional antimalware scanning with a compatible scanning package
bool isExtensionValid = fileValidator.IsValidFileType(fileName);
bool isFileSizeValid = fileValidator.HasValidSize(fileStream);
bool isSignatureValid = fileValidator.HasValidSignature(fileName, fileStream);
bool isOpenXmlValid = fileValidator.IsValidOpenXmlDocument(fileName, fileStream);
bool isOpenDocumentFormatValid = fileValidator.IsValidOpenDocumentFormat(fileName, fileStream);
bool isMalwareClean = fileValidator.IsMalwareClean(fileName, fileStream);

Example

[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
    using var stream = file.OpenReadStream();

    var antimalwareScanner = AntimalwareScannerImplementation();

    var configuration = new FileValidatorConfiguration
    {
        SupportedFileTypes = [FileExtensions.Pdf, FileExtensions.Docx],
        FileSizeLimit = ByteSize.MegaBytes(10),
        ThrowExceptionOnInvalidFile = false
    };

    var validator = new FileValidator(configuration, antimalwareScanner);

    if (!validator.IsValidFile(file.FileName, stream))
    {
        return BadRequest("Invalid or unsupported file.");
    }

    // Proceed with processing/saving...
    
    return Ok();
}

Supported File Extensions

The following file extensions are supported by the FileValidator:

  • .jpeg, .jpg
  • .pdf
  • .png
  • .bmp
  • .doc
  • .docx
  • .odt
  • .rtf
  • .xls
  • .xlsx
  • .pptx
  • .m4a
  • .mov
  • .avi
  • .mp3
  • .mp4
  • .wav

Validation coverage per type

IsValidFile always validates:

  • File extension (against SupportedFileTypes)
  • File size (against FileSizeLimit)
  • File signature (magic number)
  • Malware scan result (if an antimalware scanner has been configured)

For some formats, additional checks are performed:

  • Office Open XML / Open Document Format (.docx, .xlsx, .pptx, .odt):

    • Extension
    • File size
    • Signature
    • Specification conformance
    • Malware scan result
  • Other binary formats (e.g. images, audio, video such as .jpg, .png, .mp3, .mp4):

    • Extension
    • File size
    • Signature
    • Malware scan result

Configuration Options

The FileValidatorConfiguration supports:

Setting Required Default Description
SupportedFileTypes Yes N/A A list of allowed file extensions (e.g., .pdf, .jpg).
Use the predefined constants in FileExtensions for supported types.
FileSizeLimit Yes N/A Maximum permitted size of files.
Use the static ByteSize class provided with this package, to simplify your limit.
ThrowExceptionOnInvalidFile No true Whether to throw an exception on invalid files or return false.

Exceptions

When ThrowExceptionOnInvalidFile is set to true, validation functions will throw one of the appropriate exceptions defined below. However, when ThrowExceptionOnInvalidFile is set to false, all validation functions will either return true or false.

Exception type Scenario
EmptyFileException Thrown when the file content is null or empty, indicating a file without any content.
UnsupportedFileException Thrown when the file extension is not in the list of supported types.
InvalidFileSizeException Thrown when the file size exceeds the configured file size limit.
InvalidSignatureException Thrown when the file's signature does not match the expected signature for its type.
InvalidOpenXmlFormatException Thrown when the internal structure of an Open XML file is invalid (.docx, .xlsx, .pptx, etc.).
InvalidOpenDocumentFormatException Thrown when the specification conformance of an Open Document Format file is invalid (.odt, etc.).
MalwareDetectedException Thrown when the configured antimalware scanner detected malware in the file from a scan result.

When to use this package

  • ✅ Whenever you need consistent file validation rules across projects
  • ✅ When handling user uploads in APIs or web applications
  • ✅ When you want defense-in-depth against spoofed or malicious files

License

ByteGuard FileValidator is Copyright © ByteGuard Contributors - Provided under the MIT license.

About

ByteGuard File Validator is a security-focused .NET library for validating user-supplied files, providing a configurable API to help you enforce safe and consistent file handling across your applications.

Topics

Resources

License

Stars

Watchers

Forks