.NET virus scanning API [closed]
Asked Answered
O

12

60

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#.

Ozuna answered 10/6, 2009 at 11:46 Comment(2)
Check this question. It should be of some help.Giffie
This one is really solid and is free actually: cloudmersive.com/virus-apiSynthetic
I
9

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.

Interclavicle answered 10/6, 2009 at 11:58 Comment(2)
Things may have changed in the 6 YEARS since I posted thisInterclavicle
-Well, Joe, maybe they did -- But couldn't you just do something like var result = process.Start(); and then MessageBox.Show(result);, after doing stuff like process.StartInfo? :DSalmagundi
K
20

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.

Karyolysis answered 7/2, 2015 at 19:45 Comment(5)
This looks like the real answer.Assignat
Be mindful that VirusTotal solution non-commercial. They won't allow the API's to be used in commercial applications.Exanimate
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."Unfortunate
Yes that's seems important. But do you give them your work to scan for viruses?. All in all I am not sure if this is a real problem or not. Anyway good to know.Karyolysis
Contacted them this week. You can pay for a premium service to use for commercial purposes. However in addition to what others say they responded to me saying that they should not be used as the only means of verifying a file and should be considered a 2nd opinion. In these GDPR days combined with their reply to me they are affectively not useable for the original posters (and mine) situation.Consolation
D
18

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".
Dynel answered 28/2, 2016 at 15:12 Comment(9)
Thanks! The thing that make this solution better than the others is that it is completely generic in a way that it uses a single interface to communicate with any AV software installed on the machine. Also, it requires no internet connection which is a plus.Eckblad
My PC install AVG Free , Can i use AntiVirusScanner?Clara
I tested, but it can't scan by AV software had installed in PC.Clara
@DT Anti virus application must be supporte IAttachmentExecute API. I don't know that AVG anti virus support IAttachmentExecute. you can test this solution by Microsoft Security Essentials, Microsoft Windows Defender, ESET NOD32Dynel
I try install Microsoft Security Essentials, but result scan by Microsoft Security Essentials not the same check by dll. file .bat, .exe -> always is virus.Clara
Chrome warns me that the first link is dangerous.Raylenerayless
@EdwinStoteler It is Codeplex site and this warning is about https certificate expiration, don't worryDynel
I tried this solution on several files that the defender and ESET treated as virus- and the answer is always VirusNotFound!!! Is something wrong with this package?! This worked for you???Almaalmaata
will that work if the file is not yet residing on the server?Syriac
I
9

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.

Interclavicle answered 10/6, 2009 at 11:58 Comment(2)
Things may have changed in the 6 YEARS since I posted thisInterclavicle
-Well, Joe, maybe they did -- But couldn't you just do something like var result = process.Start(); and then MessageBox.Show(result);, after doing stuff like process.StartInfo? :DSalmagundi
J
6

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.

Judicator answered 10/6, 2009 at 12:23 Comment(2)
I beleive that API is for C++ not .net.Wiley
It uses COM. Which means you can use it from .NETJudicator
S
4

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

Saguaro answered 10/6, 2009 at 12:23 Comment(0)
P
4

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*

Patrimony answered 24/7, 2018 at 9:39 Comment(0)
O
2

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.

Oster answered 22/6, 2015 at 5:35 Comment(6)
Which you can't use if the file could contain sensitive data. Contacting them this week they say you can't even use them as AV, only as a second opinion. Thus useless in these days of GDPR.Consolation
if using scanii.com involves sending the file to the REST API then it is also not really GDPR compliant if the file contains sensitive data. You'd be sending the sensitive file to a 3rd party that is out of your control. I suppose if scanii guaranteed that everything is secured by using their service and not accessible by any of their employees and is not stored and the site using it got consent from their users to send the sensitive files to scanii then then and only then would it be fully covered.Consolation
[Original comment deleted due to an embarrassing typo] Here's our GDPR support article for future reference: support.scanii.com/article/48-gdpr-complianceOster
I read that page and the privacy shield policy it links to but no where does it mention what you do with the files sent for scanning or how you guarantee that they will only be kept for the length of time it takes to scan them nor does it guarantee that nobody could access the files sent to you. All it talks about is about the rights of the person/company using your service.Consolation
Peter, that kind of information wouldn't be in the privacy policy, for that, check out our tos, particularly under "data ownership": docs.scanii.com/tos.html. The real icing on the cake here is our security overview (docs.scanii.com/security-overview.html) which clearly spells out how our systems work and our data sovereignty commitment.Oster
There are other commercial options now, including Verisys Antivirus API and a Trend Micro offeringZurek
S
2

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.

Synthetic answered 15/7, 2020 at 2:25 Comment(0)
F
1

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.

Fineable answered 8/2, 2018 at 20:19 Comment(0)
S
1

We tried two options:

  1. clamav-daemon installed on a tiny linux container + "nClam" .NET library to interact with it. Works fine, but Clam AV misses a lot (a lot!) of viruses, especially dangerous macros hidden in MS Office files. Also ClamAV virus database has to be kept in memory at all times, which uses around 3.5GB of memory, which requires a rather expensive cloud virtual machine.

  2. Ended up using Windows Defender via MpCmdRun.exe CLI api. See answer here

Syndic answered 9/6, 2022 at 9:35 Comment(0)
P
-1

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.

Pathogenic answered 10/6, 2009 at 12:1 Comment(0)
R
-3
//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(); 
Residency answered 7/2, 2015 at 23:20 Comment(1)
Could you write a detailed explanation here? Where would I find antivirusscanx.exe for instance?Assignat

© 2022 - 2024 — McMap. All rights reserved.