Scanning Uploaded Files for Malware in C#

This blog is presented as a part of C# Advent 2023. Follow the link to check out the rest of the excellent C# and .NET content coming out as 2 blogs per day between December 1 - 25.

With cyber threats multiplying daily, it can be overwhelming to try to stay on top of security in our software applications. When faced with the daunting task of writing code to mitigate the risk of malware, viruses, and other types of threats, many developers don’t know where to start.

One critical skill of developers working on applications that work with external files is knowing how to scan those files for malicious code. In this blog post, I will show a tool called VirusTotal and how you can use it in your applications to detect malicious files.

Risks of Unscanned File Uploads

Allowing users to upload files without scanning them first opens up significant risks. Hackers could potentially upload malware, viruses, or other malicious files that attack the application and its users once uploaded.

For example, an attacker may upload a virus-infected image or PDF that infects the application’s servers when processed. Or a hacker could upload a web shell script that gives them remote code execution abilities. Another infected image may be delivered to users’ browsers and used to steal their credentials or other private information

File Upload Guidelines

Without scanning uploaded files first, the application has no visibility into threats they may contain. To mitigate this risk, it’s essential for developers to build a process into their applications for verification of external files. Scanning uploads through a service like VirusTotal identifies malware before it enters the application, acting as a critical security control.

Below I will outline how to use VirusTotal, a popular tool for identifying and neutralizing malware in files. I will guide you step-by-step through the process of integrating it into your file upload code.

Utilizing VirusTotal API for File Scanning

VirusTotal is an API that helps users identify malicious software in files. It uses a technique known as hashing to search for the presence of suspicious files, meaning it essentially creates unique identifiers or “fingerprints” from inputted data.

The power of VirusTotal lies in its ability to provide an exceptional level of detail into vulnerabilities being exploited by attackers and what kind of malware they may be deploying. Additionally, it offers both free and paid tiers, which makes this handy tool accessible to companies facing security-related issues regardless of size or budget.

Interpreting API Responses

API responses from VirusTotal require proper interpretation to extract meaningful information. Typically, the responses come in JSON format which can be easily deserialized in your C# code.

An API file report contains information from various antivirus engines and their detection status. You can check each engine’s detection status and engine version to understand how they flagged the submitted file, like malware, adware, or clean.

Furthermore, the API returns summary details, such as positives (number of engines detecting the file as malicious) and total (total number of engines used). These details help assess the overall security status of the file. Always consider a balance between false positives and true detection when interpreting the responses.

API Rate Limiting

VirusTotal imposes rate limiting on API requests. Public API users are limited to 4 requests per minute and 500 daily requests, while premium and private accounts come with higher, custom limits. It is vital to respect these limits when building your C# virus file checker.

To manage rate limiting in your application, consider implementing a queuing mechanism that schedules and prioritizes your API requests. It might also be good to cache the results for a specific file by hashing that file’s contents and caching the scan results attached to that hash value. That way you can avoid re-scanning the same file multiple times.

Demo Project

Below is a simple demo containing two endpoints, one for file upload and one for checking reports. The solution structure looks like the following.

...
// Client Factory
src.AddHttpClient<IFileChecker, FileChecker>(client =>
{
    client.BaseAddress = new Uri("https://www.virustotal.com/api/v3");
    client.DefaultRequestHeaders.Add("x-apikey", "[YOUR_API_KEY]");
});
var app = builder.Build();

app.MapPost("/api/file-upload", [AllowAnonymous] async
        ([FromServices] IFileChecker fileCheckerService, IFormFile formFile, CancellationToken ct) =>
    {
        var referenceReport = await fileCheckerService.UploadFileAsync(formFile, ct);
        return TypedResults.Ok(referenceReport);
    })
    .DisableAntiforgery();

app.MapGet("/api/file-report/{fileReference}", [AllowAnonymous] async
        ([FromServices] IFileChecker fileCheckerService,string fileReference, CancellationToken ct) =>
    {
        var referenceReport = await fileCheckerService.GetFileReportAsync(fileReference,ct);
        return TypedResults.Ok(referenceReport);
    })
    .DisableAntiforgery();
...

First in Program.cs we are adding typed HttpClient with BaseAddress, and according to VirusTotal documentation, we need to add the header key “x-apikey” for authentication.

Next, we have two endpoints:

  • /api/file-upload
  • /api/file-report/{fileReference}

