How to Scan a File for Malicious Content in C# .NET Core

Cloudmersive
4 min readMay 30, 2024

--

In addition to virus scanning client-side file uploads, it’s critically important that we verify the contents of file uploads entering our storage servers.

That doesn’t mean simply checking file extensions, either — it’s all too easy to create “spoofed” files that pass file extension verification checks.

When we verify file content in depth, we can detect all kinds of threats — including hidden executables, scripts, macros, and other extremely dangerous content types.

Files containing malicious code and other threatening content can cause just as much damage as viruses and malware can, and they’re often custom-made for targeted attacks, making them harder to detect.

Writing code to create a content verification workflow isn’t at all straightforward, of course. It’s far simpler to incorporate an API into our workflow that abstracts complex deterministic threat scanning away from our server and returns the information we need to make decisions on suspicious files.

Using the below code, we can easily take advantage of a free API that simultaneously performs a deterministic content verification scan AND a signature-based virus and malware scan on a wide range of file types. We can incorporate this API into our C# .NET Core file upload form handler to screen threats out of our upload workflow.

We can install the client SDK via NuGet by running the following command in our Package Manager console:

Install-Package Cloudmersive.APIClient.NETCore.VirusScan -Version 2.0.4

Next, we can quickly turn our attention to authorization. We’ll need a free API key to authorize our requests (this will allow us to make up to 800 API calls per month with zero additional commitments).

With our API key ready, we can use the remaining code examples to add our namespace imports and call our threat scanning function. We can replace the “YOUR_API_KEY” placeholder text with our own API key string:

using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NETCore.VirusScan.Api;
using Cloudmersive.APIClient.NETCore.VirusScan.Client;
using Cloudmersive.APIClient.NETCore.VirusScan.Model;

namespace Example
{
public class ScanFileAdvancedExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");

var apiInstance = new ScanApi();
var inputFile = new System.IO.FileStream("C:\\temp\\inputfile", System.IO.FileMode.Open); // System.IO.Stream | Input file to perform the operation on.
var allowExecutables = true; // bool? | Set to false to block executable files (program code) from being allowed in the input file. Default is false (recommended). (optional)
var allowInvalidFiles = true; // bool? | Set to false to block invalid files, such as a PDF file that is not really a valid PDF file, or a Word Document that is not a valid Word Document. Default is false (recommended). (optional)
var allowScripts = true; // bool? | Set to false to block script files, such as a PHP files, Python scripts, and other malicious content or security threats that can be embedded in the file. Set to true to allow these file types. Default is false (recommended). (optional)
var allowPasswordProtectedFiles = true; // bool? | Set to false to block password protected and encrypted files, such as encrypted zip and rar files, and other files that seek to circumvent scanning through passwords. Set to true to allow these file types. Default is false (recommended). (optional)
var allowMacros = true; // bool? | Set to false to block macros and other threats embedded in document files, such as Word, Excel and PowerPoint embedded Macros, and other files that contain embedded content threats. Set to true to allow these file types. Default is false (recommended). (optional)
var allowXmlExternalEntities = true; // bool? | Set to false to block XML External Entities and other threats embedded in XML files, and other files that contain embedded content threats. Set to true to allow these file types. Default is false (recommended). (optional)
var allowInsecureDeserialization = true; // bool? | Set to false to block Insecure Deserialization and other threats embedded in JSON and other object serialization files, and other files that contain embedded content threats. Set to true to allow these file types. Default is false (recommended). (optional)
var allowHtml = true; // bool? | Set to false to block HTML input in the top level file; HTML can contain XSS, scripts, local file accesses and other threats. Set to true to allow these file types. Default is false (recommended) [for API keys created prior to the release of this feature default is true for backward compatability]. (optional)
var restrictFileTypes = restrictFileTypes_example; // string | Specify a restricted set of file formats to allow as clean as a comma-separated list of file formats, such as .pdf,.docx,.png would allow only PDF, PNG and Word document files. All files must pass content verification against this list of file formats, if they do not, then the result will be returned as CleanResult=false. Set restrictFileTypes parameter to null or empty string to disable; default is disabled. (optional)

try
{
// Advanced Scan a file for viruses
VirusScanAdvancedResult result = apiInstance.ScanFileAdvanced(inputFile, allowExecutables, allowInvalidFiles, allowScripts, allowPasswordProtectedFiles, allowMacros, allowXmlExternalEntities, allowInsecureDeserialization, allowHtml, restrictFileTypes);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ScanApi.ScanFileAdvanced: " + e.Message );
}
}
}
}

We can play around with threat rule variables in our function to allow or disallow certain types of content in our workflow. We can also leverage var restrictFileTypes to whitelist acceptable file extensions in our upload process (e.g., ‘.pdf,.docx,.xlsx’) and categorically block all other file types.

Now we can easily detect and block a wide range of content threats using just a few lines of C# code.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.