.NET virus scanning API

C#.NetApiAntivirus

C# Problem Overview


I'm building a web application in which I need to scan the user-uploaded files for viruses.

Does anyone with experience in building something like this can provide information on how to get this up and running? I'm guessing antivirus software packages have APIs to access their functionality programatically, but it seems it's not easy to get a hand on the details.

FYI, the application is written in C#.

C# Solutions


Solution 1 - C#

Important note before use: Be aware of TOS agreement. You give them full access to everything: "When you upload or otherwise submit content, you give VirusTotal (and those we work with) a worldwide, royalty free, irrevocable and transferable licence to use, edit, host, store, reproduce, modify, create derivative works, communicate, publish, publicly perform, publicly display and distribute such content."

Instead of using a local Antivirus program (and thus binding your program to that particular Antivirus product and requesting your customers to install that Antivirus product) you could use the services of VirusTotal.com

This site provides a free service in which your file is given as input to numerous antivirus products and you receive back a detailed report with the evidences resulting from the scanning process. In this way your solution is no more binded to a particular Antivirus product (albeit you are binded to Internet availability)

The site provides also an Application Programming Interface that allows a programmatically approach to its scanning engine.

Here a VirusTotal.NET a library for this API
Here the comprensive documentation about their API
Here the documentation with examples in Python of their interface

And because no answer is complete without code, this is taken directly from the sample client shipped with the VirusTotal.NET library

static void Main(string[] args)
{
    VirusTotal virusTotal = new VirusTotal(ConfigurationManager.AppSettings["ApiKey"]);

    //Use HTTPS instead of HTTP
    virusTotal.UseTLS = true;

    //Create the EICAR test virus. See http://www.eicar.org/86-0-Intended-use.html
    FileInfo fileInfo = new FileInfo("EICAR.txt");
    File.WriteAllText(fileInfo.FullName, @"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*");

    //Check if the file has been scanned before.
    FileReport fileReport = virusTotal.GetFileReport(fileInfo);

    bool hasFileBeenScannedBefore = fileReport.ResponseCode == ReportResponseCode.Present;

    Console.WriteLine("File has been scanned before: " + (hasFileBeenScannedBefore ? "Yes" : "No"));

    //If the file has been scanned before, the results are embedded inside the report.
    if (hasFileBeenScannedBefore)
    {
        PrintScan(fileReport);
    }
    else
    {
        ScanResult fileResult = virusTotal.ScanFile(fileInfo);
        PrintScan(fileResult);
    }
    ... continue with testing a web site ....

}

DISCLAIMER
I am in no way involved with them. I am writing this answer just because it seems to be a good update for these 4 years old answers.

Solution 2 - C#

You can use IAttachmentExecute API.

> Windows OS provide the common API to calling the anti virus software which is installed (Of course, the anti virus software required support the API). But, the API to calling the anti virus software provide only COM Interface style, not supported IDispatch. So, calling this API is too difficult from any .NET language and script language.

Download this library from here Anti Virus Scanner for .NET or add reference your VS project from "NuGet" AntiVirusScanner

For example bellow code scan a file :

var scanner = new AntiVirus.Scanner();
var result = scanner.ScanAndClean(@"c:\some\file\path.txt");
Console.WriteLine(result); // console output is "VirusNotFound".

Solution 3 - C#

I would probably just make a system call to run an independent process to do the scan. There are a number of command-line AV engines out there from various vendors.

Solution 4 - C#

Take a look at the Microsoft Antivirus API. It makes use of COM, which should be easy enough to interface with from .NET. It refers specifically to Internet Explorer and Microsoft Office, but I don't see why you wouldn't be able to use to to on-demand scan any file.

All modern scanners that run on Windows should understand this API.

Solution 5 - C#

Various Virus scanners do have API's. One I have integrated with is Sophos. I am pretty sure Norton has an API also while McAfee doesn't (it used to). What virus software do you want to use? You may want to check out Metascan as it will allow integration with many different scanners, but there is an annual license cost. :-P

Solution 6 - C#

Shameless plug but you might want to check out https://scanii.com, it's basically malware/virus detection as a (REST) service. Oh also, make sure you read and understand virustotal's API terms (https://www.virustotal.com/en/documentation/public-api/) - they are very clear about not allowing commercial usage.