Endpoint file-upload is meant for uploading files and asynchronously starts a scan of it in VirusTotal. The endpoint file-report/{fileReference} is intended for retrieving the report that VirsuTotal generates when its scan completes.

FileChecker class

public class FileChecker : IFileChecker
{
    private readonly HttpClient _httpClient;

    public FileChecker(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<VirusTotalFileUploadRes> UploadFileAsync(IFormFile file, CancellationToken ct)
    {
        var request = new HttpRequestMessage(HttpMethod.Post, _httpClient.BaseAddress + "/files");
        request.Content = new MultipartFormDataContent
        {
            { new StreamContent(file.OpenReadStream()), "file", file.FileName }
        };

        var res = await _httpClient.PostAsync(request.RequestUri, request.Content, ct);
        res.EnsureSuccessStatusCode();

        // Example of Response
        // {
        //     "data": {
        //         "type": "analysis",
        //         "id": "ZjU1ZjdmODcyMGU1NzJiNDQ0MWJjNjgyMTViMzA2Yzg6MTcwMjEzOTMxOA==",
        //         "links": {
        //             "self": "https://www.virustotal.com/api/v3/analyses/ZjU1ZjdmODcyMGU1NzJiNDQ0MWJjNjgyMTViMzA2Yzg6MTcwMjEzOTMxOA=="
        //         }
        //     }
        // }
        var data = JsonSerializer.Deserialize<VirusTotalFileUploadRes>(await res.Content.ReadAsStringAsync(ct));

        return data;
    }

    public async Task<VirusTotalFileReportRes> GetFileReportAsync(string fileReference, CancellationToken ct)
    {
        var request = new HttpRequestMessage(HttpMethod.Get, _httpClient.BaseAddress + $"/analyses/{fileReference}");

        var res = await _httpClient.GetAsync(request.RequestUri, ct);
        res.EnsureSuccessStatusCode();
        
        var data = JsonSerializer.Deserialize<VirusTotalFileReportRes>(await res.Content.ReadAsStringAsync(ct));

        return data;
    }
}

From the code above, you can see two methods that are used UploadFileAsync and GetFileReportAsync.

Once the file is uploaded, it is queued for analysis by VirusTotal. Sadly, there is currently no callback support, so you will need to poll for results, which you will know based on when the status is completed.

An example of the response once scanning is completed looks like this

{
    "meta": {
        "file_info": {
            "size": 29700,
            "sha1": "d3a858cb5718b2c624146bd48c9b578a7f02bbba",
            "sha256": "3cba1b837791adb42f1fe92c68ff9a94c5c68c4c752b4a9cf783b991114d9ca1",
            "md5": "17c6028c94dbea93a309bfb4e34fd2a9"
        }
    },
    "data": {
        "attributes": {
            "date": 1702155104,
            "status": "completed",
            "stats": {
                "harmless": 0,
                "type-unsupported": 16,
                "suspicious": 0,
                "confirmed-timeout": 0,
                "timeout": 0,
                "failure": 0,
                "malicious": 0,
                "undetected": 60
            },
            "results": {
                "Bkav": {
                    "category": "undetected",
                    "engine_name": "Bkav",
                    "engine_version": "2.0.0.1",
                    "result": null,
                    "method": "blacklist",
                    "engine_update": "20231209"
                }
// Rest of checkers are here         
            }
        },
        "type": "analysis",
        "id": "f-3cba1b837791adb42f1fe92c68ff9a94c5c68c4c752b4a9cf783b991114d9ca1-1702155104",
        "links": {
            "item": "https://www.virustotal.com/api/v3/files/3cba1b837791adb42f1fe92c68ff9a94c5c68c4c752b4a9cf783b991114d9ca1",
            "self": "https://www.virustotal.com/api/v3/analyses/f-3cba1b837791adb42f1fe92c68ff9a94c5c68c4c752b4a9cf783b991114d9ca1-1702155104"
        }
    }
}

In this response, we are primarily interested in the stats section. In this section, we can find the summarized testing results and determine whether we should allow the file to be uploaded or not.

Conclusion

Integrating VirusTotal into C# projects is easy and ensures the security of your applications dealing with external files. By utilizing a virus scanning tool, you ensure all the files processed through your application are free of malware and can rest assured that it is not vulnerable to this type of potential online threat.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.