DJT Software

DJT Software Logo
Checking the contents of a file

FileSigCheck – Validate file contents

What is it?

A free and open source .NET library I have created to check file headers to see if they contain what they say they do.

What does it do?

The FileSigCheck library checks the initial part of a file, also known as the file header, for a pattern which helps determine the type of contents.  This helps to provide a level of additional protection against the upload of malicious files onto a computer system.

How does it work?

The file header of specific files follow a pattern.  For example, PNG images always start with the following 8 bytes:

0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A

By reading the first 8 bytes of any image, we can determine if it ‘looks like’ a PNG file or not.  We can do the same for other image types, audio and video too!

There are some limitations.  Some file types don’t have headers, such a pure text files from notepad.

Using it in code

static readonly string[] fileExtensions = { ".pdf", ".jpg", ".jpeg", ".png" };

public async Task<IActionResult> UploadImage([FromForm]IFormFile file)
{
    var ext = Path.GetExtension(file.FileName);

    /* Check the file extension in permissible file types */
    if(!fileExtensions.Contains(ext))
    {
        return StatusCode(StatusCodes.Status415UnsupportedMediaType);
    }
    /* Get the file data */
    using (var rs = file.OpenReadStream())
    {
        /* perform check  */
        if (!FileSignatureUtil.IsFileSignatureValid(rs, fileExtensions))
        {
            ModelState.AddModelError("File", $"Is not recognised as a {ext} file.");
            return BadRequest(ModelState);
        }

        /* Then do what you would normally do with that file... */
    }

    return Ok();
}
 

Where can I get it?

FileSigCheck is available as a NuGet package, alternatively you can build, fork or contribute to the source code here.