Solution 7 - C#

I also had this requirement. I used clamAv anti virus which provides on-demand scanning by sending the file to their tcp listening port. You can use nClam nuget package to send files to clamav.

var clam = new ClamClient("localhost", 3310);
var scanResult = clam.ScanFileOnServerAsync("C:\\test.txt"); //any file you would like!
switch (scanResult.Result.Result)
{
    case ClamScanResults.Clean:
        Console.WriteLine("The file is clean!");
        break;
    case ClamScanResults.VirusDetected:
        Console.WriteLine("Virus Found!");
        Console.WriteLine("Virus name: {0}", scanResult.Result.InfectedFiles[0].FileName);
        break;
    case ClamScanResults.Error:
        Console.WriteLine("Woah an error occured! Error: {0}", scanResult.Result.RawResult);
        break;
}

A simple and detailed example is shown here. Note:- The synchronous scan method is not available in the latest nuget. You have to code like I done above

For testing a virus you can use the below string in a txt file

> X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*

Solution 8 - C#

I would recommend using this approach:

using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.VirusScan.Api;
using Cloudmersive.APIClient.NET.VirusScan.Client;
using Cloudmersive.APIClient.NET.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, Pythong 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 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, restrictFileTypes);
                Debug.WriteLine(result);
            }
            catch (Exception e)
            {
                Debug.Print("Exception when calling ScanApi.ScanFileAdvanced: " + e.Message );
            }
        }
    }
}

Note that this way you can even control whether you filter out non-virus threat payloads such as executables, scripts, encrypted/password-protected files, etc.

This approach has a free tier and can also validate the contents of the files that you upload.

Solution 9 - C#

You can try to use DevDragon.io.

It is a web service with an API and .NET client DevDragon.Antivirus.Client you can get from NuGet. Scans are sub 200ms for 1MB file.

More documentation here: https://github.com/Dev-Dragon/Antivirus-Client

Disclosure: I work for them.

Solution 10 - C#

From my experience you can use COM for interfacing with some anti-virus software. But what I would suggest is a bit easier, just parse scan results after scanning. All you need to do is to start the scanner process and point it to file/folder you want to scan, store scan results into file or redirect stdout to your application and parse results.

Solution 11 - C#

//Scan  
string start = Console.ReadLine();  
System.Diagnostics.Process scanprocess = new System.Diagnostics.Process();  
sp.StartInfo.WorkingDirectory = @"<location of your antivirus>";  
sp.StartInfo.UseShellExecute = false;  
sp.StartInfo.FileName = "cmd.exe";  
sp.StartInfo.Arguments = @"/c antivirusscanx.exe /scan="+filePath;  
sp.StartInfo.CreateNoWindow = true;  
sp.StartInfo.RedirectStandardInput = true;    
sp.StartInfo.RedirectStandardError = true; sp.Start();  
string output = sp.StandardOutput.ReadToEnd();  
//Scan results  
System.Diagnostics.Process pr = new System.Diagnostics.Process();      
pr.StartInfo.FileName = "cmd.exe";  
pr.StartInfo.Arguments = @"/c echo %ERRORLEVEL%";   
pr.StartInfo.RedirectStandardInput = true;    
pr.StartInfo.RedirectStandardError = true; pr.Start();  
output = processresult.StandardOutput.ReadToEnd();  
pr.Close(); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFarinhaView Question on Stackoverflow
Solution 1 - C#SteveView Answer on Stackoverflow
Solution 2 - C#FredView Answer on Stackoverflow
Solution 3 - C#JoeView Answer on Stackoverflow
Solution 4 - C#ThorarinView Answer on Stackoverflow
Solution 5 - C#CraigView Answer on Stackoverflow
Solution 6 - C#Rafael FerreiraView Answer on Stackoverflow
Solution 7 - C#BeingninView Answer on Stackoverflow
Solution 8 - C#A XView Answer on Stackoverflow
Solution 9 - C#AndrewView Answer on Stackoverflow
Solution 10 - C#msuvajacView Answer on Stackoverflow
Solution 11 - C#Priya PremkumarView Answer on Stackoverflow